This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

LAUNCHCC3220MODASF: MQTT - Client <clientname> has exceeded timeout, disconnecting. Socket error on client <clientname>, disconnecting.

Part Number: LAUNCHCC3220MODASF
Other Parts Discussed in Thread: CC3220SF

Hi,

I am using the CC3220MODASF launchpad with mqtt_client_CC3220SF_LAUNCHXL_tirtos_ccs example  to send the data on local server using Mosquito broker on my computer. On which I am sending a timestamp to the Mosquito and saving this data. Also I am using the server with default configurations, except the QOS is set to 2

I have added some gpio to get the inputs from machine side, Now I am sending the data from launchpad to mosquitto broker.

But after starting a session it is sends the data to the server at most 2 days then launchpad client disconnects from mosquitto broker.

Earlier it is disconnecting within 5-7 minutes so I have free the memory allocated in program after publishing message on topic.

Before disconnecting it prints the following message in command line in mosquitto broker cmd window

- client <clientname> has exceeded timeout, disconnecting

- Socket error on client d436398c098c, disconnecting.

Here is the c file which I have modified:

4188.mqtt_client_app.c
#include <stdlib.h>
#include <pthread.h>
#include <mqueue.h>
#include <time.h>
#include <unistd.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>

#include <ti/drivers/GPIO.h>                                                    // TI-Driver includes
#include <ti/drivers/SPI.h>
#include <ti/drivers/I2C.h>
#include <ti/drivers/Timer.h>

#include <ti/drivers/net/wifi/simplelink.h>                                     // Simplelink includes

#include <ti/drivers/net/wifi/slnetifwifi.h>                                    // SlNetSock includes

#include <ti/net/mqtt/mqttclient.h>                                             // MQTT Library includes

#include "network_if.h"                                                         // Common interface includes
#include "uart_term.h"

#include "Board.h"                                                              // Application includes
#include "client_cbs.h"

#include "mqueue.h"
#include "time.h"

#include <ti/drivers/gpio/GPIOCC32xx.h>
#include <ti/drivers/timer/TimerCC32XX.h>
#include <ti/sysbios/knl/Clock.h>
//*****************************************************************************
//                          LOCAL DEFINES
//*****************************************************************************
#define CLNT_USR_PWD
#define CLIENT_INIT_STATE        (0x01)
#define MQTT_INIT_STATE          (0x04)

#define APPLICATION_VERSION      "1.1.1"
#define APPLICATION_NAME         "MQTT client"

#define SLNET_IF_WIFI_PRIO       (5)

#define MQTT_3_1_1               false                                              // Operate Lib in MQTT 3.1 mode.
#define MQTT_3_1                 true

#define WILL_TOPIC               "Client"
#define WILL_MSG                 "Client Stopped"
#define WILL_QOS                 MQTT_QOS_2
#define WILL_RETAIN              false

//#define SERVER_ADDRESS           "messagesight.demos.ibm.com"                     // Defining Broker IP address and port Number
#define SERVER_ADDRESS           "m2m.eclipse.org"
#define SERVER_IP_ADDRESS        "192.168.100.22"
#define PORT_NUMBER              1883
#define SECURED_PORT_NUMBER      8883
#define LOOPBACK_PORT            1882

#define CLEAN_SESSION            true                                               // Clean session flag

#define RETAIN_ENABLE            1                                                  // Retain Flag. Used in publish message.

#define TASKSTACKSIZE            2048                                           // Spawn task priority and Task and Thread Stack Size
#define RXTASKSIZE               4096
#define MQTTTHREADSIZE           2048
#define SPAWN_TASK_PRIORITY      9

// secured client requires time configuration, in order to verify server certificate validity (date).
#define DAY                      1                                              // Day of month (DD format) range 1-31
#define MONTH                    5                                              // Month (MM format) in the range of 1-12
#define YEAR                     2017                                           // Year (YYYY format)
#define HOUR                     12                                             // Hours in the range of 0-23
#define MINUTES                  33                                             // Minutes in the range of 0-59
#define SEC                      21                                             // Seconds in the range of 0-59


/* Number of files used for secure connection                                 */
#define CLIENT_NUM_SECURE_FILES  1

/* Expiration value for the timer that is being used to toggle the Led.       */
#define TIMER_EXPIRATION_VALUE   100 * 1000000

#define TMP006_DIE_TEMP 0x0001 /* Die Temp Result Register*/

//*****************************************************************************
//                      LOCAL FUNCTION PROTOTYPES
//*****************************************************************************
void pushButtonInterruptHandler2(uint_least8_t index);
void pushButtonInterruptHandler3(uint_least8_t index);
void cycleStartInterruptHandler(uint_least8_t index);
void cycleStopInterruptHandler(uint_least8_t index);
void materialShortInterruptHandler(uint_least8_t index);
void dieChangeInterruptHandler(uint_least8_t index);
void alarmInterruptHandler(uint_least8_t index);
void TimerPeriodicIntHandler(sigval val);
void LedTimerConfigNStart();
void LedTimerDeinitStop();
static void DisplayBanner(char * AppName);
void *MqttClient(void *pvParameters);
void Mqtt_ClientStop(uint8_t disconnect);
void Mqtt_ServerStop();
void Mqtt_Stop();
void Mqtt_start();
int32_t Mqtt_IF_Connect();
int32_t MqttServer_start();
int32_t MqttClient_start();
int32_t MQTT_SendMsgToQueue(struct msgQueue *queueElement);

//*****************************************************************************
//                 GLOBAL VARIABLES
//*****************************************************************************

/* Connection state: (0) - connected, (negative) - disconnected               */
int32_t gApConnectionState = -1;
uint32_t gInitState = 0;
uint32_t memPtrCounterfree = 0;
bool     gResetApplication = false;
static MQTTClient_Handle gMqttClient;
MQTTClient_Params  MqttClientExmple_params;
unsigned short g_usTimerInts;

/* Receive task handle                                                        */
pthread_t g_rx_task_hndl = (pthread_t) NULL;
uint32_t gUiConnFlag = 0;

/* AP Security Parameters                                                     */
SlWlanSecParams_t SecurityParams = { 0 };

