Morse Micro IoT SDK  2.9.7
mqttdemo.c File Reference

Detailed Description

MQTT example to demonstrate connecting to an MQTT broker, subscribing to a topic and publishing to a topic.

Note
It is assumed that you have followed the steps in the Getting Started guide and are therefore familiar with how to build, flash, and monitor an application using the MM-IoT-SDK framework.

mqttdemo.c is an example application that demonstrates how to use coreMQTT to connect to an MQTT broker and publish/subscribe to messages. This example was written based on the tutorial at https://www.freertos.org/mqtt/basic-mqtt-example.html.

In this example we attempt to connect to the public MQTT broker at test.mosquitto.org on port 1883. This example connects on the clear, but can be easily converted to use TLS by supplying NetworkCredentials_t to transport_connect().

Note
This example is single threaded and so publishes & subscribes in lock step in a single thread. If asynchronous publishes/subscribes are required, then this code will have to be modified to use a message queue and a single thread to handle the MQTT publishes/subscribes. Alternatively you may use the coreMQTT-Agent module which does this for you.

Getting Started

Using the app only

Simply compiling and running the application will show the application connecting to the public MQTT broker and then publishing a message to "/MorseMicro/<clientid>/topic" The clientid is unique to each device and in this example is based on the MAC address of the device.

The device also subscribes to the same topic, so if all is well you should see the message G'day World being displayed on the console.

Note
This application requires internet connectivity and DNS to connect to the public MQTT broker. Ensure your access point has DHCP and internet connectivity enabled.

Verifying the result with a third party MQTT Client

You can use a third party MQTT Client such as Mosquitto to independently verify the working of the application. You may download Mosquitto from https://mosquitto.org/download/

The above link also includes the Mosquitto MQTT server, which you may use to create a private MQTT broker for your application.

Run the mosquitto client using the following command:

mosquitto_sub -h test.mosquitto.org -p 1883 -t /MorseMicro/<clientid>/topic

Replace "<clientid>" with the client id of your device as displayed on the console.

Now run the application. You should see the message G'day World! appear on the MQTT client which confirms that the application has successfully connected to the MQTT broker and published a message.

Note
You may use mosquitto_pub to publish messages too. Documentation for mosquitto_sub is here: https://mosquitto.org/man/mosquitto_sub-1.html. And documentation for mosquitto_pub is here: https://mosquitto.org/man/mosquitto_pub-1.html.

Configuration

See Application helper routines for Wireless LAN interface for details of WLAN and IP stack configuration. Additional configuration options for this application can be found in the config.hjson file.

Troubleshooting

Connecting to server socket failed with code 7

The most common cause of this issue is AP configuration problems. Check if your device has access to the internet via your HaLow AP.

Another possible cause is a tcp socket timeout, which can occur due to issues on the broker side. If this occurs when using FreeRTOS+TCP as your IP stack, try increasing the ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME to allow the socket more time to receive a response.

If this error keeps occurring, try setting up a local MQTT broker and changing MQTT_BROKER_ENDPOINT to your computer's IP address.

Creating MQTT connection with broker failed with code 7

The main cause of this issue is issues with the Mosquitto test server, which can sometimes fail to respond before CONNACK_RECV_TIMEOUT_MS. Try increasing the timeout, or if the problem persists, try setting up a local MQTT broker and changing MQTT_BROKER_ENDPOINT to your computer's IP address.

Definition in file mqttdemo.c.

#include <string.h>
#include "mmosal.h"
#include "mmwlan.h"
#include "mmconfig.h"
#include "mmipal.h"
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#include "mbedtls/net.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
#include "core_mqtt.h"
#include "mm_app_common.h"
Include dependency graph for mqttdemo.c:

Go to the source code of this file.

Macros

#define CLIENT_ID_PREFIX   "MM_Client_%s"
 The MQTT client identifier used in this example. More...
 
#define MQTT_BROKER_ENDPOINT   "test.mosquitto.org"
 Broker address to connect to. More...
 
#define MQTT_BROKER_PORT   1883
 Broker port. More...
 
#define KEEP_ALIVE_TIMEOUT_SECONDS   60
 Keep alive Delay. More...
 
