Contiki 3.x
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/rpl/rpl.h"
93 #include "net/ip/uip.h"
94 #include "net/ipv6/uip-ds6.h"
95 #include "dev/leds.h"
96 
97 #include "tcp-socket.h"
98 #include "udp-socket.h"
99 
100 #include <stdlib.h>
101 #include <stdio.h>
102 #include <string.h>
103 /*---------------------------------------------------------------------------*/
104 /* Protocol constants */
105 #define MQTT_CLIENT_ID_MAX_LEN 23
106 
107 /* Size of the underlying TCP buffers */
108 #define MQTT_TCP_INPUT_BUFF_SIZE 512
109 #define MQTT_TCP_OUTPUT_BUFF_SIZE 512
110 
111 #define MQTT_INPUT_BUFF_SIZE 512
112 #define MQTT_MAX_TOPIC_LENGTH 64
113 #define MQTT_MAX_TOPICS_PER_SUBSCRIBE 1
114 
115 #define MQTT_FHDR_SIZE 1
116 #define MQTT_MAX_REMAINING_LENGTH_BYTES 4
117 #define MQTT_PROTOCOL_VERSION 3
118 #define MQTT_PROTOCOL_NAME "MQIsdp"
119 #define MQTT_TOPIC_MAX_LENGTH 128
120 /*---------------------------------------------------------------------------*/
121 /*
122  * Debug configuration, this is similar but not exactly like the Debugging
123  * System discussion at https://github.com/contiki-os/contiki/wiki.
124  */
125 #define DEBUG_MQTT 0
126 
127 #if DEBUG_MQTT == 1
128 #define DBG(...) printf(__VA_ARGS__)
129 #else
130 #define DBG(...)
131 #endif /* DEBUG */
132 /*---------------------------------------------------------------------------*/
133 extern process_event_t mqtt_update_event;
134 
135 /* Forward declaration */
136 struct mqtt_connection;
137 
138 typedef enum {
139  MQTT_RETAIN_OFF,
140  MQTT_RETAIN_ON,
141 } mqtt_retain_t;
142 
143 /**
144  * \brief MQTT engine events
145  */
146 typedef enum {
147  MQTT_EVENT_CONNECTED,
148  MQTT_EVENT_DISCONNECTED,
149 
150  MQTT_EVENT_SUBACK,
151  MQTT_EVENT_UNSUBACK,
152  MQTT_EVENT_PUBLISH,
153  MQTT_EVENT_PUBACK,
154 
155  /* Errors */
156  MQTT_EVENT_ERROR = 0x80,
157  MQTT_EVENT_PROTOCOL_ERROR,
158  MQTT_EVENT_CONNECTION_REFUSED_ERROR,
159  MQTT_EVENT_DNS_ERROR,
160  MQTT_EVENT_NOT_IMPLEMENTED_ERROR,
161  /* Add more */
162 } mqtt_event_t;
163 
164 typedef enum {
165  MQTT_STATUS_OK,
166 
167  MQTT_STATUS_OUT_QUEUE_FULL,
168 
169  /* Errors */
170  MQTT_STATUS_ERROR = 0x80,
171  MQTT_STATUS_NOT_CONNECTED_ERROR,
172  MQTT_STATUS_INVALID_ARGS_ERROR,
173  MQTT_STATUS_DNS_ERROR,
174 } mqtt_status_t;
175 
176 typedef enum {
177  MQTT_QOS_LEVEL_0,
178  MQTT_QOS_LEVEL_1,
179  MQTT_QOS_LEVEL_2,
180 } mqtt_qos_level_t;
181 
182 typedef enum {
183  MQTT_QOS_STATE_NO_ACK,
184  MQTT_QOS_STATE_GOT_ACK,
185 
186  /* Expand for QoS 2 */
187 } mqtt_qos_state_t;
188 /*---------------------------------------------------------------------------*/
189 /*
190  * This is the state of the connection itself.
191  *
192  * N.B. The order is important because of runtime checks on how far the
193  * connection has proceeded.
194  */
195 typedef enum {
196  MQTT_CONN_STATE_ERROR,
197  MQTT_CONN_STATE_DNS_ERROR,
198  MQTT_CONN_STATE_DISCONNECTING,
199 
200  MQTT_CONN_STATE_NOT_CONNECTED,
201  MQTT_CONN_STATE_DNS_LOOKUP,
202  MQTT_CONN_STATE_TCP_CONNECTING,
203  MQTT_CONN_STATE_TCP_CONNECTED,
204  MQTT_CONN_STATE_CONNECTING_TO_BROKER,
205  MQTT_CONN_STATE_CONNECTED_TO_BROKER,
206  MQTT_CONN_STATE_SENDING_MQTT_DISCONNECT,
207  MQTT_CONN_STATE_ABORT_IMMEDIATE,
208 } mqtt_conn_state_t;
209 /*---------------------------------------------------------------------------*/
210 struct mqtt_string {
211  char *string;
212  uint16_t length;
213 };
214 
215 /*
216  * Note that the pairing mid <-> QoS level only applies one-to-one if we only
217  * allow the subscription of one topic at a time. Otherwise we will have an
218  * ordered list of QoS levels corresponding to the order of topics.
219  *
220  * This could be part of a union of event data structures.
221  */
222 struct mqtt_suback_event {
223  uint16_t mid;
224  mqtt_qos_level_t qos_level;
225 };
226 
227 /* This is the MQTT message that is exposed to the end user. */
228 struct mqtt_message {
229  uint32_t mid;
230  char topic[MQTT_MAX_TOPIC_LENGTH + 1]; /* +1 for string termination */
231 
232  uint8_t *payload_chunk;
233  uint16_t payload_chunk_length;
234 
235  uint8_t first_chunk;
236  uint16_t payload_length;
237  uint16_t payload_left;
238 };
239 
240 /* This struct represents a packet received from the MQTT server. */
241 struct mqtt_in_packet {
242  /* Used by the list interface, must be first in the struct. */
243  struct mqtt_connection *next;
244 
245  /* Total bytes read so far. Compared to the remaining length to to decide when
246  * we've read the payload. */
247  uint32_t byte_counter;
248  uint8_t packet_received;
249 
250  uint8_t fhdr;
251  uint16_t remaining_length;
252  uint16_t mid;
253 
254  /* Helper variables needed to decode the remaining_length */
255  uint8_t remaining_multiplier;
256  uint8_t has_remaining_length;
257  uint8_t remaining_length_bytes;
258 
259  /* Not the same as payload in the MQTT sense, it also contains the variable
260  * header.
261  */
262  uint8_t payload_pos;
263  uint8_t payload[MQTT_INPUT_BUFF_SIZE];
264 
265  /* Message specific data */
266  uint16_t topic_len;
267  uint16_t topic_pos;
268  uint8_t topic_len_received;
269  uint8_t topic_received;
270 };
271 
272 /* This struct represents a packet sent to the MQTT server. */
273 struct mqtt_out_packet {
274  uint8_t fhdr;
275  uint32_t remaining_length;
276  uint8_t remaining_length_enc[MQTT_MAX_REMAINING_LENGTH_BYTES];
277  uint8_t remaining_length_enc_bytes;
278  uint16_t mid;
279  char *topic;
280  uint16_t topic_length;
281  uint8_t *payload;
282  uint32_t payload_size;
283  mqtt_qos_level_t qos;
284  mqtt_qos_state_t qos_state;
285  mqtt_retain_t retain;
286 };
287 /*---------------------------------------------------------------------------*/
288 /**
289  * \brief MQTT event callback function
290  * \param m A pointer to a MQTT connection
291  * \param event The event number
292  * \param data A user-defined pointer
293  *
294  * The MQTT socket event callback function gets called whenever there is an
295  * event on a MQTT connection, such as the connection getting connected
296  * or closed.
297  */
298 typedef void (*mqtt_event_callback_t)(struct mqtt_connection *m,
299  mqtt_event_t event,
300  void *data);
301 
302 typedef void (*mqtt_topic_callback_t)(struct mqtt_connection *m,
303  struct mqtt_message *msg);
304 /*---------------------------------------------------------------------------*/
305 struct mqtt_will {
306  struct mqtt_string topic;
307  struct mqtt_string message;
308  mqtt_qos_level_t qos;
309 };
310 
311 struct mqtt_credentials {
312  struct mqtt_string username;
313  struct mqtt_string password;
314 };
315 
316 struct mqtt_connection {
317  /* Used by the list interface, must be first in the struct */
318  struct mqtt_connection *next;
319  struct timer t;
320 
321  struct mqtt_string client_id;
322 
323  uint8_t connect_vhdr_flags;
324  uint8_t auto_reconnect;
325 
326  uint16_t keep_alive;
327  struct ctimer keep_alive_timer;
328  uint8_t waiting_for_pingresp;
329 
330  struct mqtt_will will;
331  struct mqtt_credentials credentials;
332 
333  mqtt_conn_state_t state;
334  mqtt_event_callback_t event_callback;
335 
336  /* Internal data */
337  uint16_t mid_counter;
338 
339  /* Used for communication between MQTT API and APP */
340  uint8_t out_queue_full;
341  struct process *app_process;
342 
343  /* Outgoing data related */
344  uint8_t *out_buffer_ptr;
345  uint8_t out_buffer[MQTT_TCP_OUTPUT_BUFF_SIZE];
346  uint8_t out_buffer_sent;
347  struct mqtt_out_packet out_packet;
348  struct pt out_proto_thread;
349  uint32_t out_write_pos;
350  uint16_t max_segment_size;
351 
352  /* Incoming data related */
353  uint8_t in_buffer[MQTT_TCP_INPUT_BUFF_SIZE];
354  struct mqtt_in_packet in_packet;
355  struct mqtt_message in_publish_msg;
356 
357  /* TCP related information */
358  char *server_host;
359  uip_ipaddr_t server_ip;
360  uint16_t server_port;
361  struct tcp_socket socket;
362 };
363 /* This is the API exposed to the user. */
364 /*---------------------------------------------------------------------------*/
365 /**
366  * \brief Initializes the MQTT engine.
367  * \param conn A pointer to the MQTT connection.
368  * \param app_process A pointer to the application process handling the MQTT
369  * connection.
370  * \param client_id A pointer to the MQTT client ID.
371  * \param event_callback Callback function responsible for handling the
372  * callback from MQTT engine.
373  * \param max_segment_size The TCP segment size to use for this MQTT/TCP
374  * connection.
375  * \return MQTT_STATUS_OK or MQTT_STATUS_INVALID_ARGS_ERROR
376  *
377  * This function initializes the MQTT engine and shall be called before any
378  * other MQTT function.
379  */
380 mqtt_status_t mqtt_register(struct mqtt_connection *conn,
381  struct process *app_process,
382  char *client_id,
383  mqtt_event_callback_t event_callback,
384  uint16_t max_segment_size);
385 /*---------------------------------------------------------------------------*/
386 /**
387  * \brief Connects to a MQTT broker.
388  * \param conn A pointer to the MQTT connection.
389  * \param host IP address of the broker to connect to.
390  * \param port Port of the broker to connect to, default is MQTT port is 1883.
391  * \param keep_alive Keep alive timer in seconds. Used by broker to handle
392  * client disc. Defines the maximum time interval between two messages
393  * from the client. Shall be min 1.5 x report interval.
394  * \return MQTT_STATUS_OK or an error status
395  *
396  * This function connects to a MQTT broker.
397  */
398 mqtt_status_t mqtt_connect(struct mqtt_connection *conn,
399  char *host,
400  uint16_t port,
401  uint16_t keep_alive);
402 /*---------------------------------------------------------------------------*/
403 /**
404  * \brief Disconnects from a MQTT broker.
405  * \param conn A pointer to the MQTT connection.
406  *
407  * This function disconnects from a MQTT broker.
408  */
409 void mqtt_disconnect(struct mqtt_connection *conn);
410 /*---------------------------------------------------------------------------*/
411 /**
412  * \brief Subscribes to a MQTT topic.
413  * \param conn A pointer to the MQTT connection.
414  * \param mid A pointer to message ID.
415  * \param topic A pointer to the topic to subscribe to.
416  * \param qos_level Quality Of Service level to use. Currently supports 0, 1.
417  * \return MQTT_STATUS_OK or some error status
418  *
419  * This function subscribes to a topic on a MQTT broker.
420  */
421 mqtt_status_t mqtt_subscribe(struct mqtt_connection *conn,
422  uint16_t *mid,
423  char *topic,
424  mqtt_qos_level_t qos_level);
425 /*---------------------------------------------------------------------------*/
426 /**
427  * \brief Unsubscribes from a MQTT topic.
428  * \param conn A pointer to the MQTT connection.
429  * \param mid A pointer to message ID.
430  * \param topic A pointer to the topic to unsubscribe from.
431  * \return MQTT_STATUS_OK or some error status
432  *
433  * This function unsubscribes from a topic on a MQTT broker.
434  */
435 mqtt_status_t mqtt_unsubscribe(struct mqtt_connection *conn,
436  uint16_t *mid,
437  char *topic);
438 /*---------------------------------------------------------------------------*/
439 /**
440  * \brief Publish to a MQTT topic.
441  * \param conn A pointer to the MQTT connection.
442  * \param mid A pointer to message ID.
443  * \param topic A pointer to the topic to subscribe to.
444  * \param payload A pointer to the topic payload.
445  * \param payload_size Payload size.
446  * \param qos_level Quality Of Service level to use. Currently supports 0, 1.
447  * \param retain If the RETAIN flag is set to 1, in a PUBLISH Packet sent by a
448  * Client to a Server, the Server MUST store the Application Message
449  * and its QoS, so that it can be delivered to future subscribers whose
450  * subscriptions match its topic name
451  * \return MQTT_STATUS_OK or some error status
452  *
453  * This function publishes to a topic on a MQTT broker.
454  */
455 mqtt_status_t mqtt_publish(struct mqtt_connection *conn,
456  uint16_t *mid,
457  char *topic,
458  uint8_t *payload,
459  uint32_t payload_size,
460  mqtt_qos_level_t qos_level,
461  mqtt_retain_t retain);
462 /*---------------------------------------------------------------------------*/
463 /**
464  * \brief Set the user name and password for a MQTT client.
465  * \param conn A pointer to the MQTT connection.
466  * \param username A pointer to the user name.
467  * \param password A pointer to the password.
468  *
469  * This function sets clients user name and password to use when connecting to
470  * a MQTT broker.
471  */
472 void mqtt_set_username_password(struct mqtt_connection *conn,
473  char *username,
474  char *password);
475 /*---------------------------------------------------------------------------*/
476 /**
477  * \brief Set the last will topic and message for a MQTT client.
478  * \param conn A pointer to the MQTT connection.
479  * \param topic A pointer to the Last Will topic.
480  * \param message A pointer to the Last Will message (payload).
481  * \param qos The desired QoS level.
482  *
483  * This function sets clients Last Will topic and message (payload).
484  * If the Will Flag is set to 1 (using the function) this indicates that,
485  * if the Connect request is accepted, a Will Message MUST be stored on the
486  * Server and associated with the Network Connection. The Will Message MUST
487  * be published when the Network Connection is subsequently closed.
488  *
489  * This functionality can be used to get notified that a device has
490  * disconnected from the broker.
491  *
492  */
493 void mqtt_set_last_will(struct mqtt_connection *conn,
494  char *topic,
495  char *message,
496  mqtt_qos_level_t qos);
497 
498 #define mqtt_connected(conn) \
499  ((conn)->state == MQTT_CONN_STATE_CONNECTED_TO_BROKER ? 1 : 0)
500 
501 #define mqtt_ready(conn) \
502  (!(conn)->out_queue_full && mqtt_connected((conn)))
503 /*---------------------------------------------------------------------------*/
504 #endif /* MQTT_H_ */
505 /*---------------------------------------------------------------------------*/
506 /**
507  * @}
508  * @}
509  */
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:1314
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:1283
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:1414
Header file for IPv6-related data structures.
void mqtt_disconnect(struct mqtt_connection *conn)
Disconnects from a MQTT broker.
Definition: mqtt.c:1349
A timer.
Definition: timer.h:86
mqtt_event_t
MQTT engine events.
Definition: mqtt.h:146
Header file for the callback timer
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:1446
Header file for the uIP TCP/IP stack.
Event timer header file.
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:1467
mqtt_status_t mqtt_unsubscribe(struct mqtt_connection *conn, uint16_t *mid, char *topic)
Unsubscribes from a MQTT topic.
Definition: mqtt.c:1389
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:1361
void(* mqtt_event_callback_t)(struct mqtt_connection *m, mqtt_event_t event, void *data)
MQTT event callback function.
Definition: mqtt.h:298