C
To make the API available to the application, the header file Serval_Mqtt.h has to be included in the implementation files
Additionally, in your project browse to
SDK > xdk110 > Libraries > ServalStack > 3rd-party > Serval Stack > api > Serval_Defines.hAnd set the define of SERVAL_ENABLE_MQTT to 1, if this is not already done. If this is set to 0, the API will not be available in the application.
/* system header files */
#include <stdio.h>
/* additional interface header files */
#include "FreeRTOS.h"
#include "timers.h"
// MQTT API
#include "Serval_Mqtt.h"
/* own header files */
#include "BCDS_CmdProcessor.h"
#include "BCDS_Assert.h"
#include "BCDS_NetworkConfig.h"
#include "BCDS_WlanConnect.h"
#include "PAL_initialize_ih.h"
#include "PAL_socketMonitor_ih.h"Some important constants and variables will be used throughout the guide. They are listed in the code below. The first two macros define the MQTT Host address and port respectively. The global variables for the session and a pointer to the session are relevant throughout the guide. The session must persist through the entire runtime of the MQTT application, as it will contain all the connection and server information, and is used by nearly every function of the MQTT API.
We create this function that will help us to initialized the wifi con the XDK
MQTT module must first be initialized. The initialization of the MQTT client is accomplished in two steps. First, the MQTT module itself is initialized by calling Mqtt_initialize(). Then, the variable session of type MqttSession_T is initialized.
As soon as the event MQTT_CONNECTION_ESTABLISHED occurs, it is possible to subscribe to a topic on the MQTT Server using Mqtt_subscribe().
The function Mqtt_subscribe() requires an array of topics and the corresponding Qualities of Service in another array. The first array is of type StringDescr_T, which is why each topic has to be wrapped into a StringDescr_T by using the function StringDescr_wrap. The array of QoS is of type Mqtt_qos_t, but the possible values are essentially numbers. The possible values are listed at the type definition of Mqtt_qos_t in Serval_Mqtt.h.
As soon as the event MQTT_CONNECTION_ESTABLISHED occurs, it is possible to publish on a topic on the MQTT Server to which the XDK is connected.
Parameters:
packetID
topicName
qos
retainFlag
payload
dupFlag
The current API is event-based. That means that the application reacts to every pre-defined event with a callback. The type of the variable eventData depends on the event.
The function handle_connection() is used in both MQTT_CONNECTION_ESTABLISHED and MQTT_CONNECTION_ERROR, because these events have the same data-type. It simply prints the connect return code sent by the server, at which the connection attempt was directed.
We declared the main function so we could initialized the application with all the methods that we all ready define.
Last updated
Was this helpful?