#define CONNACK_RECV_TIMEOUT_MS   10000
 Receive timeout. More...
 
#define DELAY_BETWEEN_PUBLISHES   1000
 Override the default FreeRTOS + TCP receive socket timeouts, as the test server can be slow to respond. More...
 
#define TOPIC_COUNT   1
 Number of topics we subscribe to. More...
 
#define TOPIC_FORMAT   "/MorseMicro/%s/topic"
 Topic to publish/subscribe, we include the client ID to keep it unique. More...
 
#define EXAMPLE_MESSAGE   "G'day World!"
 Message to publish/subscribe. More...
 
#define MAC_ADDR_STR_LEN   (18)
 Length of MAC address string (i.e., "XX:XX:XX:XX:XX:XX") including terminator. More...
 

Functions

static void MQTTProcessIncomingPublish (MQTTPublishInfo_t *pxPublishInfo)
 This callback gets called when a published message matches one of our subscribed topics. More...
 
static void MQTTProcessResponse (MQTTPacketInfo_t *pxIncomingPacket, uint16_t usPacketId)
 This callback gets called whenever we receive an ACK from the server. More...
 
static void EventCallback (MQTTContext_t *pxMQTTContext, MQTTPacketInfo_t *pxPacketInfo, MQTTDeserializedInfo_t *pxDeserializedInfo)
 This is a callback from MQTT_Process whenever a packet is received from the server. More...
 
MQTTStatus_t CreateMQTTConnectionToBroker (MQTTContext_t *pxMQTTContext, NetworkContext_t *pxNetworkContext, char *clientID)
 Initializes an MQTT connection with the server. More...
 
MQTTStatus_t MQTTSubscribe (MQTTContext_t *pxMQTTContext, const char *topic)
 Subscribes to the specified topic. More...
 
MQTTStatus_t MQTTUnsubscribeFromTopic (MQTTContext_t *pxMQTTContext, const char *topic)
 Unsubscribes from the specified topic. More...
 
MQTTStatus_t MQTTPublishToTopic (MQTTContext_t *pxMQTTContext, const char *topic, void *payload, size_t payloadLength)
 Publish a message to the specified MQTT topic. More...
 
void app_init (void)
 Main entry point to the application. More...
 

Variables

static unsigned char buf [1024]
 Statically allocated buffer for MQTT. More...
 

Macro Definition Documentation

◆ CLIENT_ID_PREFIX

#define CLIENT_ID_PREFIX   "MM_Client_%s"

The MQTT client identifier used in this example.

Each client identifier must be unique to ensure no two clients connecting to the same broker use the same client identifier.

Definition at line 116 of file mqttdemo.c.

◆ CONNACK_RECV_TIMEOUT_MS

#define CONNACK_RECV_TIMEOUT_MS   10000

Receive timeout.

Definition at line 134 of file mqttdemo.c.

◆ DELAY_BETWEEN_PUBLISHES

#define DELAY_BETWEEN_PUBLISHES   1000

Override the default FreeRTOS + TCP receive socket timeouts, as the test server can be slow to respond.

Delay in ms between publishes

Note
This is a single threaded demo, so increasing this delay will cause the application to sleep for extended periods of time and not respond to other messages.

Definition at line 148 of file mqttdemo.c.

◆ EXAMPLE_MESSAGE

#define EXAMPLE_MESSAGE   "G'day World!"

Message to publish/subscribe.

Definition at line 157 of file mqttdemo.c.

◆ KEEP_ALIVE_TIMEOUT_SECONDS

#define KEEP_ALIVE_TIMEOUT_SECONDS   60

Keep alive Delay.

Definition at line 132 of file mqttdemo.c.

◆ MAC_ADDR_STR_LEN

#define MAC_ADDR_STR_LEN   (18)

Length of MAC address string (i.e., "XX:XX:XX:XX:XX:XX") including terminator.

Definition at line 159 of file mqttdemo.c.

◆ MQTT_BROKER_ENDPOINT

#define MQTT_BROKER_ENDPOINT   "test.mosquitto.org"

Broker address to connect to.

This is a public test server and is not guaranteed to be always available. For production applications or extensive testing you should setup your own server. Mosquitto is one such free MQTT server that you can use.