/* Client ID                                                                  */
/* If ClientId isn't set, the MAC address of the device will be copied into the ClientID parameter.                                                    */
char ClientId[13] = {'\0'};

/* Client User Name and Password                                              */
const char *ClientUsername = "mqtt-user";
const char *ClientPassword = "mqtt-password";

unsigned char qos = MQTT_QOS_2;
/* Subscription topics and qos values                                         */
char *topic = "cc32xx/TimeSync" ;

/* Publishing topics and messages                                            */
const char *publish_topic0 = "cc32xx/ButtonPressEvtSw2";

const char *publish_CycleStart          =  "2";                // "cc32xx/CycleStart" ;
const char *publish_CycleStop           =  "3";                // "cc32xx/CycleStop";
const char *publish_MaterialShort       =  "4";                // "cc32xx/MaterialShort";
const char *publish_MaterialAvailable   =  "5";                // "cc32xx/MaterialAvailable";
const char *publish_DieChange_Begin     =  "6";                // "cc32xx/DieChange";
const char *publish_DieChange_End       =  "7";                // "cc32xx/DieChange";
const char *publish_OilLevel_Low        =  "8";                // cc32xx/OilLevel";
const char *publish_OilLevel_High       =  "9";                // cc32xx/OilLevel";
const char *publish_ConnStatus          =  "10";
const char *publish_Temp                =  "20";
const char *publish_Alarm_generated     =  "12";              // "cc32xx/Alarm";
const char *publish_Alarm_reset         =  "13";              // "cc32xx/Alarm";

/* Message Queue                                                              */
mqd_t g_PBQueue;
pthread_t mqttThread = (pthread_t) NULL;
pthread_t appThread = (pthread_t) NULL;
timer_t g_timer;

/* Printing new line                                                          */
char lineBreak[] = "\n\r";

SlDateTime_t ReaddateTime = {0};
int timercount = 0, TimeValue[6];
char *tok;
char str0[5], str1[3], str2[3], str3[3], str4[3], str5[3];
char *str, *dateTimeValue, *dateTimeVal;
char *readTemp;
int intrCount[6] = { 0,0,0,0,0,0 }, countVal[6] = { 0,0,0,0,0,0 };
uint32_t cycle_TimeCount[2], material_TimeCount[2], die_TimeCount[2], oil_TimeCount[2], alarm_TimeCount[2], test_TimeCount[2] ;

uint16_t temperature;
uint8_t txBuffer[1];
uint8_t rxBuffer[2];
I2C_Handle i2c;
I2C_Params i2cParams;
I2C_Transaction i2cTransaction;
Timer_Handle timer0;
Timer_Params timerParams;
//*****************************************************************************
//                 Banner VARIABLES
//*****************************************************************************
#ifdef  SECURE_CLIENT

char *Mqtt_Client_secure_files[CLIENT_NUM_SECURE_FILES] = {"ca-cert.pem"};

MQTTClient_ConnParams Mqtt_ClientCtx =
{
     MQTTCLIENT_NETCONN_IP4 | MQTTCLIENT_NETCONN_SEC,
     SERVER_IP_ADDRESS, //SERVER_ADDRESS,
     SECURED_PORT_NUMBER,//  PORT_NUMBER
     SLNETSOCK_SEC_METHOD_SSLv3_TLSV1_2,
     SLNETSOCK_SEC_CIPHER_FULL_LIST,
     CLIENT_NUM_SECURE_FILES,
     Mqtt_Client_secure_files
};

void setTime()
{
    SlDateTime_t dateTime = {0};
    dateTime.tm_day  = (uint32_t)DAY;
    dateTime.tm_mon  = (uint32_t)MONTH;
    dateTime.tm_year = (uint32_t)YEAR;
    dateTime.tm_hour = (uint32_t)HOUR;
    dateTime.tm_min  = (uint32_t)MINUTES;
    dateTime.tm_sec  = (uint32_t)SEC;
    sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_DATE_TIME, sizeof(SlDateTime_t), (uint8_t *)(&dateTime));
}
#else
MQTTClient_ConnParams Mqtt_ClientCtx =
{
    MQTTCLIENT_NETCONN_URL,
    SERVER_IP_ADDRESS,
    PORT_NUMBER, 0, 0, 0,
    NULL
};
#endif

MQTTClient_Will will_param =                                                            // Initialize the will_param structure to the default will parameters
{
    WILL_TOPIC,
    WILL_MSG,
    WILL_QOS,
    WILL_RETAIN
};

int32_t MQTT_SendMsgToQueue(struct msgQueue *queueElement)
{
    struct timespec abstime = {0};
    clock_gettime(CLOCK_REALTIME, &abstime);

    if(g_PBQueue)
    {
        if (mq_timedsend(g_PBQueue, (char *) queueElement, sizeof(struct msgQueue), 0, &abstime) == 0)              // send message to the queue
        {
            return 0;
        }
    }
    return -1;
}

struct subMsgHeader
{
    uint32_t        stopicLen;
    uint32_t        spayLen;
    bool            sretain;
    bool            sdup;
    unsigned char   sqos;
};

void TimeSync()
{
    SlDateTime_t TSdateTime = {0};

    TSdateTime.tm_year = (uint32_t)TimeValue[0];
    TSdateTime.tm_mon  = (uint32_t)TimeValue[1];
    TSdateTime.tm_day  = (uint32_t)TimeValue[2];
    TSdateTime.tm_hour = (uint32_t)TimeValue[3];
    TSdateTime.tm_min  = (uint32_t)TimeValue[4];
    TSdateTime.tm_sec  = (uint32_t)TimeValue[5];
    sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_DATE_TIME, sizeof(SlDateTime_t), (uint8_t *)(&TSdateTime));
}

char* readDateandTime()
{
    SlDateTime_t dateTime =  {0};
    _u16 configLen = sizeof (SlDateTime_t);
    _u8 configOpt = SL_DEVICE_GENERAL_DATE_TIME;
    sl_DeviceGet(SL_DEVICE_GENERAL,&configOpt, &configLen,(_u8 *)(&dateTime));

    str = (char *) malloc (15*sizeof(char));
    sprintf (str0, "%04d-", dateTime.tm_year);
    sprintf (str1, "%02d-", dateTime.tm_mon);
    sprintf (str2, "%02d ", dateTime.tm_day);
    sprintf (str3, "%02d:", dateTime.tm_hour);
    sprintf (str4, "%02d:", dateTime.tm_min);
    sprintf (str5, "%02d ", dateTime.tm_sec);

    strcpy (str, str0);
    strcat (str, str1);
    strcat (str, str2);
    strcat (str, str3);
    strcat (str, str4);
    strcat (str, str5);

    return str;
}


