MQTT Client API

MQTT Client API provides sequential API built on top of MQTT Client.

MQTT API application example code
  1/*
  2 * MQTT client API example with ESP device to test server.
  3 * It utilizes sequential mode without callbacks in one user thread
  4 *
  5 * Once device is connected to network,
  6 * it will try to connect to mosquitto test server and start the MQTT.
  7 *
  8 * If successfully connected, it will publish data to "lwesp_mqtt_topic" topic every x seconds.
  9 *
 10 * To check if data are sent, you can use mqtt-spy PC software to inspect
 11 * test.mosquitto.org server and subscribe to publishing topic
 12 */
 13
 14#include "mqtt_client_api.h"
 15#include "lwesp/apps/lwesp_mqtt_client_api.h"
 16#include "lwesp/lwesp_mem.h"
 17
 18/**
 19 * \brief           Connection information for MQTT CONNECT packet
 20 */
 21static const lwesp_mqtt_client_info_t mqtt_client_info = {
 22    .keep_alive = 10,
 23
 24    /* Server login data */
 25    .user = "8a215f70-a644-11e8-ac49-e932ed599553",
 26    .pass = "26aa943f702e5e780f015cd048a91e8fb54cca28",
 27
 28    /* Device identifier address */
 29    .id = "869f5a20-af9c-11e9-b01f-db5cf74e7fb7",
 30};
 31
 32static char mqtt_topic_str[256];  /*!< Topic string */
 33static char mqtt_topic_data[256]; /*!< Data string */
 34
 35/**
 36 * \brief           Generate random number and write it to string
 37 * It utilizes simple pseudo random generator, super simple one
 38 * \param[out]      str: Output string with new number
 39 */
 40static void
 41prv_generate_random(char* str) {
 42    static uint32_t random_beg = 0x8916;
 43    random_beg = random_beg * 0x00123455 + 0x85654321;
 44    sprintf(str, "%u", (unsigned)((random_beg >> 8) & 0xFFFF));
 45}
 46
 47/**
 48 * \brief           MQTT client API thread
 49 * \param[in]       arg: User argument
 50 */
 51void
 52lwesp_mqtt_client_api_thread(void const* arg) {
 53    lwesp_mqtt_client_api_p client;
 54    lwesp_mqtt_conn_status_t conn_status;
 55    lwesp_mqtt_client_api_buf_p buf;
 56    lwespr_t res;
 57    char random_str[10];
 58
 59    LWESP_UNUSED(arg);
 60
 61    /* Create new MQTT API */
 62    if ((client = lwesp_mqtt_client_api_new(256, 128)) == NULL) {
 63        goto terminate;
 64    }
 65
 66    while (1) {
 67        /* Make a connection */
 68        printf("Joining MQTT server\r\n");
 69
 70        /* Try to join */
 71        conn_status = lwesp_mqtt_client_api_connect(client, "mqtt.mydevices.com", 1883, &mqtt_client_info);
 72        if (conn_status == LWESP_MQTT_CONN_STATUS_ACCEPTED) {
 73            printf("Connected and accepted!\r\n");
 74            printf("Client is ready to subscribe and publish to new messages\r\n");
 75        } else {
 76            printf("Connect API response: %d\r\n", (int)conn_status);
 77            lwesp_delay(5000);
 78            continue;
 79        }
 80
 81        /* Subscribe to topics */
 82        sprintf(mqtt_topic_str, "v1/%s/things/%s/cmd/#", mqtt_client_info.user, mqtt_client_info.id);
 83        if (lwesp_mqtt_client_api_subscribe(client, mqtt_topic_str, LWESP_MQTT_QOS_AT_LEAST_ONCE) == lwespOK) {
 84            printf("Subscribed to topic\r\n");
 85        } else {
 86            printf("Problem subscribing to topic!\r\n");
 87        }
 88
 89        while (1) {
 90            /* Receive MQTT packet with 1000ms timeout */
 91            if ((res = lwesp_mqtt_client_api_receive(client, &buf, 5000)) == lwespOK) {
 92                if (buf != NULL) {
 93                    printf("Publish received!\r\n");
 94                    printf("Topic: %s, payload: %s\r\n", buf->topic, buf->payload);
 95                    lwesp_mqtt_client_api_buf_free(buf);
 96                    buf = NULL;
 97                }
 98            } else if (res == lwespCLOSED) {
 99                printf("MQTT connection closed!\r\n");
100                break;
101            } else if (res == lwespTIMEOUT) {
102                printf("Timeout on MQTT receive function. Manually publishing.\r\n");
103
104                /* Publish data on channel 1 */
105                prv_generate_random(random_str);
106                sprintf(mqtt_topic_str, "v1/%s/things/%s/data/1", mqtt_client_info.user, mqtt_client_info.id);
107                sprintf(mqtt_topic_data, "temp,c=%s", random_str);
108                lwesp_mqtt_client_api_publish(client, mqtt_topic_str, mqtt_topic_data, strlen(mqtt_topic_data),
109                                              LWESP_MQTT_QOS_AT_LEAST_ONCE, 0);
110            }
111        }
112        //goto terminate;
113    }
114
115terminate:
116    lwesp_mqtt_client_api_delete(client);
117    printf("MQTT client thread terminate\r\n");
118    lwesp_sys_thread_terminate(NULL);
119}
group LWESP_APP_MQTT_CLIENT_API

