sMQTTBroker
sMQTTMessage.h
1 #ifndef SMQTTMESSAGE_FILE
2 #define SMQTTMESSAGE_FILE
3 
4 #include<vector>
5 #include<string>
6 
7 enum sMQTTError
8 {
9  sMQTTOk = 0,
10  sMQTTNowhereToSend = 1,
11  sMQTTInvalidMessage = 2,
12 };
13 
14 static const char *debugMessageType[] = {
15  "Unknown",
16  "Connect",
17  "ConnAck",
18  "Publish",
19  "PubAck",
20  "PubRec",
21  "PubRel",
22  "PubComp",
23  "Subscribe",
24  "SubAck",
25  "UnSubscribe",
26  "UnSuback",
27  "PingReq",
28  "PingResp",
29  "Disconnect"
30 };
31 
32 class sMQTTClient;
34 {
35 public:
36  enum Type
37  {
38  Unknown = 0,
39  Connect = 0x10,
40  ConnAck = 0x20,
41  Publish = 0x30,
42  PubAck = 0x40,
43  PubRec = 0x50,
44  PubRel = 0x60,
45  PubComp=0x70,
46  Subscribe = 0x80,
47  SubAck = 0x90,
48  UnSubscribe = 0xA0,
49  UnSuback = 0xB0,
50  PingReq = 0xC0,
51  PingResp = 0xD0,
52  Disconnect = 0xE0
53  };
54  enum State
55  {
56  FixedHeader = 0,
57  Length = 1,
58  VariableHeader = 2,
59  PayLoad = 3,
60  Complete = 4,
61  Error = 5,
62  Create = 6
63  };
64  sMQTTMessage();
65  sMQTTMessage(Type t, unsigned char bits_d3_d0 = 0);
66  void incoming(char byte);
67  void add(char byte) { incoming(byte); }
68  void add(const char* p, size_t len, bool addLength = true)
69  {
70  if (addLength)
71  {
72  buffer.reserve(buffer.size() + addLength + 2);
73  incoming(len >> 8);
74  incoming(len & 0xFF);
75  }
76  while (len--) incoming(*p++);
77  }
78  void add(const std::string &str) { add(str.c_str(), str.size()); }
79  const char* end() const { return &buffer[0] + buffer.size(); }
80  const char* getVHeader() const { return &buffer[vheader]; }
81  void reset();
82  Type type() const
83  {
84  return state == Complete ? static_cast<Type>(buffer[0] & 0XF0) : Unknown;
85  }
86  unsigned char QoS() {
87  return (buffer[0] & 0x6)>>1;
88  }
89  bool isRetained() {
90  return buffer[0] & 0x1;
91  }
92  sMQTTError sendTo(sMQTTClient *, bool needRecalc=true);
93  // buff is MSB/LSB/STRING
94  // output buff+=2, len=length(str)
95  static void getString(const char* &buff, unsigned short &len);
96 private:
97  void create(Type type)
98  {
99  buffer.push_back((char)type);
100  buffer.push_back('\0'); // reserved for msg length
101  vheader = 2;
102  size = 0;
103  state = Create;
104  }
105  int encodeLength(char* msb, int length) const;
106 
107  std::vector<char> buffer;
108  State state;
109  unsigned short multiplyer;
110  unsigned short size;
111  unsigned char vheader;
112 };
113 #endif
sMQTTMessage
Definition: sMQTTMessage.h:34
sMQTTClient
Definition: sMQTTClient.h:22