void i2cTransferCallbackFxn(I2C_Handle handle, I2C_Transaction *transaction, bool transferStatus)
{
    if (transferStatus)
    {
        temperature = (rxBuffer[0] << 6) | (rxBuffer[1] >> 2);
        if (rxBuffer[0] & 0x80)
        {
            temperature |= 0xF000;
        }
        temperature /= 32;

        struct msgQueue queueElement;

        queueElement.event = PUBLISH_TEMPERATURE;
        queueElement.msgPtr = NULL;
        if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
        {
            UART_PRINT("\n\n\rQueue is full\n\n\r");
        }
    }
    else
    {
        UART_PRINT("I2C Bus fault");
    }

    I2C_close(i2c);
    timercount = 0 ;
}


void timerCallback()
{
    if ( timercount == 2 )
    {
        I2C_Params_init(&i2cParams);
        i2cParams.bitRate = I2C_400kHz;
        i2cParams.transferMode = I2C_MODE_CALLBACK; //Switched
        i2cParams.transferCallbackFxn = i2cTransferCallbackFxn; // Add this
        i2c = I2C_open(Board_I2C_TMP, &i2cParams);

        if (i2c == NULL)
        {
            UART_PRINT("Error Initializing I2C");
            while (1);
        }

        I2C_transfer(i2c, &i2cTransaction);
    }

    else
    {
        timercount += 1;
    }
}


