mqtt_protocol.h 2.4 KB

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