Definition at line 123 of file mqttdemo.c.

◆ MQTT_BROKER_PORT

#define MQTT_BROKER_PORT   1883

Broker port.

Usually 1883 is used for communications in the clear and 8883 is used for TLS encrypted communications.

Definition at line 128 of file mqttdemo.c.

◆ TOPIC_COUNT

#define TOPIC_COUNT   1

Number of topics we subscribe to.

Definition at line 151 of file mqttdemo.c.

◆ TOPIC_FORMAT

#define TOPIC_FORMAT   "/MorseMicro/%s/topic"

Topic to publish/subscribe, we include the client ID to keep it unique.

Definition at line 154 of file mqttdemo.c.

Function Documentation

◆ app_init()

void app_init ( void  )

Main entry point to the application.

This will be invoked in a thread once operating system and hardware initialization has completed. It may return, but it does not have to.

Definition at line 464 of file mqttdemo.c.

◆ CreateMQTTConnectionToBroker()

MQTTStatus_t CreateMQTTConnectionToBroker ( MQTTContext_t *  pxMQTTContext,
NetworkContext_t *  pxNetworkContext,
char *  clientID 
)

Initializes an MQTT connection with the server.

Parameters
pxMQTTContextThe MQTT context
pxNetworkContextThe network context (socket)
clientIDOur unique Client ID string
Returns
Returns MQTTSuccess on success, else returns error code

Definition at line 281 of file mqttdemo.c.

◆ EventCallback()

static void EventCallback ( MQTTContext_t *  pxMQTTContext,
MQTTPacketInfo_t *  pxPacketInfo,
MQTTDeserializedInfo_t *  pxDeserializedInfo 
)
static

This is a callback from MQTT_Process whenever a packet is received from the server.

Parameters
pxMQTTContextThe MQTT context
pxPacketInfoThe packet info
pxDeserializedInfoThe de-serialized packet info

Definition at line 257 of file mqttdemo.c.

◆ MQTTProcessIncomingPublish()

static void MQTTProcessIncomingPublish ( MQTTPublishInfo_t *  pxPublishInfo)
static

This callback gets called when a published message matches one of our subscribed topics.

Parameters
pxPublishInfoThe received message

Definition at line 170 of file mqttdemo.c.

◆ MQTTProcessResponse()

static void MQTTProcessResponse ( MQTTPacketInfo_t *  pxIncomingPacket,
uint16_t  usPacketId 
)
static

This callback gets called whenever we receive an ACK from the server.

Parameters
pxIncomingPacketThe incoming packet
usPacketIdThe packet ID

Definition at line 205 of file mqttdemo.c.

◆ MQTTPublishToTopic()

MQTTStatus_t MQTTPublishToTopic ( MQTTContext_t *  pxMQTTContext,
const char *  topic,
void *  payload,
size_t  payloadLength 
)

Publish a message to the specified MQTT topic.

Parameters
pxMQTTContextThe MQTT context
topicThe topic top publish to
payloadA pointer to the binary or text data to publish
payloadLengthThe length of the data to publish
Returns
Returns MQTTSuccess on success, else returns error code

Definition at line 437 of file mqttdemo.c.

◆ MQTTSubscribe()

MQTTStatus_t MQTTSubscribe ( MQTTContext_t *  pxMQTTContext,
const char *  topic 
)

Subscribes to the specified topic.

Parameters
pxMQTTContextThe MQTT context
topicThe topic to subscribe to
Returns
Returns MQTTSuccess on success, else returns error code

Definition at line 348 of file mqttdemo.c.

◆ MQTTUnsubscribeFromTopic()

MQTTStatus_t MQTTUnsubscribeFromTopic ( MQTTContext_t *  pxMQTTContext,
const char *  topic 
)

Unsubscribes from the specified topic.

Parameters
pxMQTTContextThe MQTT context
topicThe topic to unsubscribe from
Returns
Returns MQTTSuccess on success, else returns error code

Definition at line 399 of file mqttdemo.c.

Variable Documentation

◆ buf

unsigned char buf[1024]
static

Statically allocated buffer for MQTT.

Definition at line 162 of file mqttdemo.c.