void cycleInterruptHandler(uint_least8_t index)
{
    if ( !intrCount[0] && ( GPIO_read ( Board_GPIO_Cycle ) == 1 ) )
    {
        cycle_TimeCount[0] = Clock_getTicks();

        if (  countVal[0]  == 0 || ( cycle_TimeCount[0] - cycle_TimeCount[1] )  >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_Cycle);


            queueElement.event = PUBLISH_CYCLE_START;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[0] = !intrCount[0];
    }

    else if ( intrCount[0] && ( GPIO_read ( Board_GPIO_Cycle ) == 0 ) )
    {
        cycle_TimeCount[1] = Clock_getTicks();

        if ( ( cycle_TimeCount[1] - cycle_TimeCount[0] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_Cycle);

            queueElement.event = PUBLISH_CYCLE_STOP;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[0] = !intrCount[0];
        countVal[0] ++;
    }
}

void materialShortInterruptHandler(uint_least8_t index)
{
    if ( !intrCount[1] && ( GPIO_read ( Board_GPIO_Material ) == 1 ) )
    {
        material_TimeCount[0] = Clock_getTicks();

        if (  countVal[1]  == 0 || ( material_TimeCount[0] - material_TimeCount[1] ) >= 100 )
        {
            struct msgQueue queueElement;

            queueElement.event = PUBLISH_MATERIAL_AVAILABLE;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }
        intrCount[1] = !intrCount[1];
    }

    else if ( intrCount[1] && ( GPIO_read ( Board_GPIO_Material ) == 0 ) )
    {
        material_TimeCount[1] = Clock_getTicks();

        if ( ( material_TimeCount[1] - material_TimeCount[0] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_Material);

            queueElement.event = PUBLISH_MATERIAL_SHORT;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[1] = !intrCount[1];
        countVal[1] ++;
    }
}

void dieChangeInterruptHandler(uint_least8_t index)
{
    if ( !intrCount[2] && ( GPIO_read ( Board_GPIO_DiaChange ) == 1 ) )
    {
        die_TimeCount[0] = Clock_getTicks();

        if (  countVal[2]  == 0 || ( die_TimeCount[0] - die_TimeCount[1] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_DiaChange);

            queueElement.event = PUBLISH_DIA_CHANGE_BEGIN;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[2] = !intrCount[2];
    }

    else if ( intrCount[2] && ( GPIO_read ( Board_GPIO_DiaChange ) == 0 ) )
    {
        die_TimeCount[1] = Clock_getTicks();

        if ( ( die_TimeCount[1] - die_TimeCount[0] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_DiaChange);

            queueElement.event = PUBLISH_DIA_CHANGE_END;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[2] = !intrCount[2];
        countVal[2]++ ;
    }
}

/*void oilLevelInterruptHandler(uint_least8_t index)
{
    if ( !intrCount[3] && ( GPIO_read ( Board_GPIO_OilLevel ) == 1 ) )
        {
            oil_TimeCount[0] = Clock_getTicks();

            if (  countVal[3]  == 0 || ( oil_TimeCount [0] - oil_TimeCount [1] ) >= 100 )
            {
                struct msgQueue queueElement;
                GPIO_disableInt(Board_GPIO_OilLevel);

                queueElement.event = PUBLISH_MACHINE_OILLEVEL_LOW;
                queueElement.msgPtr = NULL;
                if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
                {
                    UART_PRINT("\n\n\rQueue is full\n\n\r");
                }
            }

            intrCount[3] = !intrCount[3];
        }

        else if ( intrCount[3] && ( GPIO_read ( Board_GPIO_OilLevel ) == 0 ) )
        {
            oil_TimeCount[1] = Clock_getTicks();

            if ( ( oil_TimeCount[1] - oil_TimeCount[0] ) >= 100 )
            {
                struct msgQueue queueElement;
                GPIO_disableInt(Board_GPIO_OilLevel);

                queueElement.event = PUBLISH_MACHINE_OILLEVEL_HIGH;
                queueElement.msgPtr = NULL;
                if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
                {
                    UART_PRINT("\n\n\rQueue is full\n\n\r");
                }
            }

            intrCount[3] = !intrCount[3];
            countVal[3]++ ;
        }
}*/

void alarmInterruptHandler(uint_least8_t index)
{

    if ( !intrCount[4] && ( GPIO_read ( Board_GPIO_Alarm ) == 1 ) )
        {
            alarm_TimeCount[0] = Clock_getTicks();

            if ( countVal[4]  == 0 || ( alarm_TimeCount[0] - alarm_TimeCount[1] ) >= 100 )
            {
                struct msgQueue queueElement;
                GPIO_disableInt(Board_GPIO_Alarm);

                queueElement.event = PUBLISH_MACHINE_ALARM_GENERATED;
                queueElement.msgPtr = NULL;
                if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
                {
                    UART_PRINT("\n\n\rQueue is full\n\n\r");
                }
            }

            intrCount[4] = !intrCount[4];
        }

        else if ( intrCount[4] && ( GPIO_read ( Board_GPIO_Alarm ) == 0 ) )
        {
            alarm_TimeCount[1] = Clock_getTicks();

            if ( ( alarm_TimeCount[1] - alarm_TimeCount[0] ) >= 100 )
            {
                struct msgQueue queueElement;
                GPIO_disableInt(Board_GPIO_Alarm);

                queueElement.event = PUBLISH_MACHINE_ALARM_RESET;
                queueElement.msgPtr = NULL;
                if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
                {
                    UART_PRINT("\n\n\rQueue is full\n\n\r");
                }
            }

            intrCount[4] = !intrCount[4];
            countVal[4]++ ;
        }
}


void testInterruptHandler(uint_least8_t index)
{
    if ( !intrCount[5] && ( GPIO_read ( Board_GPIO_test ) == 1 ) )
    {
        test_TimeCount[0] = Clock_getTicks();

        if (  countVal[5]  == 0 || ( test_TimeCount[0] - test_TimeCount[1] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_test);

            queueElement.event = PUBLISH_MACHINE_OILLEVEL_LOW;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[5] = !intrCount[5];
    }

    else if ( intrCount[5] && ( GPIO_read ( Board_GPIO_test ) == 0 ) )
    {
        test_TimeCount[1] = Clock_getTicks();

        if ( ( test_TimeCount[1] - test_TimeCount[0] ) >= 100 )
        {
            struct msgQueue queueElement;
            GPIO_disableInt(Board_GPIO_test);

            queueElement.event = PUBLISH_MACHINE_OILLEVEL_HIGH;
            queueElement.msgPtr = NULL;
            if (MQTT_SendMsgToQueue(&queueElement))                                             // write message indicating publish message
            {
                UART_PRINT("\n\n\rQueue is full\n\n\r");
            }
        }

        intrCount[5] = !intrCount[5];
        countVal[5]++ ;
    }
}


void TimerPeriodicIntHandler(sigval val)
{
    g_usTimerInts++;                                                                    // Increment our interrupt counter.

    if (!(g_usTimerInts & 0x1))
    {
        GPIO_write(Board_GPIO_LED0, Board_GPIO_LED_OFF);                                // Turn Led Off
    }
    else
    {
        GPIO_write(Board_GPIO_LED0, Board_GPIO_LED_ON);                                 // Turn Led On
    }
}

void LedTimerConfigNStart()
{
    struct itimerspec value;
    sigevent sev;

    sev.sigev_notify = SIGEV_SIGNAL;                                                    // Create Timer
    sev.sigev_notify_function = &TimerPeriodicIntHandler;
    timer_create(2, &sev, &g_timer);

    value.it_interval.tv_sec = 0;                                                       // start timer
    value.it_interval.tv_nsec = TIMER_EXPIRATION_VALUE;
    value.it_value.tv_sec = 0;
    value.it_value.tv_nsec = TIMER_EXPIRATION_VALUE;

    timer_settime(g_timer, 0, &value, NULL);
}


void LedTimerDeinitStop()
{
    /* Disable the LED blinking Timer as Device is connected to AP.           */
    timer_delete(g_timer);
}


static void DisplayBanner(char * AppName)
{
    UART_PRINT("\n\n\n\r");
    UART_PRINT("\t\t *************************************************\n\r");
    UART_PRINT("\t\t    CC3220 %s Application       \n\r", AppName);
    UART_PRINT("\t\t *************************************************\n\r");
    UART_PRINT("\n\n\n\r");
}


void *MqttClientThread(void * pvParameters)
{
    struct msgQueue queueElement;
    struct msgQueue queueElemRecv;

    MQTTClient_run((MQTTClient_Handle)pvParameters);

    queueElement.event  = LOCAL_CLIENT_DISCONNECTION;
    queueElement.msgPtr = NULL;

    /* write message indicating disconnect Broker message.                    */
    if (MQTT_SendMsgToQueue(&queueElement))
    {
        UART_PRINT("\n\n\rQueue is full, throw first msg and send the new one\n\n\r");
        mq_receive(g_PBQueue, (char*) &queueElemRecv, sizeof(struct msgQueue), NULL);
        MQTT_SendMsgToQueue(&queueElement);
    }
    pthread_exit(0);
    return NULL;
}


void * MqttClient(void *pvParameters)
{

    struct msgQueue queueElemRecv;
    long lRetVal = -1;
    struct publishMsgHeader *publishMsgHeaderptr;
    uint32_t topicLen, payLen;
    char *topic, *payload, *messagePtr;
    int m;


    /* Initializing Client and Subscribing to the Broker.                     */
    if (gApConnectionState >= 0)
    {
        lRetVal = MqttClient_start();
        if (lRetVal == -1)
        {
            UART_PRINT("MQTT Client lib initialization failed\n\r");
            pthread_exit(0);
            return NULL;
        }
    }


    for (;;)
    {

        /* waiting for signals                                                */
        mq_receive(g_PBQueue, (char*) &queueElemRecv, sizeof(struct msgQueue), NULL);

        switch (queueElemRecv.event)
        {

          case PUBLISH_CYCLE_START:

              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_CycleStart, strlen((char*) publish_CycleStart), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_CycleStart);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_Cycle);
              GPIO_enableInt(Board_GPIO_Cycle);

              break;

          case PUBLISH_CYCLE_STOP:
              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_CycleStop, strlen((char*) publish_CycleStop), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_CycleStop);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_Cycle);
              GPIO_enableInt(Board_GPIO_Cycle);

              break;

          case PUBLISH_MATERIAL_SHORT:
             dateTimeValue =  readDateandTime();

             lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_MaterialShort, strlen((char*) publish_MaterialShort), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

             UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
             UART_PRINT("Topic: %s\n\r", publish_MaterialShort);
             UART_PRINT("Data: %s\n\r", dateTimeValue);
             free(dateTimeValue);

             GPIO_clearInt(Board_GPIO_Material);
             GPIO_enableInt(Board_GPIO_Material);
             break;

          case PUBLISH_MATERIAL_AVAILABLE:
             dateTimeValue =  readDateandTime();

             lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_MaterialAvailable, strlen((char*) publish_MaterialAvailable), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

             UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
             UART_PRINT("Topic: %s\n\r", publish_MaterialAvailable);
             UART_PRINT("Data: %s\n\r", dateTimeValue);
             free(dateTimeValue);

             GPIO_clearInt(Board_GPIO_Material);
             GPIO_enableInt(Board_GPIO_Material);

             break;

          case PUBLISH_DIA_CHANGE_BEGIN:
              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_DieChange_Begin, strlen((char*) publish_DieChange_Begin), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_DieChange_Begin);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_DiaChange);
              GPIO_enableInt(Board_GPIO_DiaChange);

              break;

          case PUBLISH_DIA_CHANGE_END:
              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_DieChange_End, strlen((char*) publish_DieChange_End), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_DieChange_End);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_DiaChange);
              GPIO_enableInt(Board_GPIO_DiaChange);
              break;

          case PUBLISH_MACHINE_OILLEVEL_LOW:
              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_OilLevel_Low, strlen((char*) publish_OilLevel_Low), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_OilLevel_Low);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_test);
              GPIO_enableInt(Board_GPIO_test);

              break;

          case PUBLISH_MACHINE_OILLEVEL_HIGH:
              dateTimeValue =  readDateandTime();

              lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_OilLevel_High, strlen((char*) publish_OilLevel_High), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

              UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
              UART_PRINT("Topic: %s\n\r", publish_OilLevel_High);
              UART_PRINT("Data: %s\n\r", dateTimeValue);
              free(dateTimeValue);

              GPIO_clearInt(Board_GPIO_test);
              GPIO_enableInt(Board_GPIO_test);
              break;

          case PUBLISH_MACHINE_ALARM_GENERATED:
               dateTimeValue =  readDateandTime();

               lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_Alarm_generated, strlen((char*) publish_Alarm_generated), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

               UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
               UART_PRINT("Topic: %s\n\r", publish_Alarm_generated);
               UART_PRINT("Data: %s\n\r", dateTimeValue);
               free(dateTimeValue);

               GPIO_clearInt(Board_GPIO_Alarm);
               GPIO_enableInt(Board_GPIO_Alarm);
               break;

          case PUBLISH_MACHINE_ALARM_RESET:
               dateTimeValue =  readDateandTime();

               lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_Alarm_reset, strlen((char*) publish_Alarm_reset), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

               UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
               UART_PRINT("Topic: %s\n\r", publish_Alarm_reset);
               UART_PRINT("Data: %s\n\r", dateTimeValue);
               free(dateTimeValue);

               GPIO_clearInt(Board_GPIO_Alarm);
               GPIO_enableInt(Board_GPIO_Alarm);
               break;


            case PUBLISH_TEMPERATURE:
                readTemp = (char *) malloc (15*sizeof(char));
                sprintf(readTemp, "%d", temperature);

                lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_Temp, strlen((char*) publish_Temp), (char*) readTemp, strlen((char*) readTemp), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

                UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
                UART_PRINT("Topic: %s\n\r", publish_Temp);
                UART_PRINT("Data: %s\n\r", readTemp);
                free(readTemp);

                break;

            case PUBLISH_MACHINE_CONNSTATUS:
                dateTimeValue =  readDateandTime();

                lRetVal = MQTTClient_publish(gMqttClient, (char*) publish_ConnStatus, strlen((char*) publish_ConnStatus), (char*) dateTimeValue, strlen((char*) dateTimeValue), MQTT_QOS_2 | ((RETAIN_ENABLE)?MQTT_PUBLISH_RETAIN:0) );

                UART_PRINT("\n\r CC3200 Publishes the following message \n\r");             // send publish message
                UART_PRINT("Topic: %s\n\r", publish_ConnStatus);
                UART_PRINT("Data: %s\n\r", dateTimeValue);
                free(dateTimeValue);

                break;

            case MSG_RECV_BY_CLIENT:

                    messagePtr = (char *) queueElemRecv.msgPtr;
                    publishMsgHeaderptr = malloc(sizeof(struct publishMsgHeader));
                    memcpy((void *) publishMsgHeaderptr, (const void *) messagePtr, sizeof(struct publishMsgHeader));

                    topicLen = publishMsgHeaderptr->topicLen;
                    payLen = publishMsgHeaderptr->payLen;

                    topic = malloc(topicLen);
                    memcpy((void*) topic, ((const void*) (messagePtr + sizeof(struct publishMsgHeader))), topicLen);

                    payload = malloc(payLen);
                    memcpy((void*) payload, (const void*) (messagePtr + sizeof(struct publishMsgHeader) + topicLen + 1), payLen);

                    if(strcmp(topic, "cc32xx/TimeSync") == 0)
                    {
                        tok = strtok (payload, ",");
                        for (m = 0; tok != NULL; m++)
                        {
                          TimeValue[m] = atoi(tok);
                          tok = strtok (NULL, ",");
                        }
                        TimeSync();
                    }

                free(queueElemRecv.msgPtr);
                free(publishMsgHeaderptr);
                free(topic);
                free(payload);
                break;


            case LOCAL_CLIENT_DISCONNECTION:
                UART_PRINT("\n\rOn-board Client Disconnected\n\r\r\n");
                gUiConnFlag = 0;
                break;


            case THREAD_TERMINATE_REQ:
                gUiConnFlag = 0;
                pthread_exit(0);
                return NULL;

            default:
                sleep(1);
                break;
        }
    }
}

