Contiki-NG
mqtt.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015, Texas Instruments Incorporated - http://www.ti.com/
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holder nor the names of its
14  * contributors may be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28  * OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 /*---------------------------------------------------------------------------*/
31 /**
32  * \addtogroup apps
33  * @{
34  *
35  * \defgroup mqtt-engine An implementation of MQTT v3.1
36  * @{
37  *
38  * This application is an engine for MQTT v3.1. It supports QoS Levels 0 and 1.
39  *
40  * MQTT is a Client Server publish/subscribe messaging transport protocol.
41  * It is light weight, open, simple, and designed so as to be easy to implement.
42  * These characteristics make it ideal for use in many situations, including
43  * constrained environments such as for communication in Machine to Machine
44  * (M2M) and Internet of Things (IoT) contexts where a small code footprint is
45  * required and/or network bandwidth is at a premium.
46  *
47  * The protocol runs over TCP/IP, more specifically tcp_socket.
48  * Its features include:
49  *
50  * - Use of the publish/subscribe message pattern which provides
51  * one-to-many message distribution and decoupling of applications.
52  * - A messaging transport that is agnostic to the content of the payload.
53  * Three qualities of service for message delivery:
54  * -- "At most once" (0), where messages are delivered according to the best
55  * efforts of the operating environment. Message loss can occur.
56  * This level could be used, for example, with ambient sensor data where it
57  * does not matter if an individual reading is lost as the next one will be
58  * published soon after.
59  * --"At least once" (1), where messages are assured to arrive but duplicates
60  * can occur.
61  * -- "Exactly once" (2), where message are assured to arrive exactly once.
62  * This level could be used, for example, with billing systems where duplicate
63  * or lost messages could lead to incorrect charges being applied. This QoS
64  * level is currently not supported in this implementation.
65  *
66  * - A small transport overhead and protocol exchanges minimized to reduce
67  * network traffic.
68  * - A mechanism, Last Will, to notify interested parties when an abnormal
69  * disconnection occurs.
70  *
71  * The protocol specification and other useful information can be found
72  * here: http://mqtt.org
73  *
74  */
75 /**
76  * \file
77  * Header file for the Contiki MQTT engine
78  *
79  * \author
80  * Texas Instruments
81  */
82 /*---------------------------------------------------------------------------*/
83 #ifndef MQTT_H_
84 #define MQTT_H_
85 /*---------------------------------------------------------------------------*/
86 #include "contiki.h"
87 #include "contiki-net.h"
88 #include "contiki-lib.h"
89 #include "lib/random.h"
90 #include "sys/ctimer.h"
91 #include "sys/etimer.h"
92 #include "net/ipv6/uip.h"
93 #include "net/ipv6/uip-ds6.h"
94 #include "dev/leds.h"
95 
96 #include "tcp-socket.h"
97 #include "udp-socket.h"
98 
99 #include <stdlib.h>
100 #include <stdio.h>
101 #include <string.h>
102 /*---------------------------------------------------------------------------*/
103 /* Protocol constants */
104 #define MQTT_CLIENT_ID_MAX_LEN 23
105 
106 /* Size of the underlying TCP buffers */
107 #define MQTT_TCP_INPUT_BUFF_SIZE 512
108 #define MQTT_TCP_OUTPUT_BUFF_SIZE 512
109 
110 #define MQTT_INPUT_BUFF_SIZE 512
111 #define MQTT_MAX_TOPIC_LENGTH 64
112 #define MQTT_MAX_TOPICS_PER_SUBSCRIBE 1
113 
114 #define MQTT_FHDR_SIZE 1
115 #define MQTT_MAX_REMAINING_LENGTH_BYTES 4
116 #define MQTT_PROTOCOL_VERSION 3
117 #define MQTT_PROTOCOL_NAME "MQIsdp"
118 #define MQTT_TOPIC_MAX_LENGTH 128
119 /*---------------------------------------------------------------------------*/
120 /*
121  * Debug configuration, this is similar but not exactly like the Debugging
122  * System discussion at https://github.com/contiki-os/contiki/wiki.
123  */
124 #define DEBUG_MQTT 0
125 
126 #if DEBUG_MQTT == 1
127 #define DBG(...) printf(__VA_ARGS__)
128 #else
129 #define DBG(...)
130 #endif /* DEBUG */
131 /*---------------------------------------------------------------------------*/
132 extern process_event_t mqtt_update_event;
133 
134 /* Forward declaration */
135 struct mqtt_connection;
136 
137 typedef enum {
138  MQTT_RETAIN_OFF,
139  MQTT_RETAIN_ON,
140 } mqtt_retain_t;
141 
142 /**
143  * \brief MQTT engine events
144  */
145 typedef enum {
146  MQTT_EVENT_CONNECTED,
147  MQTT_EVENT_DISCONNECTED,
148 
149  MQTT_EVENT_SUBACK,
150  MQTT_EVENT_UNSUBACK,
151  MQTT_EVENT_PUBLISH,
152  MQTT_EVENT_PUBACK,
153 
154  /* Errors */
155  MQTT_EVENT_ERROR = 0x80,
156  MQTT_EVENT_PROTOCOL_ERROR,
157  MQTT_EVENT_CONNECTION_REFUSED_ERROR,
158  MQTT_EVENT_DNS_ERROR,
159  MQTT_EVENT_NOT_IMPLEMENTED_ERROR,
160  /* Add more */
161 } mqtt_event_t;
162 
163 typedef enum {
164  MQTT_STATUS_OK,
165 
166  MQTT_STATUS_OUT_QUEUE_FULL,
167 
168  /* Errors */
169  MQTT_STATUS_ERROR = 0x80,
170  MQTT_STATUS_NOT_CONNECTED_ERROR,
171  MQTT_STATUS_INVALID_ARGS_ERROR,
172  MQTT_STATUS_DNS_ERROR,
173 } mqtt_status_t;
174 
175 typedef enum {
176  MQTT_QOS_LEVEL_0,
177  MQTT_QOS_LEVEL_1,
178  MQTT_QOS_LEVEL_2,
179 } mqtt_qos_level_t;
180 
181 typedef enum {
182  MQTT_QOS_STATE_NO_ACK,
183  MQTT_QOS_STATE_GOT_ACK,
184 
185  /* Expand for QoS 2 */
186 } mqtt_qos_state_t;
187 /*---------------------------------------------------------------------------*/
188 /*
189  * This is the state of the connection itself.
190  *
191  * N.B. The order is important because of runtime checks on how far the
192  * connection has proceeded.
193  */
194 typedef enum {
195  MQTT_CONN_STATE_ERROR,
196  MQTT_CONN_STATE_DNS_ERROR,
197  MQTT_CONN_STATE_DISCONNECTING,
198  MQTT_CONN_STATE_ABORT_IMMEDIATE,
199  MQTT_CONN_STATE_NOT_CONNECTED,
200  MQTT_CONN_STATE_DNS_LOOKUP,
201  MQTT_CONN_STATE_TCP_CONNECTING,
202  MQTT_CONN_STATE_TCP_CONNECTED,
203  MQTT_CONN_STATE_CONNECTING_TO_BROKER,
204  MQTT_CONN_STATE_CONNECTED_TO_BROKER,
205  MQTT_CONN_STATE_SENDING_MQTT_DISCONNECT,
206 } mqtt_conn_state_t;
207 /*---------------------------------------------------------------------------*/
208 struct mqtt_string {
209  char *string;
210  uint16_t length;
211 };
212 
213 /*
214  * Note that the pairing mid <-> QoS level only applies one-to-one if we only
215  * allow the subscription of one topic at a time. Otherwise we will have an
216  * ordered list of QoS levels corresponding to the order of topics.
217  *
218  * This could be part of a union of event data structures.
219  */
220 struct mqtt_suback_event {
221  uint16_t mid;
222  mqtt_qos_level_t qos_level;
223 };
224 
225 /* This is the MQTT message that is exposed to the end user. */
226 struct mqtt_message {
227  uint32_t mid;
228  char topic[MQTT_MAX_TOPIC_LENGTH + 1]; /* +1 for string termination */
229 
230  uint8_t *payload_chunk;
231  uint16_t payload_chunk_length;
232 
233  uint8_t first_chunk;
234  uint16_t payload_length;
235  uint16_t payload_left;
236 };
237 
238 /* This struct represents a packet received from the MQTT server. */
239 struct mqtt_in_packet {
240  /* Used by the list interface, must be first in the struct. */
241  struct mqtt_connection *next;
242 
243  /* Total bytes read so far. Compared to the remaining length to to decide when
244  * we've read the payload. */
245  uint32_t byte_counter;
246  uint8_t packet_received;
247 
248  uint8_t fhdr;
249  uint16_t remaining_length;
250  uint16_t mid;
251 
252  /* Helper variables needed to decode the remaining_length */
253  uint8_t remaining_multiplier;
254  uint8_t has_remaining_length;
255  uint8_t remaining_length_bytes;
256 
257  /* Not the same as payload in the MQTT sense, it also contains the variable
258  * header.
259  */
260  uint8_t payload_pos;
261  uint8_t payload[MQTT_INPUT_BUFF_SIZE];
262 
263  /* Message specific data */
264  uint16_t topic_len;
265  uint16_t topic_pos;
266  uint8_t topic_len_received;
267  uint8_t topic_received;
268 };
269 
270 /* This struct represents a packet sent to the MQTT server. */
271 struct mqtt_out_packet {
272  uint8_t fhdr;
273  uint32_t remaining_length;
274  uint8_t remaining_length_enc[MQTT_MAX_REMAINING_LENGTH_BYTES];
275  uint8_t remaining_length_enc_bytes;
276  uint16_t mid;
277  char *topic;
278  uint16_t topic_length;
279  uint8_t *payload;
280  uint32_t payload_size;
281  mqtt_qos_level_t qos;
282  mqtt_qos_state_t qos_state;
283  mqtt_retain_t retain;
284 };
285 /*---------------------------------------------------------------------------*/
286 /**
287  * \brief MQTT event callback function
288  * \param m A pointer to a MQTT connection
289  * \param event The event number
290  * \param data A user-defined pointer
291  *
292  * The MQTT socket event callback function gets called whenever there is an
293  * event on a MQTT connection, such as the connection getting connected
294  * or closed.
295  */
296 typedef void (*mqtt_event_callback_t)(struct mqtt_connection *m,
297  mqtt_event_t event,
298  void *data);
299 
300 typedef void (*mqtt_topic_callback_t)(struct mqtt_connection *m,
301  struct mqtt_message *msg);
302 /*---------------------------------------------------------------------------*/
303 struct mqtt_will {
304  struct mqtt_string topic;
305  struct mqtt_string message;
306  mqtt_qos_level_t qos;
307 };
308 
309 struct mqtt_credentials {
310  struct mqtt_string username;
311  struct mqtt_string password;
312 };
313 
314 struct mqtt_connection {
315  /* Used by the list interface, must be first in the struct */
316  struct mqtt_connection *next;
317  struct timer t;
318 
319  struct mqtt_string client_id;
320 
321  uint8_t connect_vhdr_flags;
322  uint8_t auto_reconnect;
323 
324  uint16_t keep_alive;
325  struct ctimer keep_alive_timer;
326  uint8_t waiting_for_pingresp;
327 
328  struct mqtt_will will;
329  struct mqtt_credentials credentials;
330 
331  mqtt_conn_state_t state;
332  mqtt_event_callback_t event_callback;
333 
334  /* Internal data */
335  uint16_t mid_counter;
336 
337  /* Used for communication between MQTT API and APP */
338  uint8_t out_queue_full;
339  struct process *app_process;
340 
341  /* Outgoing data related */
342  uint8_t *out_buffer_ptr;
343  uint8_t out_buffer[MQTT_TCP_OUTPUT_BUFF_SIZE];
344  uint8_t out_buffer_sent;
345  struct mqtt_out_packet out_packet;
346  struct pt out_proto_thread;
347  uint32_t out_write_pos;
348  uint16_t max_segment_size;
349 
350  /* Incoming data related */
351  uint8_t in_buffer[MQTT_TCP_INPUT_BUFF_SIZE];
352  struct mqtt_in_packet in_packet;
353  struct mqtt_message in_publish_msg;
354 
355  /* TCP related information */
356  char *server_host;
357  uip_ipaddr_t server_ip;
358  uint16_t server_port;
359  struct tcp_socket socket;
360 };
361 /* This is the API exposed to the user. */
362 /*---------------------------------------------------------------------------*/
363 /**
364  * \brief Initializes the MQTT engine.
365  * \param conn A pointer to the MQTT connection.
366  * \param app_process A pointer to the application process handling the MQTT
367  * connection.
368  * \param client_id A pointer to the MQTT client ID.
369  * \param event_callback Callback function responsible for handling the
370  * callback from MQTT engine.
371  * \param max_segment_size The TCP segment size to use for this MQTT/TCP
372  * connection.
373  * \return MQTT_STATUS_OK or MQTT_STATUS_INVALID_ARGS_ERROR
374  *
375  * This function initializes the MQTT engine and shall be called before any
376  * other MQTT function.
377  */
378 mqtt_status_t mqtt_register(struct mqtt_connection *conn,
379  struct process *app_process,
380  char *client_id,
381  mqtt_event_callback_t event_callback,
382  uint16_t max_segment_size);
383 /*---------------------------------------------------------------------------*/
384 /**
385  * \brief Connects to a MQTT broker.
386  * \param conn A pointer to the MQTT connection.
387  * \param host IP address of the broker to connect to.
388  * \param port Port of the broker to connect to, default is MQTT port is 1883.
389  * \param keep_alive Keep alive timer in seconds. Used by broker to handle
390  * client disc. Defines the maximum time interval between two messages
391  * from the client. Shall be min 1.5 x report interval.
392  * \return MQTT_STATUS_OK or an error status
393  *
394  * This function connects to a MQTT broker.
395  */
396 mqtt_status_t mqtt_connect(struct mqtt_connection *conn,
397  char *host,
398  uint16_t port,
399  uint16_t keep_alive);
400 /*---------------------------------------------------------------------------*/
401 /**
402  * \brief Disconnects from a MQTT broker.
403  * \param conn A pointer to the MQTT connection.
404  *
405  * This function disconnects from a MQTT broker.
406  */
407 void mqtt_disconnect(struct mqtt_connection *conn);
408 /*---------------------------------------------------------------------------*/
409 /**
410  * \brief Subscribes to a MQTT topic.
411  * \param conn A pointer to the MQTT connection.
412  * \param mid A pointer to message ID.
413  * \param topic A pointer to the topic to subscribe to.
414  * \param qos_level Quality Of Service level to use. Currently supports 0, 1.
415  * \return MQTT_STATUS_OK or some error status
416  *
417  * This function subscribes to a topic on a MQTT broker.
418  */
419 mqtt_status_t mqtt_subscribe(struct mqtt_connection *conn,
420  uint16_t *mid,
421  char *topic,
422  mqtt_qos_level_t qos_level);
423 /*---------------------------------------------------------------------------*/
424 /**
425  * \brief Unsubscribes from a MQTT topic.
426  * \param conn A pointer to the MQTT connection.
427  * \param mid A pointer to message ID.
428  * \param topic A pointer to the topic to unsubscribe from.
429  * \return MQTT_STATUS_OK or some error status
430  *
431  * This function unsubscribes from a topic on a MQTT broker.
432  */
433 mqtt_status_t mqtt_unsubscribe(struct mqtt_connection *conn,
434  uint16_t *mid,
435  char *topic);
436 /*---------------------------------------------------------------------------*/
437 /**
438  * \brief Publish to a MQTT topic.
439  * \param conn A pointer to the MQTT connection.
440  * \param mid A pointer to message ID.
441  * \param topic A pointer to the topic to subscribe to.
442  * \param payload A pointer to the topic payload.
443  * \param payload_size Payload size.
444  * \param qos_level Quality Of Service level to use. Currently supports 0, 1.
445  * \param retain If the RETAIN flag is set to 1, in a PUBLISH Packet sent by a
446  * Client to a Server, the Server MUST store the Application Message
447  * and its QoS, so that it can be delivered to future subscribers whose
448  * subscriptions match its topic name
449  * \return MQTT_STATUS_OK or some error status
450  *
451  * This function publishes to a topic on a MQTT broker.
452  */
453 mqtt_status_t mqtt_publish(struct mqtt_connection *conn,
454  uint16_t *mid,
455  char *topic,
456  uint8_t *payload,
457  uint32_t payload_size,
458  mqtt_qos_level_t qos_level,
459  mqtt_retain_t retain);
460 /*---------------------------------------------------------------------------*/
461 /**
462  * \brief Set the user name and password for a MQTT client.
463  * \param conn A pointer to the MQTT connection.
464  * \param username A pointer to the user name.
465  * \param password A pointer to the password.
466  *
467  * This function sets clients user name and password to use when connecting to
468  * a MQTT broker.
469  */
470 void mqtt_set_username_password(struct mqtt_connection *conn,
471  char *username,
472  char *password);
473 /*---------------------------------------------------------------------------*/
474 /**
475  * \brief Set the last will topic and message for a MQTT client.
476  * \param conn A pointer to the MQTT connection.
477  * \param topic A pointer to the Last Will topic.
478  * \param message A pointer to the Last Will message (payload).
479  * \param qos The desired QoS level.
480  *
481  * This function sets clients Last Will topic and message (payload).
482  * If the Will Flag is set to 1 (using the function) this indicates that,
483  * if the Connect request is accepted, a Will Message MUST be stored on the
484  * Server and associated with the Network Connection. The Will Message MUST
485  * be published when the Network Connection is subsequently closed.
486  *
487  * This functionality can be used to get notified that a device has
488  * disconnected from the broker.
489  *
490  */
491 void mqtt_set_last_will(struct mqtt_connection *conn,
492  char *topic,
493  char *message,
494  mqtt_qos_level_t qos);
495 
496 #define mqtt_connected(conn) \
497  ((conn)->state == MQTT_CONN_STATE_CONNECTED_TO_BROKER ? 1 : 0)
498 
499 #define mqtt_ready(conn) \
500  (!(conn)->out_queue_full && mqtt_connected((conn)))
501 /*---------------------------------------------------------------------------*/
502 #endif /* MQTT_H_ */
503 /*---------------------------------------------------------------------------*/
504 /**
505  * @}
506  * @}
507  */
mqtt_status_t mqtt_subscribe(struct mqtt_connection *conn, uint16_t *mid, char *topic, mqtt_qos_level_t qos_level)
Subscribes to a MQTT topic.
Definition: mqtt.c:1374
mqtt_event_t
MQTT engine events.
Definition: mqtt.h:145
mqtt_status_t mqtt_connect(struct mqtt_connection *conn, char *host, uint16_t port, uint16_t keep_alive)
Connects to a MQTT broker.
Definition: mqtt.c:1325
mqtt_status_t mqtt_publish(struct mqtt_connection *conn, uint16_t *mid, char *topic, uint8_t *payload, uint32_t payload_size, mqtt_qos_level_t qos_level, mqtt_retain_t retain)
Publish to a MQTT topic.
Definition: mqtt.c:1427
A timer.
Definition: timer.h:82
void(* mqtt_event_callback_t)(struct mqtt_connection *m, mqtt_event_t event, void *data)
MQTT event callback function.
Definition: mqtt.h:296
Header file for IPv6-related data structures.
Header file for the callback timer
Event timer header file.
mqtt_status_t mqtt_unsubscribe(struct mqtt_connection *conn, uint16_t *mid, char *topic)
Unsubscribes from a MQTT topic.
Definition: mqtt.c:1402
void mqtt_set_username_password(struct mqtt_connection *conn, char *username, char *password)
Set the user name and password for a MQTT client.
Definition: mqtt.c:1459
Header file for the uIP TCP/IP stack.
mqtt_status_t mqtt_register(struct mqtt_connection *conn, struct process *app_process, char *client_id, mqtt_event_callback_t event_callback, uint16_t max_segment_size)
Initializes the MQTT engine.
Definition: mqtt.c:1294
void mqtt_disconnect(struct mqtt_connection *conn)
Disconnects from a MQTT broker.
Definition: mqtt.c:1362
void mqtt_set_last_will(struct mqtt_connection *conn, char *topic, char *message, mqtt_qos_level_t qos)
Set the last will topic and message for a MQTT client.
Definition: mqtt.c:1480
Header file for the LED HAL.