msg_queue.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "c_string.h"
  2. #include "c_stdlib.h"
  3. #include "c_stdio.h"
  4. #include "msg_queue.h"
  5. msg_queue_t *msg_enqueue(msg_queue_t **head, mqtt_message_t *msg, uint16_t msg_id, int msg_type, int publish_qos){
  6. if(!head){
  7. return NULL;
  8. }
  9. if (!msg || !msg->data || msg->length == 0){
  10. NODE_DBG("empty message\n");
  11. return NULL;
  12. }
  13. msg_queue_t *node = (msg_queue_t *)c_zalloc(sizeof(msg_queue_t));
  14. if(!node){
  15. NODE_DBG("not enough memory\n");
  16. return NULL;
  17. }
  18. node->msg.data = (uint8_t *)c_zalloc(msg->length);
  19. if(!node->msg.data){
  20. NODE_DBG("not enough memory\n");
  21. c_free(node);
  22. return NULL;
  23. }
  24. c_memcpy(node->msg.data, msg->data, msg->length);
  25. node->msg.length = msg->length;
  26. node->next = NULL;
  27. node->msg_id = msg_id;
  28. node->msg_type = msg_type;
  29. node->publish_qos = publish_qos;
  30. msg_queue_t *tail = *head;
  31. if(tail){
  32. while(tail->next!=NULL) tail = tail->next;
  33. tail->next = node;
  34. } else {
  35. *head = node;
  36. }
  37. return node;
  38. }
  39. void msg_destroy(msg_queue_t *node){
  40. if(!node) return;
  41. if(node->msg.data){
  42. c_free(node->msg.data);
  43. node->msg.data = NULL;
  44. }
  45. c_free(node);
  46. }
  47. msg_queue_t * msg_dequeue(msg_queue_t **head){
  48. if(!head || !*head){
  49. return NULL;
  50. }
  51. msg_queue_t *node = *head; // fetch head.
  52. *head = node->next; // update head.
  53. node->next = NULL;
  54. return node;
  55. }
  56. msg_queue_t * msg_peek(msg_queue_t **head){
  57. if(!head || !*head){
  58. return NULL;
  59. }
  60. return *head; // fetch head.
  61. }
  62. int msg_size(msg_queue_t **head){
  63. if(!head || !*head){
  64. return 0;
  65. }
  66. int i = 1;
  67. msg_queue_t *tail = *head;
  68. if(tail){
  69. while(tail->next!=NULL){
  70. tail = tail->next;
  71. i++;
  72. }
  73. }
  74. return i;
  75. }