int32_t Mqtt_IF_Connect()
{
    int32_t lRetVal;
    char SSID_Remote_Name[32];
    int8_t Str_Length;

    memset(SSID_Remote_Name, '\0', sizeof(SSID_Remote_Name));
    Str_Length = strlen(SSID_NAME);

    if (Str_Length)
    {
        /* Copy the Default SSID to the local variable                        */
        strncpy(SSID_Remote_Name, SSID_NAME, Str_Length);
    }

    /* Display Application Banner                                             */
    DisplayBanner(APPLICATION_NAME);

    GPIO_write(Board_GPIO_LED0, Board_GPIO_LED_OFF);
    GPIO_write(Board_GPIO_LED1, Board_GPIO_LED_OFF);
    GPIO_write(Board_GPIO_LED2, Board_GPIO_LED_OFF);

    /* Reset The state of the machine                                         */
    Network_IF_ResetMCUStateMachine();

    /* Start the driver                                                       */
    lRetVal = Network_IF_InitDriver(ROLE_STA);
    if (lRetVal < 0)
    {
        UART_PRINT("Failed to start SimpleLink Device\n\r", lRetVal);
        return -1;
    }

    /* switch on Green LED to indicate Simplelink is properly up.             */
    GPIO_write(Board_GPIO_LED2, Board_GPIO_LED_ON);

    /* Start Timer to blink Red LED till AP connection                        */
    LedTimerConfigNStart();

    /* Initialize AP security params                                          */
    SecurityParams.Key = (signed char *) SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    /* Connect to the Access Point                                            */
    lRetVal = Network_IF_ConnectAP(SSID_Remote_Name, SecurityParams);
    if (lRetVal < 0)
    {
        UART_PRINT("Connection to an AP failed\n\r");
        return -1;
    }

    /* Disable the LED blinking Timer as Device is connected to AP.           */
    LedTimerDeinitStop();

    /* Switch ON RED LED to indicate that Device acquired an IP.              */
    GPIO_write(Board_GPIO_LED0, Board_GPIO_LED_ON);

    sleep(1);

    GPIO_write(Board_GPIO_LED0, Board_GPIO_LED_OFF);
    GPIO_write(Board_GPIO_LED1, Board_GPIO_LED_OFF);
    GPIO_write(Board_GPIO_LED2, Board_GPIO_LED_OFF);

    return 0;
}

