mqtt_client_misc.c
Go to the documentation of this file.
1 /**
2  * @file mqtt_client_misc.c
3  * @brief Helper functions for MQTT 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.8
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL MQTT_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "mqtt/mqtt_client.h"
39 #include "mqtt/mqtt_client_misc.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (MQTT_CLIENT_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Update MQTT client state
48  * @param[in] context Pointer to the MQTT client context
49  * @param[in] newState New state to switch to
50  **/
51 
53  MqttClientState newState)
54 {
55  //Switch to the new state
56  context->state = newState;
57 }
58 
59 
60 /**
61  * @brief Process MQTT client events
62  * @param[in] context Pointer to the MQTT client context
63  * @param[in] timeout Maximum time to wait before returning
64  * @return Error code
65  **/
66 
68 {
69  error_t error;
70  size_t n;
71 
72  //It is the responsibility of the client to ensure that the interval
73  //between control packets being sent does not exceed the keep-alive value
74  error = mqttClientCheckKeepAlive(context);
75 
76  //Check status code
77  if(!error)
78  {
79  //Check current state
80  if(context->state == MQTT_CLIENT_STATE_IDLE ||
81  context->state == MQTT_CLIENT_STATE_PACKET_SENT)
82  {
83  //Wait for incoming data
84  error = mqttClientWaitForData(context, timeout);
85 
86  //Check status code
87  if(!error)
88  {
89  //Initialize context
90  context->packet = context->buffer;
91  context->packetPos = 0;
92  context->packetLen = 0;
93  context->remainingLen = 0;
94 
95  //Start receiving the packet
97  }
98  }
99  else if(context->state == MQTT_CLIENT_STATE_RECEIVING_PACKET)
100  {
101  //Receive the incoming packet
102  error = mqttClientReceivePacket(context);
103 
104  //Check status code
105  if(!error)
106  {
107  //Process MQTT control packet
108  error = mqttClientProcessPacket(context);
109 
110  //Update MQTT client state
111  if(context->state == MQTT_CLIENT_STATE_RECEIVING_PACKET)
112  {
113  if(context->packetType == MQTT_PACKET_TYPE_INVALID)
114  {
116  }
117  else
118  {
120  }
121  }
122  }
123  }
124  else if(context->state == MQTT_CLIENT_STATE_SENDING_PACKET)
125  {
126  //Any remaining data to be sent?
127  if(context->packetPos < context->packetLen)
128  {
129  //Send more data
130  error = mqttClientSendData(context, context->packet + context->packetPos,
131  context->packetLen - context->packetPos, &n, 0);
132 
133  //Advance data pointer
134  context->packetPos += n;
135  }
136  else
137  {
138  //Save the time at which the message was sent
139  context->keepAliveTimestamp = osGetSystemTime();
140 
141  //Update MQTT client state
142  if(context->packetType == MQTT_PACKET_TYPE_INVALID)
143  {
145  }
146  else
147  {
149  }
150  }
151  }
152  }
153 
154  //Return status code
155  return error;
156 }
157 
158 
159 /**
160  * @brief Check keep-alive time interval
161  * @param[in] context Pointer to the MQTT client context
162  * @return Error code
163  **/
164 
166 {
167  error_t error;
168  systime_t time;
169  systime_t keepAlive;
170 
171  //Initialize status code
172  error = NO_ERROR;
173 
174  //In the absence of sending any other control packets, the client must
175  //send a PINGREQ packet
176  if(context->state == MQTT_CLIENT_STATE_IDLE ||
177  context->state == MQTT_CLIENT_STATE_PACKET_SENT)
178  {
179  //A keep-alive value of zero has the effect of turning off the keep
180  //alive mechanism
181  if(context->settings.keepAlive != 0)
182  {
183  //Get current time
184  time = osGetSystemTime();
185 
186  //Convert the keep-alive value to milliseconds
187  keepAlive = context->settings.keepAlive * 1000;
188 
189  //It is the responsibility of the client to ensure that the interval
190  //between control packets being sent does not exceed the keep-alive value
191  if(timeCompare(time, context->keepAliveTimestamp + keepAlive) >= 0)
192  {
193  //Format PINGREQ packet
194  error = mqttClientFormatPingReq(context);
195 
196  //Check status code
197  if(!error)
198  {
199  //Debug message
200  TRACE_INFO("MQTT: Sending PINGREQ packet (%" PRIuSIZE " bytes)...\r\n", context->packetLen);
201  TRACE_DEBUG_ARRAY(" ", context->packet, context->packetLen);
202 
203  //Point to the beginning of the packet
204  context->packetPos = 0;
205 
206  //Send PINGREQ packet
208  }
209  }
210  }
211  }
212 
213  //Return status code
214  return error;
215 }
216 
217 
218 /**
219  * @brief Serialize fixed header
220  * @param[in] buffer Pointer to the output buffer
221  * @param[in,out] pos Current position
222  * @param[in] type MQTT control packet type
223  * @param[in] dup DUP flag
224  * @param[in] qos QoS field
225  * @param[in] retain RETAIN flag
226  * @param[in] remainingLen Length of the variable header and the payload
227  * @return Error code
228  **/
229 
230 error_t mqttSerializeHeader(uint8_t *buffer, size_t *pos, MqttPacketType type,
231  bool_t dup, MqttQosLevel qos, bool_t retain, size_t remainingLen)
232 {
233  uint_t i;
234  uint_t k;
235  size_t n;
236  MqttPacketHeader *header;
237 
238  //Point to the current position
239  n = *pos;
240 
241  //The Remaining Length is encoded using a variable length encoding scheme
242  if(remainingLen < 128)
243  {
244  k = 1;
245  }
246  else if(remainingLen < 16384)
247  {
248  k = 2;
249  }
250  else if(remainingLen < 2097152)
251  {
252  k = 3;
253  }
254  else if(remainingLen < 268435456)
255  {
256  k = 4;
257  }
258  else
259  {
260  return ERROR_INVALID_LENGTH;
261  }
262 
263  //Sanity check
264  if(n < (sizeof(MqttPacketHeader) + k))
265  {
266  return ERROR_BUFFER_OVERFLOW;
267  }
268 
269  //Position where to format the header
270  n -= sizeof(MqttPacketHeader) + k;
271 
272  //Point to the MQTT packet header
273  header = (MqttPacketHeader *) (buffer + n);
274 
275  //Encode the first byte of the header
276  header->type = type;
277  header->dup = dup;
278  header->qos = qos;
279  header->retain = retain;
280 
281  //Encode the Remaining Length field
282  for(i = 0; i < k; i++)
283  {
284  //The least significant seven bits of each byte encode the data
285  header->length[i] = remainingLen & 0xFF;
286  remainingLen >>= 7;
287 
288  //The most significant bit is used to indicate that there are
289  //following bytes in the representation
290  if(remainingLen > 0)
291  {
292  header->length[i] |= 0x80;
293  }
294  }
295 
296  //Update current position
297  *pos = n;
298 
299  //Successful processing
300  return NO_ERROR;
301 }
302 
303 
304 /**
305  * @brief Write a 8-bit integer to the output buffer
306  * @param[in] buffer Pointer to the output buffer
307  * @param[in] bufferLen Maximum number of bytes the output buffer can hold
308  * @param[in,out] pos Current position
309  * @param[in] value 8-bit integer to be serialized
310  * @return Error code
311  **/
312 
313 error_t mqttSerializeByte(uint8_t *buffer, size_t bufferLen,
314  size_t *pos, uint8_t value)
315 {
316  size_t n;
317 
318  //Point to the current position
319  n = *pos;
320 
321  //Make sure the output buffer is large enough
322  if((n + sizeof(uint8_t)) > bufferLen)
323  {
324  return ERROR_BUFFER_OVERFLOW;
325  }
326 
327  //Write the byte to the output buffer
328  buffer[n++] = value;
329 
330  //Advance current position
331  *pos = n;
332 
333  //Successful processing
334  return NO_ERROR;
335 }
336 
337 
338 /**
339  * @brief Write a 16-bit integer to the output buffer
340  * @param[in] buffer Pointer to the output buffer
341  * @param[in] bufferLen Maximum number of bytes the output buffer can hold
342  * @param[in,out] pos Current position
343  * @param[in] value 16-bit integer to be serialized
344  * @return Error code
345  **/
346 
347 error_t mqttSerializeShort(uint8_t *buffer, size_t bufferLen,
348  size_t *pos, uint16_t value)
349 {
350  size_t n;
351 
352  //Point to the current position
353  n = *pos;
354 
355  //Make sure the output buffer is large enough
356  if((n + sizeof(uint16_t)) > bufferLen)
357  {
358  return ERROR_BUFFER_OVERFLOW;
359  }
360 
361  //Write the short integer to the output buffer
362  buffer[n++] = MSB(value);
363  buffer[n++] = LSB(value);
364 
365  //Advance current position
366  *pos = n;
367 
368  //Successful processing
369  return NO_ERROR;
370 }
371 
372 
373 /**
374  * @brief Serialize string
375  * @param[in] buffer Pointer to the output buffer
376  * @param[in] bufferLen Maximum number of bytes the output buffer can hold
377  * @param[in,out] pos Current position
378  * @param[in] string Pointer to the string to be serialized
379  * @param[in] stringLen Length of the string, in bytes
380  * @return Error code
381  **/
382 
383 error_t mqttSerializeString(uint8_t *buffer, size_t bufferLen,
384  size_t *pos, const void *string, size_t stringLen)
385 {
386  size_t n;
387 
388  //Point to the current position
389  n = *pos;
390 
391  //Make sure the output buffer is large enough to hold the string
392  if((n + sizeof(uint16_t) + stringLen) > bufferLen)
393  {
394  return ERROR_BUFFER_OVERFLOW;
395  }
396 
397  //Encode the length field
398  buffer[n++] = MSB(stringLen);
399  buffer[n++] = LSB(stringLen);
400 
401  //Write the string to the output buffer
402  osMemcpy(buffer + n, string, stringLen);
403 
404  //Advance current position
405  *pos = n + stringLen;
406 
407  //Successful processing
408  return NO_ERROR;
409 }
410 
411 
412 /**
413  * @brief Serialize raw data
414  * @param[in] buffer Pointer to the output buffer
415  * @param[in] bufferLen Maximum number of bytes the output buffer can hold
416  * @param[in,out] pos Current position
417  * @param[in] data Pointer to the raw data to be serialized
418  * @param[in] dataLen Length of the raw data, in bytes
419  * @return Error code
420  **/
421 
422 error_t mqttSerializeData(uint8_t *buffer, size_t bufferLen,
423  size_t *pos, const void *data, size_t dataLen)
424 {
425  size_t n;
426 
427  //Point to the current position
428  n = *pos;
429 
430  //Make sure the output buffer is large enough to hold the data
431  if((n + dataLen) > bufferLen)
432  {
433  return ERROR_BUFFER_OVERFLOW;
434  }
435 
436  //Write the data to the output buffer
437  osMemcpy(buffer + n, data, dataLen);
438 
439  //Advance current position
440  *pos = n + dataLen;
441 
442  //Successful processing
443  return NO_ERROR;
444 }
445 
446 
447 /**
448  * @brief Deserialize fixed header
449  * @param[in] buffer Pointer to the input buffer
450  * @param[in] bufferLen Length of the input buffer
451  * @param[in,out] pos Current position
452  * @param[out] type MQTT control packet type
453  * @param[out] dup DUP flag from the fixed header
454  * @param[out] qos QoS field from the fixed header
455  * @param[out] retain RETAIN flag from the fixed header
456  * @param[out] remainingLen Length of the variable header and the payload
457  * @return Error code
458  **/
459 
460 error_t mqttDeserializeHeader(uint8_t *buffer, size_t bufferLen, size_t *pos,
461  MqttPacketType *type, bool_t *dup, MqttQosLevel *qos, bool_t *retain, size_t *remainingLen)
462 {
463  uint_t i;
464  size_t n;
465  MqttPacketHeader *header;
466 
467  //Point to the current position
468  n = *pos;
469 
470  //Make sure the input buffer is large enough
471  if((n + sizeof(MqttPacketHeader)) > bufferLen)
472  {
473  return ERROR_INVALID_LENGTH;
474  }
475 
476  //Point to the MQTT packet header
477  header = (MqttPacketHeader *) (buffer + n);
478 
479  //Save MQTT control packet type
480  *type = (MqttPacketType) header->type;
481 
482  //Save flags
483  *dup = header->dup;
484  *qos = (MqttQosLevel) header->qos;
485  *retain = header->retain;
486 
487  //Advance current position
488  n += sizeof(MqttPacketHeader);
489 
490  //Prepare to decode the Remaining Length field
491  *remainingLen = 0;
492 
493  //The Remaining Length is encoded using a variable length encoding scheme
494  for(i = 0; i < 4; i++)
495  {
496  //Sanity check
497  if((n + sizeof(uint8_t)) > bufferLen)
498  {
499  return ERROR_INVALID_LENGTH;
500  }
501 
502  //Advance current position
503  n += sizeof(uint8_t);
504 
505  //The most significant bit is used to indicate that there are
506  //following bytes in the representation
507  if(header->length[i] & 0x80)
508  {
509  //Applications can send control packets of size up to 256 MB
510  if(i == 3)
511  {
512  return ERROR_INVALID_SYNTAX;
513  }
514 
515  //The least significant seven bits of each byte encode the data
516  *remainingLen |= (header->length[i] & 0x7F) << (7 * i);
517  }
518  else
519  {
520  //The least significant seven bits of each byte encode the data
521  *remainingLen |= header->length[i] << (7 * i);
522  //This is the last byte
523  break;
524  }
525  }
526 
527  //Return the current position
528  *pos = n;
529 
530  //Successful processing
531  return NO_ERROR;
532 }
533 
534 
535 /**
536  * @brief Read a 8-bit integer from the input buffer
537  * @param[in] buffer Pointer to the input buffer
538  * @param[in] bufferLen Length of the input buffer
539  * @param[in,out] pos Current position
540  * @param[out] value Value of the 8-bit integer
541  * @return Error code
542  **/
543 
544 error_t mqttDeserializeByte(uint8_t *buffer, size_t bufferLen,
545  size_t *pos, uint8_t *value)
546 {
547  size_t n;
548 
549  //Point to the current position
550  n = *pos;
551 
552  //Make sure the input buffer is large enough
553  if((n + sizeof(uint8_t)) > bufferLen)
554  {
555  return ERROR_BUFFER_OVERFLOW;
556  }
557 
558  //Read the short integer from the input buffer
559  *value = buffer[n];
560 
561  //Advance current position
562  *pos = n + sizeof(uint8_t);
563 
564  //Successful processing
565  return NO_ERROR;
566 }
567 
568 
569 /**
570  * @brief Read a 16-bit integer from the input buffer
571  * @param[in] buffer Pointer to the input buffer
572  * @param[in] bufferLen Length of the input buffer
573  * @param[in,out] pos Current position
574  * @param[out] value Value of the 16-bit integer
575  * @return Error code
576  **/
577 
578 error_t mqttDeserializeShort(uint8_t *buffer, size_t bufferLen,
579  size_t *pos, uint16_t *value)
580 {
581  size_t n;
582 
583  //Point to the current position
584  n = *pos;
585 
586  //Make sure the input buffer is large enough
587  if((n + sizeof(uint16_t)) > bufferLen)
588  {
589  return ERROR_BUFFER_OVERFLOW;
590  }
591 
592  //Read the short integer from the input buffer
593  *value = (buffer[n] << 8) | buffer[n + 1];
594 
595  //Advance current position
596  *pos = n + sizeof(uint16_t);
597 
598  //Successful processing
599  return NO_ERROR;
600 }
601 
602 
603 /**
604  * @brief Deserialize string
605  * @param[in] buffer Pointer to the input buffer
606  * @param[in] bufferLen Length of the input buffer
607  * @param[in,out] pos Current position
608  * @param[out] string Pointer to the string
609  * @param[out] stringLen Length of the string, in bytes
610  * @return Error code
611  **/
612 
613 error_t mqttDeserializeString(uint8_t *buffer, size_t bufferLen,
614  size_t *pos, char_t **string, size_t *stringLen)
615 {
616  size_t n;
617 
618  //Point to the current position
619  n = *pos;
620 
621  //Make sure the input buffer is large enough
622  if((n + sizeof(uint16_t)) > bufferLen)
623  {
624  return ERROR_BUFFER_OVERFLOW;
625  }
626 
627  //Decode the length field
628  *stringLen = (buffer[n] << 8) | buffer[n + 1];
629 
630  //Make sure the input buffer is large enough
631  if((n + sizeof(uint16_t) + *stringLen) > bufferLen)
632  {
633  return ERROR_BUFFER_OVERFLOW;
634  }
635 
636  //Read the string from the input buffer
637  *string = (char_t *) buffer + n + 2;
638 
639  //Advance current position
640  *pos = n + 2 + *stringLen;
641 
642  //Successful processing
643  return NO_ERROR;
644 }
645 
646 
647 /**
648  * @brief Determine whether a timeout error has occurred
649  * @param[in] context Pointer to the MQTT client context
650  * @return Error code
651  **/
652 
654 {
655 #if (NET_RTOS_SUPPORT == DISABLED)
656  error_t error;
657  systime_t time;
658 
659  //Get current time
660  time = osGetSystemTime();
661 
662  //Check whether the timeout has elapsed
663  if(timeCompare(time, context->startTime + context->settings.timeout) >= 0)
664  {
665  //Report a timeout error
666  error = ERROR_TIMEOUT;
667  }
668  else
669  {
670  //The operation would block
671  error = ERROR_WOULD_BLOCK;
672  }
673 
674  //Return status code
675  return error;
676 #else
677  //Report a timeout error
678  return ERROR_TIMEOUT;
679 #endif
680 }
681 
682 #endif
error_t mqttSerializeData(uint8_t *buffer, size_t bufferLen, size_t *pos, const void *data, size_t dataLen)
Serialize raw data.
int bool_t
Definition: compiler_port.h:63
@ MQTT_PACKET_TYPE_INVALID
Invalid packet.
Definition: mqtt_common.h:100
@ ERROR_WOULD_BLOCK
Definition: error.h:96
error_t mqttClientFormatPingReq(MqttClientContext *context)
Format PINGREQ packet.
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:143
error_t mqttDeserializeHeader(uint8_t *buffer, size_t bufferLen, size_t *pos, MqttPacketType *type, bool_t *dup, MqttQosLevel *qos, bool_t *retain, size_t *remainingLen)
Deserialize fixed header.
uint8_t data[]
Definition: ethernet.h:224
error_t mqttClientReceivePacket(MqttClientContext *context)
Receive MQTT packet.
error_t mqttClientSendData(MqttClientContext *context, const void *data, size_t length, size_t *written, uint_t flags)
Send data using the relevant transport protocol.
MqttPacketHeader
Definition: mqtt_common.h:199
uint8_t type
Definition: coap_common.h:176
error_t mqttDeserializeString(uint8_t *buffer, size_t bufferLen, size_t *pos, char_t **string, size_t *stringLen)
Deserialize string.
error_t mqttClientWaitForData(MqttClientContext *context, systime_t timeout)
Wait for incoming data.
uint8_t qos
Definition: mqtt_common.h:194
error_t mqttDeserializeByte(uint8_t *buffer, size_t bufferLen, size_t *pos, uint8_t *value)
Read a 8-bit integer from the input buffer.
@ MQTT_CLIENT_STATE_SENDING_PACKET
Definition: mqtt_client.h:165
#define timeCompare(t1, t2)
Definition: os_port.h:40
error_t mqttSerializeHeader(uint8_t *buffer, size_t *pos, MqttPacketType type, bool_t dup, MqttQosLevel qos, bool_t retain, size_t remainingLen)
Serialize fixed header.
#define osMemcpy(dest, src, length)
Definition: os_port.h:147
Helper functions for MQTT client.
void mqttClientChangeState(MqttClientContext *context, MqttClientState newState)
Update MQTT client state.
error_t
Error codes.
Definition: error.h:43
Transport protocol abstraction layer.
error_t mqttClientProcessEvents(MqttClientContext *context, systime_t timeout)
Process MQTT client events.
@ MQTT_CLIENT_STATE_PACKET_SENT
Definition: mqtt_client.h:167
error_t mqttSerializeByte(uint8_t *buffer, size_t bufferLen, size_t *pos, uint8_t value)
Write a 8-bit integer to the output buffer.
MqttQosLevel
Quality of service level.
Definition: mqtt_common.h:87
@ ERROR_INVALID_LENGTH
Definition: error.h:111
MQTT packet parsing and formatting.
#define MSB(x)
Definition: os_port.h:59
#define TRACE_INFO(...)
Definition: debug.h:105
#define LSB(x)
Definition: os_port.h:55
error_t mqttClientProcessPacket(MqttClientContext *context)
Process incoming MQTT packet.
uint32_t dataLen
Definition: sftp_common.h:229
@ MQTT_CLIENT_STATE_RECEIVING_PACKET
Definition: mqtt_client.h:169
uint32_t systime_t
System time.
@ MQTT_CLIENT_STATE_IDLE
Definition: mqtt_client.h:164
@ ERROR_TIMEOUT
Definition: error.h:95
char char_t
Definition: compiler_port.h:55
uint32_t time
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:120
uint8_t n
error_t mqttClientCheckTimeout(MqttClientContext *context)
Determine whether a timeout error has occurred.
error_t mqttClientCheckKeepAlive(MqttClientContext *context)
Check keep-alive time interval.
MqttClientState
MQTT client states.
Definition: mqtt_client.h:160
uint8_t value[]
Definition: tcp.h:376
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
uint8_t dup
Definition: mqtt_common.h:195
#define MqttClientContext
Definition: mqtt_client.h:147
error_t mqttDeserializeShort(uint8_t *buffer, size_t bufferLen, size_t *pos, uint16_t *value)
Read a 16-bit integer from the input buffer.
error_t mqttSerializeShort(uint8_t *buffer, size_t bufferLen, size_t *pos, uint16_t value)
Write a 16-bit integer to the output buffer.
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
TCP/IP stack core.
error_t mqttSerializeString(uint8_t *buffer, size_t bufferLen, size_t *pos, const void *string, size_t stringLen)
Serialize string.
@ NO_ERROR
Success.
Definition: error.h:44
MqttPacketType
MQTT control packet type.
Definition: mqtt_common.h:99
Debugging facilities.
systime_t osGetSystemTime(void)
Retrieve system time.
MQTT client.