Sequential, single thread MQTT client API.

Typedefs

typedef struct lwesp_mqtt_client_api_buf *lwesp_mqtt_client_api_buf_p

Pointer to lwesp_mqtt_client_api_buf_t structure.

Functions

lwesp_mqtt_client_api_p lwesp_mqtt_client_api_new(size_t tx_buff_len, size_t rx_buff_len)

Create new MQTT client API.

Parameters
  • tx_buff_len[in] Maximal TX buffer for maximal packet length

  • rx_buff_len[in] Maximal RX buffer

Returns

Client handle on success, NULL otherwise

void lwesp_mqtt_client_api_delete(lwesp_mqtt_client_api_p client)

Delete client from memory.

Parameters

client[in] MQTT API client handle

lwesp_mqtt_conn_status_t lwesp_mqtt_client_api_connect(lwesp_mqtt_client_api_p client, const char *host, lwesp_port_t port, const lwesp_mqtt_client_info_t *info)

Connect to MQTT broker.

Parameters
  • client[in] MQTT API client handle

  • host[in] TCP host

  • port[in] TCP port

  • info[in] MQTT client info

Returns

LWESP_MQTT_CONN_STATUS_ACCEPTED on success, member of lwesp_mqtt_conn_status_t otherwise

lwespr_t lwesp_mqtt_client_api_close(lwesp_mqtt_client_api_p client)

Close MQTT connection.

Parameters

client[in] MQTT API client handle

Returns

lwespOK on success, member of lwespr_t otherwise

lwespr_t lwesp_mqtt_client_api_subscribe(lwesp_mqtt_client_api_p client, const char *topic, lwesp_mqtt_qos_t qos)

Subscribe to topic.

Parameters
  • client[in] MQTT API client handle

  • topic[in] Topic to subscribe on

  • qos[in] Quality of service. This parameter can be a value of lwesp_mqtt_qos_t

Returns

lwespOK on success, member of lwespr_t otherwise

lwespr_t lwesp_mqtt_client_api_unsubscribe(lwesp_mqtt_client_api_p client, const char *topic)

Unsubscribe from topic.

Parameters
  • client[in] MQTT API client handle

  • topic[in] Topic to unsubscribe from

Returns

lwespOK on success, member of lwespr_t otherwise

lwespr_t lwesp_mqtt_client_api_publish(lwesp_mqtt_client_api_p client, const char *topic, const void *data, size_t btw, lwesp_mqtt_qos_t qos, uint8_t retain)

Publish new packet to MQTT network.

Parameters
  • client[in] MQTT API client handle

  • topic[in] Topic to publish on

  • data[in] Data to send

  • btw[in] Number of bytes to send for data parameter

  • qos[in] Quality of service. This parameter can be a value of lwesp_mqtt_qos_t

  • retain[in] Set to 1 for retain flag, 0 otherwise

Returns

lwespOK on success, member of lwespr_t otherwise

uint8_t lwesp_mqtt_client_api_is_connected(lwesp_mqtt_client_api_p client)

Check if client MQTT connection is active.

Parameters

client[in] MQTT API client handle

Returns

1 on success, 0 otherwise

lwespr_t lwesp_mqtt_client_api_receive(lwesp_mqtt_client_api_p client, lwesp_mqtt_client_api_buf_p *p, uint32_t timeout)

Receive next packet in specific timeout time.

Note

This function can be called from separate thread than the rest of API function, which allows you to handle receive data separated with custom timeout

Parameters
  • client[in] MQTT API client handle

  • p[in] Pointer to output buffer

  • timeout[in] Maximal time to wait before function returns timeout

Returns

lwespOK on success, lwespCLOSED if MQTT is closed, lwespTIMEOUT on timeout

void lwesp_mqtt_client_api_buf_free(lwesp_mqtt_client_api_buf_p p)

Free buffer memory after usage.

Parameters

p[in] Buffer to free

struct lwesp_mqtt_client_api_buf_t
#include <lwesp_mqtt_client_api.h>

MQTT API RX buffer.

Public Members

char *topic

Topic data

size_t topic_len

Topic length

uint8_t *payload

Payload data

size_t payload_len

Payload length

lwesp_mqtt_qos_t qos

Quality of service