void Mqtt_start()
{
    int32_t threadArg = 100;
    pthread_attr_t pAttrs;
    struct sched_param priParam;
    int32_t retc = 0;
    mq_attr attr;
    unsigned mode = 0;

    /* sync object for inter thread communication                             */
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = sizeof(struct msgQueue);
    g_PBQueue = mq_open("g_PBQueue", O_CREAT, mode, &attr);

    if (g_PBQueue == NULL)
    {
        UART_PRINT("MQTT Message Queue create fail\n\r");
        gInitState &= ~MQTT_INIT_STATE;
        return;
    }

    /* Set priority and stack size attributes                                 */
    pthread_attr_init(&pAttrs);
    priParam.sched_priority = 2;
    retc = pthread_attr_setschedparam(&pAttrs, &priParam);
    retc |= pthread_attr_setstacksize(&pAttrs, MQTTTHREADSIZE);
    retc |= pthread_attr_setdetachstate(&pAttrs, PTHREAD_CREATE_DETACHED);

    if (retc != 0)
    {
        gInitState &= ~MQTT_INIT_STATE;
        UART_PRINT("MQTT thread create fail\n\r");
        return;
    }

    retc = pthread_create(&mqttThread, &pAttrs, MqttClient, (void *) &threadArg);
    if (retc != 0)
    {
        gInitState &= ~MQTT_INIT_STATE;
        UART_PRINT("MQTT thread create fail\n\r");
        return;
    }


    GPIO_setCallback(Board_GPIO_Cycle, cycleInterruptHandler);
    GPIO_enableInt(Board_GPIO_Cycle);
    GPIO_setCallback(Board_GPIO_Material, materialShortInterruptHandler);
    GPIO_enableInt(Board_GPIO_Material);
    GPIO_setCallback(Board_GPIO_DiaChange, dieChangeInterruptHandler);
    GPIO_enableInt(Board_GPIO_DiaChange);
/*    GPIO_setCallback(Board_GPIO_OilLevel, oilLevelInterruptHandler);
    GPIO_enableInt(Board_GPIO_OilLevel);*/
    GPIO_setCallback(Board_GPIO_Alarm, alarmInterruptHandler);
    GPIO_enableInt(Board_GPIO_Alarm);
    GPIO_setCallback(Board_GPIO_test, testInterruptHandler);
    GPIO_enableInt(Board_GPIO_test);

    gInitState &= ~MQTT_INIT_STATE;
}


void Mqtt_Stop()
{
    struct msgQueue queueElement;
    struct msgQueue queueElemRecv;

    if (gApConnectionState >= 0)
    {
        Mqtt_ClientStop(1);
    }

    queueElement.event = THREAD_TERMINATE_REQ;
    queueElement.msgPtr = NULL;

    if (MQTT_SendMsgToQueue(&queueElement))                                                 // write message indicating publish message
    {
        UART_PRINT("\n\n\rQueue is full, throw first msg and send the new one\n\n\r");
        mq_receive(g_PBQueue, (char*) &queueElemRecv, sizeof(struct msgQueue), NULL);
        MQTT_SendMsgToQueue(&queueElement);
    }

    sleep(2);

    mq_close(g_PBQueue);
    g_PBQueue = NULL;


    sl_Stop(SL_STOP_TIMEOUT);
    UART_PRINT("\n\r Client Stop completed\r\n");

    GPIO_disableInt(Board_GPIO_Cycle);
    GPIO_disableInt(Board_GPIO_Material);
    GPIO_disableInt(Board_GPIO_DiaChange);
    GPIO_disableInt(Board_GPIO_OilLevel);
    GPIO_disableInt(Board_GPIO_Alarm);
    GPIO_disableInt(Board_GPIO_test);
}

