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
void networkSetup(void) {
WlanConnect_SSID_T connectSSID = (WlanConnect_SSID_T) "yourWifiNetworkSSID";
WlanConnect_PassPhrase_T connectPassPhrase = (WlanConnect_PassPhrase_T) "yourWifiNetworkPW";
WlanConnect_Init();
NetworkConfig_SetIpDhcp(0);
WlanConnect_WPA(connectSSID, connectPassPhrase, NULL);
PAL_initialize();
PAL_socketMonitorInit();
NetworkConfig_IpSettings_T myIp;
NetworkConfig_GetIpSettings(&myIp);
// insert a delay here, if the IP is not properly printed
printf("The IP was retrieved: %u.%u.%u.%u \n\r",
(unsigned int) (NetworkConfig_Ipv4Byte(myIp.ipV4, 3)),
(unsigned int) (NetworkConfig_Ipv4Byte(myIp.ipV4, 2)),
(unsigned int) (NetworkConfig_Ipv4Byte(myIp.ipV4, 1)),
(unsigned int) (NetworkConfig_Ipv4Byte(myIp.ipV4, 0)));
}
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.
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.