mqtt_protocol.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ifndef HV_MQTT_PROTOCOL_H_
  2. #define HV_MQTT_PROTOCOL_H_
  3. #include "hexport.h"
  4. #define DEFAULT_MQTT_PORT 1883
  5. #define MQTT_PROTOCOL_V31 3
  6. #define MQTT_PROTOCOL_V311 4
  7. #define MQTT_PROTOCOL_V5 5 // Not yet supproted
  8. #define MQTT_PROTOCOL_NAME "MQTT"
  9. #define MQTT_PROTOCOL_NAME_v31 "MQIsdp"
  10. /*
  11. * MQTT connect
  12. * 2 + 4 protocol_name + 1 protocol_version + 1 conn_flags + 2 keepalive + 2 + [client_id] +
  13. * [2 + will_topic + 2 + will_payload] +
  14. * [2 + username] + [2 + password]
  15. */
  16. #define MQTT_CONN_HEAD_LEN 12
  17. /*
  18. * connect flags
  19. * 0 1 2 3-4 5 6 7
  20. * reserved clean_session has_will will_qos will_retain has_password has_username
  21. */
  22. #define MQTT_CONN_CLEAN_SESSION 0x02
  23. #define MQTT_CONN_HAS_WILL 0x04
  24. #define MQTT_CONN_WILL_RETAIN 0x20
  25. #define MQTT_CONN_HAS_PASSWORD 0x40
  26. #define MQTT_CONN_HAS_USERNAME 0x80
  27. typedef enum {
  28. MQTT_TYPE_CONNECT = 1,
  29. MQTT_TYPE_CONNACK = 2,
  30. MQTT_TYPE_PUBLISH = 3,
  31. MQTT_TYPE_PUBACK = 4,
  32. MQTT_TYPE_PUBREC = 5,
  33. MQTT_TYPE_PUBREL = 6,
  34. MQTT_TYPE_PUBCOMP = 7,
  35. MQTT_TYPE_SUBSCRIBE = 8,
  36. MQTT_TYPE_SUBACK = 9,
  37. MQTT_TYPE_UNSUBSCRIBE = 10,
  38. MQTT_TYPE_UNSUBACK = 11,
  39. MQTT_TYPE_PINGREQ = 12,
  40. MQTT_TYPE_PINGRESP = 13,
  41. MQTT_TYPE_DISCONNECT = 14,
  42. } mqtt_type_e;
  43. typedef enum {
  44. MQTT_CONNACK_ACCEPTED = 0,
  45. MQTT_CONNACK_REFUSED_PROTOCOL_VERSION = 1,
  46. MQTT_CONNACK_REFUSED_IDENTIFIER_REJECTED = 2,
  47. MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE = 3,
  48. MQTT_CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4,
  49. MQTT_CONNACK_REFUSED_NOT_AUTHORIZED = 5,
  50. } mqtt_connack_e;
  51. typedef struct mqtt_head_s {
  52. unsigned char type: 4;
  53. unsigned char dup: 1;
  54. unsigned char qos: 2;
  55. unsigned char retain: 1;
  56. unsigned int length;
  57. } mqtt_head_t;
  58. typedef struct mqtt_message_s {
  59. unsigned int topic_len;
  60. const char* topic;
  61. unsigned int payload_len;
  62. const char* payload;
  63. unsigned char qos;
  64. unsigned char retain;
  65. } mqtt_message_t;
  66. BEGIN_EXTERN_C
  67. #define DEFAULT_MQTT_PACKAGE_MAX_LENGTH (1 << 28) // 256M
  68. HV_INLINE int mqtt_estimate_length(mqtt_head_t* head) {
  69. // 28 bits => 4*7 bits varint
  70. return 1 + 4 + head->length;
  71. }
  72. HV_EXPORT int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]);
  73. HV_EXPORT int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len);
  74. END_EXTERN_C
  75. #endif // HV_MQTT_PROTOCOL_H_