int32_t MqttClient_start()
{
    int32_t lRetVal = -1;

    int32_t threadArg = 100;
    pthread_attr_t pAttrs;
    struct sched_param priParam;

    MqttClientExmple_params.clientId = ClientId;
    MqttClientExmple_params.connParams = &Mqtt_ClientCtx;
    MqttClientExmple_params.mqttMode31 = MQTT_3_1;
    MqttClientExmple_params.blockingSend = true;

    gInitState |= CLIENT_INIT_STATE;

    gMqttClient = MQTTClient_create(MqttClientCallback, &MqttClientExmple_params);                                      // Initialize MQTT client lib
    if( gMqttClient == NULL )
    {
        gInitState &= ~CLIENT_INIT_STATE;                                                                               // lib initialization failed
        return -1;
    }

    /* Open Client Receive Thread start the receive task. Set priority and stack size attributes                                                  */
    pthread_attr_init(&pAttrs);
    priParam.sched_priority = 2;
    lRetVal = pthread_attr_setschedparam(&pAttrs, &priParam);
    lRetVal |= pthread_attr_setstacksize(&pAttrs, RXTASKSIZE);
    lRetVal |= pthread_attr_setdetachstate(&pAttrs, PTHREAD_CREATE_DETACHED);
    lRetVal |= pthread_create(&g_rx_task_hndl, &pAttrs, MqttClientThread, (void *) &threadArg);
    if (lRetVal != 0)
    {
        UART_PRINT("Client Thread Create Failed failed\n\r");
        gInitState &= ~CLIENT_INIT_STATE;
        return -1;
    }


#ifdef SECURE_CLIENT
    setTime();
#endif

    MQTTClient_set(gMqttClient, MQTTClient_WILL_PARAM, &will_param, sizeof(will_param));                                // setting will parameters

#ifdef CLNT_USR_PWD
    MQTTClient_set(gMqttClient, MQTTClient_USER_NAME, (void *)ClientUsername, strlen((char*)ClientUsername));           // Set user name for client connection
    MQTTClient_set(gMqttClient, MQTTClient_PASSWORD, (void *)ClientPassword, strlen((char*)ClientPassword));            // Set password
#endif

    if (gApConnectionState >= 0)                                                                                        // Initiate MQTT Connect
    {
#if CLEAN_SESSION == false
        bool clean = CLEAN_SESSION;
        MQTTClient_set(gMqttClient, MQTTClient_CLEAN_CONNECT, (void *)&clean, sizeof(bool));
#endif

        /* The return code of MQTTClient_connect is the ConnACK value that returns from the server */
        lRetVal = MQTTClient_connect(gMqttClient);
        /* negative lRetVal means error, 0 means connection successful without session stored by the server, greater than 0 means successful connection with session stored by the server */

        if (0 > lRetVal)
        {
            UART_PRINT("Connection to broker failed, Error code: %d\n\r", lRetVal);                 // lib initialization failed
            gUiConnFlag = 0;
        }
        else
        {
            gUiConnFlag = 1;
        }

        /* Subscribe to topics when session is not stored by the server       */
        if ( (gUiConnFlag == 1) && (0 == lRetVal) )
        {

            MQTTClient_SubscribeParams subscriptionInfo[1];

              subscriptionInfo[0].topic = topic;
              subscriptionInfo[0].qos = qos;


            if (MQTTClient_subscribe(gMqttClient , subscriptionInfo, 1) < 0)
            {
                UART_PRINT("\n\r Subscription Error \n\r");
                MQTTClient_disconnect(gMqttClient);
                gUiConnFlag = 0;
            }
            else
            {

                    UART_PRINT("Client subscribed on %s\n\r,", topic);
                    MQTTClient_publish(gMqttClient, (char*) publish_ConnStatus, strlen((char*)publish_ConnStatus), (char*) "1", 1, MQTT_QOS_2 | MQTT_PUBLISH_RETAIN );
            }
        }
    }
    gInitState &= ~CLIENT_INIT_STATE;
    return 0;
}


void Mqtt_ClientStop(uint8_t disconnect)
{
    MQTTClient_UnsubscribeParams subscriptionInfo[1];

    subscriptionInfo[0].topic = topic;

    MQTTClient_unsubscribe(gMqttClient , subscriptionInfo, 1);
    UART_PRINT("Unsubscribed from the topic %s\r\n", topic);
    MQTTClient_publish(gMqttClient, (char*) publish_ConnStatus, strlen((char*)publish_ConnStatus), (char*) "0", 1, MQTT_QOS_2 | MQTT_PUBLISH_RETAIN );

    gUiConnFlag = 0;
    MQTTClient_delete(gMqttClient);                                             // exiting the Client library
}

void printBorder(char ch, int n)
{
    int        i = 0;

    for(i=0; i<n; i++)    putch(ch);
}

void SetClientIdNamefromMacAddress(uint8_t *macAddress)
{
    uint8_t Client_Mac_Name[2];
    uint8_t Index;

    /* When ClientID isn't set, use the mac address as ClientID               */
    if (ClientId[0] == '\0')
    {
        /* 6 bytes is the length of the mac address                           */
        for (Index = 0; Index < SL_MAC_ADDR_LEN; Index++)
        {
            /* Each mac address byte contains two hexadecimal characters      */
            /* Copy the 4 MSB - the most significant character                */
            Client_Mac_Name[0] = (macAddress[Index] >> 4) & 0xf;
            /* Copy the 4 LSB - the least significant character               */
            Client_Mac_Name[1] = macAddress[Index] & 0xf;

            if (Client_Mac_Name[0] > 9)
            {
                /* Converts and copies from number that is greater than 9 in  */
                /* hexadecimal representation (a to f) into ascii character   */
                ClientId[2 * Index] = Client_Mac_Name[0] + 'a' - 10;
            }
            else
            {
                /* Converts and copies from number 0 - 9 in hexadecimal       */
                /* representation into ascii character                        */
                ClientId[2 * Index] = Client_Mac_Name[0] + '0';
            }
            if (Client_Mac_Name[1] > 9)
            {
                /* Converts and copies from number that is greater than 9 in  */
                /* hexadecimal representation (a to f) into ascii character   */
                ClientId[2 * Index + 1] = Client_Mac_Name[1] + 'a' - 10;
            }
            else
            {
                /* Converts and copies from number 0 - 9 in hexadecimal       */
                /* representation into ascii character                        */
                ClientId[2 * Index + 1] = Client_Mac_Name[1] + '0';
            }
        }
    }
}


