mqtt_protocol.c 684 B

12345678910111213141516171819202122
  1. #include "mqtt_protocol.h"
  2. #include "hmath.h"
  3. int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]) {
  4. buf[0] = (head->type << 4) |
  5. (head->dup << 3) |
  6. (head->qos << 1) |
  7. (head->retain);
  8. int bytes = varint_encode(head->length, buf + 1);
  9. return 1 + bytes;
  10. }
  11. int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len) {
  12. head->type = (buf[0] >> 4) & 0x0F;
  13. head->dup = (buf[0] >> 3) & 0x01;
  14. head->qos = (buf[0] >> 1) & 0x03;
  15. head->retain = buf[0] & 0x01;
  16. int bytes = len - 1;
  17. head->length = varint_decode(buf + 1, &bytes);
  18. if (bytes <= 0) return bytes;
  19. return 1 + bytes;
  20. }