int32_t DisplayAppBanner(char* appName, char* appVersion)
{
    int32_t            ret = 0;
    uint8_t            macAddress[SL_MAC_ADDR_LEN];
    uint16_t           macAddressLen = SL_MAC_ADDR_LEN;
    uint16_t           ConfigSize = 0;
    uint8_t            ConfigOpt = SL_DEVICE_GENERAL_VERSION;
    SlDeviceVersion_t  ver = {0};

    ConfigSize = sizeof(SlDeviceVersion_t);

    ret = sl_DeviceGet(SL_DEVICE_GENERAL, &ConfigOpt, &ConfigSize, (uint8_t*)(&ver));                           /* Print device version info. */
    ret = sl_NetCfgGet(SL_NETCFG_MAC_ADDRESS_GET, 0, &macAddressLen, &macAddress[0]);                           /* Print device Mac address */

    UART_PRINT(lineBreak);
    UART_PRINT("\t");
    printBorder('=', 44);
    UART_PRINT(lineBreak);
    UART_PRINT("\t   %s Example Ver: %s",appName, appVersion);
    UART_PRINT(lineBreak);
    UART_PRINT("\t");
    printBorder('=', 44);
    UART_PRINT(lineBreak);
    UART_PRINT(lineBreak);
    UART_PRINT("\t CHIP: 0x%x",ver.ChipId);
    UART_PRINT(lineBreak);
    UART_PRINT("\t MAC:  %d.%d.%d.%d",ver.FwVersion[0],ver.FwVersion[1],ver.FwVersion[2],ver.FwVersion[3]);
    UART_PRINT(lineBreak);
    UART_PRINT("\t PHY:  %d.%d.%d.%d",ver.PhyVersion[0],ver.PhyVersion[1],ver.PhyVersion[2],ver.PhyVersion[3]);
    UART_PRINT(lineBreak);
    UART_PRINT("\t NWP:  %d.%d.%d.%d",ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3]);
    UART_PRINT(lineBreak);
    UART_PRINT("\t ROM:  %d",ver.RomVersion);
    UART_PRINT(lineBreak);
    UART_PRINT("\t HOST: %s", SL_DRIVER_VERSION);
    UART_PRINT(lineBreak);
    UART_PRINT("\t MAC address: %02x:%02x:%02x:%02x:%02x:%02x", macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]);
    UART_PRINT(lineBreak);
    UART_PRINT(lineBreak);
    UART_PRINT("\t");
    printBorder('=', 44);
    UART_PRINT(lineBreak);
    UART_PRINT(lineBreak);

    SetClientIdNamefromMacAddress(macAddress);
    return ret;
}

void mainThread(void * args)
{
    uint32_t count = 0;
    pthread_t spawn_thread = (pthread_t) NULL;
    pthread_attr_t pAttrs_spawn;
    struct sched_param priParam;
    int32_t retc = 0;
    UART_Handle tUartHndl;

    SlNetIf_init(0);                                                                        /* Initialize SlNetSock layer with CC3x20 interface                      */
    SlNetIf_add(SLNETIF_ID_1, "CC3220", (const SlNetIf_Config_t *)&SlNetIfConfigWifi, SLNET_IF_WIFI_PRIO);

    SlNetSock_init(0);
    SlNetUtil_init(0);

    GPIO_init();
    SPI_init();
    tUartHndl = InitTerm();                                                               // Configure the UART
    UART_control(tUartHndl, UART_CMD_RXDISABLE, NULL);
    Timer_init();
    I2C_init();

     txBuffer[0] = TMP006_DIE_TEMP;
     i2cTransaction.slaveAddress = Board_TMP_ADDR;
     i2cTransaction.writeBuf = txBuffer;
     i2cTransaction.writeCount = 1;
     i2cTransaction.readBuf = rxBuffer;
     i2cTransaction.readCount = 2;

     Timer_Params_init(&timerParams);
     timerParams.period = 1000000;                                       // For 30 Min period is 1800000000;
     timerParams.periodUnits = Timer_PERIOD_US;
     timerParams.timerMode = Timer_CONTINUOUS_CALLBACK;
     timerParams.timerCallback = timerCallback;

     timer0 = Timer_open(Board_TIMER0, &timerParams);
     if (timer0 == NULL)
     {
        while (1);
     }

     if (Timer_start(timer0) == Timer_STATUS_ERROR)
     {
       while (1);
     }

    /* Create the sl_Task                                                     */
    pthread_attr_init(&pAttrs_spawn);
    priParam.sched_priority = SPAWN_TASK_PRIORITY;
    retc = pthread_attr_setschedparam(&pAttrs_spawn, &priParam);
    retc |= pthread_attr_setstacksize(&pAttrs_spawn, TASKSTACKSIZE);
    retc |= pthread_attr_setdetachstate(&pAttrs_spawn, PTHREAD_CREATE_DETACHED);

    retc = pthread_create(&spawn_thread, &pAttrs_spawn, sl_Task, NULL);

    if (retc != 0)
    {
        UART_PRINT("could not create simplelink task\n\r");
        while (1);
    }

    retc = sl_Start(0, 0, 0);
    if (retc < 0)
    {
        UART_PRINT("\n sl_Start failed\n");                                                 /* Handle Error */
        while(1);
    }

    retc = DisplayAppBanner(APPLICATION_NAME, APPLICATION_VERSION);                         /* Output device information to the UART terminal */
    retc = sl_Stop(SL_STOP_TIMEOUT );
    if (retc < 0)
    {
        UART_PRINT("\n sl_Stop failed\n");                                                  /* Handle Error */
        while(1);
    }

    if(retc < 0)
    {
        UART_PRINT("mqtt_client - Unable to retrieve device information \n");               /* Handle Error */
        while (1);
    }

    while (1)
    {
        gResetApplication = false;

        gInitState = 0;
        gApConnectionState = Mqtt_IF_Connect();
        gInitState |= MQTT_INIT_STATE;

        Mqtt_start();
        while (gInitState != 0)
        {
            UART_PRINT(".");
            sleep(1);
        }
        UART_PRINT(".\r\n");

        while (gResetApplication == false);
        UART_PRINT("TO Complete - Closing all threads and resources\r\n");
        Mqtt_Stop();

        UART_PRINT("reopen MQTT # %d  \r\n", ++count);
    }

}