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.

CC3200 UART problem

Other Parts Discussed in Thread: CC3200, CC2530

Hi All

I have been facing a problem with configuring the UART 1 peripheral of the CC3200. I am using the TCP socket example program in the CC3200 SDK. 

I am trying to configure UART 1 along with the UART 0 (which is used for the console). I am following the same procedure for configuring UART 1 as for UART 0. However, I am unable to send or receive anything from UART 1.

My code is as follows

// Enable Peripheral Clocks

MAP_PRCMPeripheralClkEnable(PRCM_UARTA1, PRCM_RUN_MODE_CLK);

// Configure PIN_01 for UART1 UART1_TX

MAP_PinTypeUART(PIN_01, PIN_MODE_7);


// Configure PIN_02 for UART1 UART1_RX

MAP_PinTypeUART(PIN_02, PIN_MODE_7);

//Enabling UART 1

MAP_UARTConfigSetExpClk(UARTA1_BASE,MAP_PRCMPeripheralClockGet(PRCM_UARTA1),
UART_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
UART_CONFIG_PAR_NONE));

//Sending a character

MAP_UARTCharPut(UARTA1_BASE, 'c');

Can anybody tell me what I'm doing wrong here?

PS: I used the CC3200 Pin Mux utility for the mux settings.

Thanks in advance

  • Hi Varun,

         See, if how uart is initialized at "\cc3200-sdk\example\uart_demo", may help you.

    - kel

  • Hi Varun,

    I've got it to work using the following code.

    pinmux.c

        // Enable Peripheral Clocks 
        MAP_PRCMPeripheralClkEnable(PRCM_UARTA1, PRCM_RUN_MODE_CLK);
    
        // Configure PIN_01 for UART1 UART1_TX
        MAP_PinTypeUART(PIN_01, PIN_MODE_7);

    main.c

    const char *mystr = "Hello, World!\r\n";
    
    /////////////////
    
    char *i = (char *)mystr, c;
    
    UARTConfigSetExpClk(UARTA1_BASE,MAP_PRCMPeripheralClockGet(PRCM_UARTA1),
    	UART_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
    	UART_CONFIG_PAR_NONE));
    
    UARTEnable(UARTA1_BASE);
    
    while ( (c = *i++) != '\0' ) {
    	UARTCharPut(UARTA1_BASE, c);
    	}
    
    	UARTDisable(UARTA1_BASE);

    Glenn.

  • Hi Varun,

        How are you observing the character on UART 1 ? Can you please provide more information about your setup.

    Thanks and Regards,

    Praveen

  • Hi Kel


    The initialization procedure in the example is the same as the one I've posted.

    Varun

  • Hi Glenn

    Thanks for your response. I tried your code and this time its getting stuck in the UARTDisable() function that gets called when UARTConfigSetExpClk() is called.

    Any idea why this is happening? Do you think that the CC3200 chip is faulty?

    I tried using the pinmux utility to configure other pins as UART1 TX and RX, but with the same results.

    Varun

  • Hi Praveen


    I'm using a software called Hyper Serial Port to observe the characters. Its working well as the console.


    Regards

    Varun

  • Varun,

     By default UART A1 is not connected to FTDI on LP boards, I assume you have some kind of emulator board ( USB to UART ) connected to PIN 1 and Pin 2.

    You can port the "uart_demo" example from the SDK to use UART A1 by making following changes.

    1. In example/common/uart_if.h

    #define CONSOLE                   UARTA0_BASE    to   UARTA1_BASE
    #define CONSOLE_PERIPH  PRCM_UARTA0   to   PRCM_UARTA1


    2. Comment out the following line

    #define CONSOLE                UARTA0_BASE

    3. Generate pinmux.c and .h for UARTA1 on pin 1 and 2.

    If you don't have any USB-UART emulator. You can do wiring on LP itself as shown below

    1. Remove the jumpers J7 and J6

    2. Pin 1.9 connected to J7

    3. Pin 1.10 connected to J6

    Note : This will disconnect the UARTA0 from FTDI

    Regards,

    Praveen

  • Hi 

    When running the UART demo with no changes, my serial port sniffer displays gibberish. I am connected to P4-10 (Tx) on the component side and P2-1 (Gnd )

    I expect 115200 baud rate

    Any ideas?

     MAP_UARTConfigSetExpClk(CONSOLE,MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH), 
                      UART_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                       UART_CONFIG_PAR_NONE));

    Regards

    Paul

  • Where is UARTA0 physically mapped to on the board? The pdf documentation indicates P1 3,4 but I see some activity on P4-10 on my monitor

    Regards

    Paul

  • Hi Praveen

    Thanks for your suggestions. I tried changing the UART from UART0 base to UART1 base on the sample applications, and it worked well. However, when I tried to open UART0 and UART1 in the same program, UARTo wouldn't work. I also tried removing the jumpers and connected the UART pins directly to a USB->UART chip, and it works when im using only one UART. 

    Anyway my requirements have changed and I only need one UART now. Also I think the chip was fundamentally faulty since it stopped working as of 2 days ago when I tried to program the flash.

    Im getting a new one soon and I'll post my results with it when I get it.  Thank you all for your suggestions

    Regards

    Varun

  • Hi Paul

    The physical mapping of the UART pins can be found out from a function called PinMuxConfig() in pinmux.c file. The function is called from main.c during startup. If you haven't changed the sample application at all, then you can use the FTDI chip in the CC3200 launchpad to view the output on a serial console. Just make sure that the jumpers J6 and J7 are connected

    Regards

    Varun

  • Hi Paul,

    For operation with an external RS-232 transceiver, remove CC3200BP jumpers J6 and J7 to disconnect CC3200LP UART0 from FTDI.  Then wire CC3200LP to RS-232 Transceiver as follows.  Picture is attached.

    3.3V to P1-1

    GND to P2-1

    TX to P7

    RX to P6

    Regards,

    Mark

  • Hi Mark,

    To make assembly of our mules easier I would like to map the serial IO to the 20 pin Headers. Reading the CC3200 document SWAS032E it looks like there are several mapping options available GPIO10, GPIO11, GPIO12, GPIO13, GPIO16,GPIO17. The schematic for the launch Pad has CC_GPIO and LP_GPIO lines.  Do I have access to the CC_GPIO IO lines from the applications processor?

    Regards

    Paul

  • The UART TX and RX are available on P2.9 (GPIO_01) and P3.3 (GPIO_02) with jumpers
    J7 1-2 and J6 1-2 installed.

    Mark

  • Hi Varun,

    Can you please ship the faulty board to us? To understand more details about the board and shipment may we contact you at the email address you provided in your E2E profile?

    Thanks & Regards,
    Raghavendra

  • Please feel free to contact me

    Regards

    Varun

  • Hi 

    I have been able to map LaunchPad booster pack pins P2.3 P2.6 to UART1.

    // Configure PIN_07 for UART1 UART1_TX
        //
        MAP_PinTypeUART(PIN_07, PIN_MODE_5);
    
        //
        // Configure PIN_08 for UART1 UART1_RX
        //
        MAP_PinTypeUART(PIN_08, PIN_MODE_5);

    I am having trouble mapping P3.5 and P3.6 to UART1. Are additional configuration steps needed for these
    analog pins? Once we populate the missing resistors should this work?


        // Configure PIN_58 for UART1 UART1_TX
        //
        MAP_PinTypeUART(PIN_58, PIN_MODE_6);
    
        //
        // Configure PIN_59 for UART1 UART1_RX
        //
        MAP_PinTypeUART(PIN_59, PIN_MODE_6);


    Paul
  • Hi Paul,

    Are you getting any output on these pins? I mean garbage.

    Pls note that PIN_58 and PIN_59 also connects to P1.2 and P1.6. Are using these header pins also ? Can you try isolating PIN_58 and PIN_59 from these header pins.?

     

    Thanks and Regards,

    Praveen

  • Thanks Praveen - that was the problem. I did not notice that P1.2 and P1.6 were also mapped to P3.5 and P3.6. I now have UART1 assigned to these pins

    -Paul

  • Hi,

    I am also trying to get Pin_58 and Pin_59 working for UART1, but I see nothing on pins P1.2 and P1.6.

    My code also hangs after writing a second time...

    UARTCharPut(UARTA1_BASE, c);  <<- hangs waiting for FIFO space

    My Pinmux.c

    MAP_PRCMPeripheralClkEnable(PRCM_UARTA1, PRCM_RUN_MODE_CLK);
     
    MAP_PinTypeUART(PIN_58, PIN_MODE_6);
     
    MAP_PinTypeUART(PIN_59, PIN_MODE_6);
    

    Main.c

      MAP_UARTConfigSetExpClk(UARTA1_BASE, MAP_PRCMPeripheralClockGet(PRCM_UARTA1),
          UART1_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
          UART_CONFIG_PAR_NONE));
    
      UARTEnable(UARTA1_BASE);


    My UART0 for Console works fine, but I need an aditional UART.

    Thanks, Tom

  • Hi Tom,

    I modified the uart_demo example to use UARTA1 on pin 58 and 59 and it works fine on my setup

    Can you share more details of your code flow and also the baud rate UART1_BAUD_RATE you are using ?

    Can you also try modifying uart_demo to use UARTA1 and post the results here.?

     

    Thanks and Regards,

    Praveen

  • Praveen, I am using the following InitTerm()

    InitTerm()
    {
    #ifndef NOTERM
      MAP_UARTConfigSetExpClk(CONSOLE, MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH),
                      UART0_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                       UART_CONFIG_PAR_NONE));
    #endif
    
      MAP_UARTConfigSetExpClk(UARTA1_BASE, MAP_PRCMPeripheralClockGet(PRCM_UARTA1),
    		  	  	  UART1_BAUD_RATE, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
    		  	  		UART_CONFIG_PAR_NONE));
    
      UARTEnable(UARTA1_BASE);
    
      __Errorlog = 0;
    }
    

    in my uart_if.h

    #define UART0_BAUD_RATE 115200
    #define UART1_BAUD_RATE 9600
    #define SYSCLK          80000000
    #define CONSOLE         UARTA0_BASE
    #define CONSOLE_PERIPH  PRCM_UARTA0
    

    Then I try to send out a char in main, after InitTerm()

        DBG_PRINT("sending out UART1. 1\n\r");
    
        MAP_UARTCharPut(UARTA1_BASE, 0x80);
        DBG_PRINT("sending out UART1. 2\n\r");
    
        MAP_UARTCharPut(UARTA1_BASE, 0x80);
        DBG_PRINT("Done sending out UART1.\n\r");
    
    


    No data makes it out on pin 58, and the code hangs on the last UARTCharPut statement waiting for the previous char to clear...
  • Hi Tom,

    I just copied your code on to my setup for InitTerm() and uart_if.h macros. Then I am doing

        //
        // Initailizing the board
        //
        BoardInit();

        //
        // Muxing for Enabling UART_TX and UART_RX.
        //
        PinMuxConfig();

        //
        // Initialising the Terminal.
        //
        InitTerm();

        Message("sending out UART1. 1\n\r");

        MAP_UARTCharPut(UARTA1_BASE, 'c');
        Message("sending out UART1. 2\n\r");

        MAP_UARTCharPut(UARTA1_BASE, 'c');
        Message("Done sending out UART1.\n\r");

    And it work for me. I can see the prints on both the terminals

    And here is how my pinmux look like

    PinMuxConfig(void)
    {
        //
        // Enable Peripheral Clocks
        //
        MAP_PRCMPeripheralClkEnable(PRCM_UARTA0, PRCM_RUN_MODE_CLK);
        MAP_PRCMPeripheralClkEnable(PRCM_UARTA1, PRCM_RUN_MODE_CLK);

        //
        // Configure PIN_55 for UART0 UART0_TX
        //
        MAP_PinTypeUART(PIN_55, PIN_MODE_3);

        //
        // Configure PIN_57 for UART0 UART0_RX
        //
        MAP_PinTypeUART(PIN_57, PIN_MODE_3);

        //
        // Configure PIN_58 for UART1 UART1_TX
        //
        MAP_PinTypeUART(PIN_58, PIN_MODE_6);

        //
        // Configure PIN_59 for UART1 UART1_RX
        //
        MAP_PinTypeUART(PIN_59, PIN_MODE_6);
    }

     

    Can you post here screenshots of memory window range: 0x4000_d000 to 0x4000_d048

    One just after the InitTerm(); and another after it hangs inside   MAP_UARTCharPut().

    Thanks and Regards,

    Praveen

  • Varun Warrier said:

    Thanks for your response. I tried your code and this time its getting stuck in the UARTDisable() function that gets called when UARTConfigSetExpClk() is called.

    Any idea why this is happening? Do you think that the CC3200 chip is faulty?

    I observed exactly the same problem on my CC3200. I tried to workaround it and after adding:

            UARTEnable(UARTA1_BASE); 
            HWREG(UARTA1_BASE + UART_O_FR) = 0;
    

    before call to UARTConfigSetExpClk() and it started working. What's funny is that I am unable to reproduce that problem anymore (atleast not easily).

  • Do we need a level shifter between UART pins of cc3200 and the UART port coming from PC?

    Because it didn't work for me either.

  • Shashi Ranjan1 said:
    Do we need a level shifter between UART pins of cc3200 and the UART port coming from PC?

    Yes, you need a RS232 Transceiver.

    Is you UART Port through USB to RS232 Converter?

    - kel

  • Dear Praveen, 

    I'm Chan. I've started working on CC3200 launchpad a week ago. Your replies on "UART problem" helped me to quickly configure UART0 to external RS-232 transceiver as follows.

    a. Removed the jumpers on J6 and J7.

    b. Connected middle pin of J6 to Rx and middle pin of J7 to Tx.

    c. Power pins of external RS-232 transceiver are connected on P3-1 (+5V) and P3-2 (GND) of CC3200LP.

    Now, I want to use another UART also simultaneously in my application. Please help me by providing the following information.

    1. Is the above configuration is correct ?

    2. I want to retain the USB connection to Computer for debugging. Hence, J6 and J7 are to be connected. If they are connected, what are the alternative PINs for Rx and Tx of UART0. The idea is to run application in MCU without removing USB cable from PC (However, SOP2 shall be removed and Reset button shall be pressed).

    3. In short, please let me know the Pins for UART0 and UART1 when J6 and J7 are connected. Also let men know another set of +5V and GND connections for 2nd RS-232 Transceiver.

    4. Kindly provide the modifications in "uart_demo" example to use UART0 and UART1 simultaneously to connect two separate RS-232 devices.

    Thanks & Best Regards

    Chan

  • Hi,

    I've connected UART0 through USB while J6 and J7 are connected. UART1 is connected on P1-2 and P1-6.

    In the uart_demo example of cc3200 sdk, I've duplicated UartGetChar(), UartPutChar(c), InitTerm(), ClearTerm(), Message() and Report() functions for UART1 just by changing CONSOLE to CONSOLE1.

    Now, I could send and receive characters on both UARTs SEQUENTIALLY where I need it be SIMULTANEOUSLY.

    Using uart_demo example, if we write the code as follows, 

    cCharacter = UartGetChar();        // receive character from UART0
    UartPutChar(cCharacter);            // send character to UART0
    cCharacter1 = Uart1GetChar();  // receive character from UART1
    Uart1PutChar(cCharacter1);      // receive character from UART1

    The Problem is unless a character is received on UART0, the code will not move to cCharacter1 = Uart1GetChar(). Hence, user can't input a character on UART1 until and unless UART0 received a character.

    When the statement, cCharacter = UartGetChar(); is executed, it enters into the following code at uart.c

    long
    UARTCharGet(unsigned long ulBase)
    {
    //
    // Check the arguments.
    //
    ASSERT(UARTBaseValid(ulBase));

    //
    // Wait until a char is available.
    //
    while(HWREG(ulBase + UART_O_FR) & UART_FR_RXFE)
              {
               }
    //
    // Now get the char.
    //
    return(HWREG(ulBase + UART_O_DR));
    }

    The program comes to the statement, while(HWREG(ulBase + UART_O_FR) & UART_FR_RXFE) of uart.c and will not move from there unless until a character is received.

    Surprisingly even if the entire code for UARTCharGet function is deleted!

    Questions: 

    1. Where is the definition of the function, MAP_UARTCharGet located ?

    2. How and why the program is being halted at Line981, Col5 of uart.c file even if the above code is deleted ?

    3. 
    Is it mandatory for the program to wait for a character at an UART ? In that case how to make the other UART to function without being in a queue?


    My Objective: is to

    a) to make the functionality of UARTs independent of each other i.e. even if UART0 is not connected to terminal or not  getting any input, UART1 should function normally without waiting till a character is received on UART0.

    b)Application-1: to send a string (of format 0B 03 45 17 00 0A 03 E8) to an RS-232 port of a device. The device replies in the same format which is to be received by UART. This sending and receiving process is continuous or periodic at specified intervals or at specific time based on RTC.

    In short, UART should receive the string only after sending a string. It shouldn't receive any other data, even if the device sends voluntarily.

    Here, sending string length is fixed but receiving string length is not fixed but of same format.

    c) Application-2:to receive strings (of format 0B 03 45 17 00 0A 03 E8) continuously which are sent continuously by a device at it's RS-232 port and send reply in same format.

    Here, receiving string length is fixed but sending string length is not fixed but of same format.

    d) Application-3:to send strings (of format 0B 03 45 17 00 0A 03 E8) continuously to a device at it's RS-232 port but don't receive anything from the device.

    Here, sending string length is fixed.

    Kindly help me out.

  • Hi,

        I suggest you use a RS232 transceiver to achieve simultaneous communication from 2 UART ports.

    - kel

  • Markel Robregado said:

    Hi,

        I suggest you use a RS232 transceiver to achieve simultaneous communication from 2 UART ports.

    - kel

    Dear Markel, 

    Thanks for quick reply. I'm using RS-232 transceiver.

    The only problem is with UARTCharGet or MAP_UARTCharPut function. As described in my previous post, If I can run the following set of statements together, i.e. Set-A and Set-B simultaneously, my problem will be solved. Otherwise, unless until a character is received by cCharacter = UartGetChar() at UART0, program will not move to next statement.

    Set-A:

    cCharacter = UartGetChar();        // receive character from UART0
    UartPutChar(cCharacter);            // send character to UART0

    Set-B:

    cCharacter1 = Uart1GetChar();  // receive character from UART1
    Uart1PutChar(cCharacter1);      // receive character from UART1

     

    As of now, I've written the above statements together in While (1) loop in main(). Is there any way to write code to execute two sets of statements simultaneously ?

  • Hi Chan,

    Did you tried UARTCharGetNonBlocking() and UARTCharPutNonBlocking()? You can use the return values to see if these functions were successful and act accordingly.

    You can also use UART interrupts.

    Thanks and Regards,

    Praveen

  • Hello Praveen,

       I flashed the uart_demo code on the launchpad and connected to tera term for console with the recommended settings, I am not seeing any dump on the console port. And I have connected the J6 and J7 in flash mode not the bp mode. Can you tell me what mistake I am doing?

    Thanks in advance 

  • Hi Xavier,

    What is the part no. printed on the device?

    Thanks and Regards,

    Praveen

  • Hi Praveen,

      CC3200MODR1M2AM0B

      CC3200MODLAUNCHXL Rev 1.0

  • Hi Xavier,

    Hope you have removed SOP2 jumper after flashing.

    In that case, can you try using debugger to run the same application?

    Thanks and Regards,

    Praveen

  • Hi Praveen,

    Yes I removed the SOP2 jumper.

    As you are suggesting, that's the next thing I did. I am not able to debug from CCS either.

    The hardware user guide says the debug LED D2 should glow when it is in debug mode.

    And for that the jumper should be on J8,J9,J10 and J11 but that LED doesn't glow.

    And yetI tried debugging through CCS, but it said Error in the FTDI cable.

  • Hi Praveen,  

        It was a jumper issue.

        Replacing one of them fixed it. I don't know why though.

       Thanks for all your support.

  • Hello,

    I have a question regarding UART on CC2530 so I think posting here: Is it possible to get UART working on 1.8 V? If yes, how?

    Thanks,

    Mircea

  • You can use voltage level shifter. between UART of CC3200 and your PC.

  • Shashi Ranjan1 said:
    between UART of CC3200 and your PC.

    Mircea is asking about "UART on CC2530".

    @Mircea,

        You posted in the wrong forum as you can see above this is the SimpleLink WiFi CC31xx/CC32xx Forum.

         But, you need to be specific of your question. Which do you mean will run at 1.8V? Is it the CC2530 or is it the UART lines?

    - kel

  • Hello Kel,

    CC2530 has VCC = 3V but I was wondering if I can "setup" the UART to work at 1.8 V because I have another device what uses 1.8 V UART. I was wondering if this is possible considering the power from CC2530 is internally regulated to 1.8 V:

    (The digital core and peripherals are powered by a 1.8-V low-dropout voltage regulator (Chapter 25).) from CC253x Userguide.

    Thanks,

    Mircea

  • Hello,

    It is probable, that in Your case UartPutChar resolves to a macro, MAP_UARTCharPut(CONSOLE,c)

    The function eventually called by MAP_UARTCharPut , is a blocking function, it means it does not release control to program unless the byte is actually sent.

    You might want to use the FIFO buffer, and just leave the byte to be sent in the buffer and release control to program instantly, this is achieved by using the non-blocking versions of these function, that is MAP_UARTCharPutNonBlocking, like MAP_UARTCharPutNonBlocking (CONSOLE, cCharacter);

    Good luck!

  • Hi Praveen and Varun

    I am a New one for this Controller.I am Facing the same problem.I need to connect the UART0 and UART1 in One board.

    In LP board where the UART0 and UART1 Rx ,Tx Pins.Can Pls Share about it.

    Thanks & Regards

    Dinesh

  • Hi to All,

    I am Trying to connect the  cc3200  Uart 0 to my system terminal software and to get output but i can't able to get ouput .

    I am Connecting the RX and Tx Pin in PORT 1  3 and 4 Respectively.And Change the Jumper on J6 & J7 to Normal UART mode.

    I attach my coding in this message 

    Thanks 

    //*****************************************************************************
    // Copyright (C) 2014 Texas Instruments Incorporated
    //
    // All rights reserved. Property of Texas Instruments Incorporated.
    // Restricted rights to use, duplicate or disclose this code are
    // granted through contract.
    // The program may not be used without the written permission of
    // Texas Instruments Incorporated or against the terms and conditions
    // stipulated in the agreement under which this program has been supplied,
    // and under no circumstances can it be used with non-TI connectivity device.
    //
    //*****************************************************************************

    //*****************************************************************************
    //
    // Application Name - MQTT Client
    // Application Overview - This application acts as a MQTT client and connects
    // to the IBM MQTT broker, simultaneously we can
    // connect a web client from a web browser. Both
    // clients can inter-communicate using appropriate
    // topic names.
    //
    // Application Details -
    // processors.wiki.ti.com/.../CC32xx_MQTT_Client
    // or
    // docs\examples\CC32xx_MQTT_Client.pdf
    //
    //*****************************************************************************

    //*****************************************************************************
    //
    //! \addtogroup mqtt_client
    //! @{
    //
    //*****************************************************************************

    // Standard includes
    #include <stdlib.h>

    // simplelink includes
    #include "simplelink.h"

    // driverlib includes
    #include "hw_types.h"
    #include "hw_ints.h"
    #include "hw_memmap.h"
    #include "hw_common_reg.h"
    #include "interrupt.h"
    #include "rom.h"
    #include "rom_map.h"
    #include "prcm.h"
    #include "uart.h"
    #include "timer.h"

    // common interface includes
    #include "network_if.h"
    #ifndef NOTERM
    #include "uart_if.h"
    #endif

    #include "button_if.h"
    #include "gpio_if.h"
    #include "timer_if.h"
    #include "common.h"
    #include "utils.h"


    #include "sl_mqtt_client.h"

    // application specific includes
    #include "pinmux.h"

    #define APPLICATION_VERSION "1.1.1"

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

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

    /*Defining Broker IP address and port Number*/
    #define SERVER_ADDRESS "m12.cloudmqtt.com" // "messagesight.demos.ibm.com"
    #define PORT_NUMBER 16696

    #define MAX_BROKER_CONN 1

    #define SERVER_MODE MQTT_3_1
    /*Specifying Receive time out for the Receive task*/
    #define RCV_TIMEOUT 30

    /*Background receive task priority*/
    #define TASK_PRIORITY 3

    /* Keep Alive Timer value*/
    #define KEEP_ALIVE_TIMER 25

    /*Clean session flag*/
    #define CLEAN_SESSION true

    /*Retain Flag. Used in publish message. */
    #define RETAIN 1

    /*Defining Publish Topic*/
    #define PUB_TOPIC_FOR_SW3 "/Dinesh/BSw3"
    #define PUB_TOPIC_FOR_SW2 "/Dinesh/BSw2"

    /*Defining Number of topics*/
    #define TOPIC_COUNT 3 // 3

    /*Defining Subscription Topic Values*/
    #define TOPIC1 "/Dinesh/LED1" // "/Dinesh/LED1"
    #define TOPIC2 "/Dinesh/LED2" // "/Dinesh/LED2"
    #define TOPIC3 "/Dinesh/LED3" // "/Dinesh/LED3"
    /*#define TOPIC4 "/Dinesh/LED2OFF" // "/Dinesh/LED1"
    #define TOPIC5 "/Dinesh/LED3ON" // "/Dinesh/LED2"
    #define TOPIC6 "/Dinesh/LED3OFF" // "/Dinesh/LED3"*/

    /*To Control The LED On/Off */
    #define Control1 "/On"
    #define Control2 "/Off"

    /*Defining QOS levels*/
    #define QOS0 0
    #define QOS1 1
    #define QOS2 2

    /*Spawn task priority and OSI Stack Size*/
    #define OSI_STACK_SIZE 2048
    #define UART_PRINT Report


    /* for the Usart Transmit */
    #define CONSOLE UARTA0_BASE
    #define UartGetChar() MAP_UARTCharGet(CONSOLE)
    #define UartPutChar(c) MAP_UARTCharPut(CONSOLE,c)
    #define MAX_STRING_LENGTH 80

    typedef struct connection_config{
    SlMqttClientCtxCfg_t broker_config;
    void *clt_ctx;
    unsigned char *client_id;
    unsigned char *usr_name;
    unsigned char *usr_pwd;
    bool is_clean;
    unsigned int keep_alive_time;
    SlMqttClientCbs_t CallBAcks;
    int num_topics;
    char *topic[TOPIC_COUNT];
    unsigned char qos[TOPIC_COUNT];
    SlMqttWill_t will_params;
    bool is_connected;
    }connect_config;

    typedef enum
    {
    PUSH_BUTTON_SW2_PRESSED,
    PUSH_BUTTON_SW3_PRESSED,
    BROKER_DISCONNECTION
    }events;

    typedef struct
    {
    void * hndl;
    events event;
    }event_msg;

    //*****************************************************************************
    // LOCAL FUNCTION PROTOTYPES
    //*****************************************************************************
    static void
    Mqtt_Recv(void *app_hndl, const char *topstr, long top_len, const void *payload,
    long pay_len, bool dup,unsigned char qos, bool retain);
    static void sl_MqttEvt(void *app_hndl,long evt, const void *buf,
    unsigned long len);
    static void sl_MqttDisconnect(void *app_hndl);
    void pushButtonInterruptHandler2();
    void pushButtonInterruptHandler3();
    void ToggleLedState(ledEnum LedNum);
    void TimerPeriodicIntHandler(void);
    void LedTimerConfigNStart();
    void LedTimerDeinitStop();
    void BoardInit(void);
    static void DisplayBanner(char * AppName);
    void MqttClient(void *pvParameters);
    //*****************************************************************************
    // GLOBAL VARIABLES -- Start
    //*****************************************************************************
    #ifdef USE_FREERTOS
    #if defined(ewarm)
    extern uVectorEntry __vector_table;
    #endif
    #if defined(ccs)
    extern void (* const g_pfnVectors[])(void);
    #endif
    #endif

    volatile int g_iCounter = 0;

    //#if defined(ccs)
    //extern void (* const g_pfnVectors[])(void);
    //#endif
    //#if defined(ewarm)
    //extern uVectorEntry __vector_table;
    //#endif

    unsigned short g_usTimerInts;
    /* AP Security Parameters */
    SlSecParams_t SecurityParams = {0};

    /*Message Queue*/
    OsiMsgQ_t g_PBQueue;

    /* connection configuration */
    connect_config usr_connect_config[] =
    {
    {
    {
    {
    SL_MQTT_NETCONN_URL,
    SERVER_ADDRESS,
    PORT_NUMBER,
    0,
    0,
    0,
    NULL
    },
    SERVER_MODE,
    true,
    },
    NULL, // broker configuration
    "user1", // Client CTX
    "kmbnvuaz",//NULL, // User name for client web
    "nE8TLc8r8Cc7",//NULL, // Password for client web
    true, // Boolean Experssion true or flase
    KEEP_ALIVE_TIMER, // Keep alive time set here
    {Mqtt_Recv, sl_MqttEvt, sl_MqttDisconnect},
    TOPIC_COUNT,
    {TOPIC1, TOPIC2, TOPIC3},
    {QOS2, QOS2, QOS2},
    {WILL_TOPIC,WILL_MSG,WILL_QOS,WILL_RETAIN},
    false
    }
    };

    /* library configuration */
    SlMqttClientLibCfg_t Mqtt_Client={
    1882,
    TASK_PRIORITY,
    30,
    true,
    (long(*)(const char *, ...))UART_PRINT
    };

    /*Publishing topics and messages*/

    /*When Switch is pressed the data is Sent to the web sever*/
    const char *pub_topic_sw2 = PUB_TOPIC_FOR_SW2;
    const char *pub_topic_sw3 = PUB_TOPIC_FOR_SW3;
    unsigned char *data_sw2={"Wegot Utility solution"};/*{"Push button sw2 is pressed on CC32XX device"};*/
    unsigned char *data_sw3={"VenAqua "};/*{"Push button sw3 is pressed on CC32XX device"};*/

    void *app_hndl = (void*)usr_connect_config;
    //*****************************************************************************
    // GLOBAL VARIABLES -- End
    //*****************************************************************************

    //****************************************************************************
    //! Defines Mqtt_Pub_Message_Receive event handler.
    //! Client App needs to register this event handler with sl_ExtLib_mqtt_Init
    //! API. Background receive task invokes this handler whenever MQTT Client
    //! receives a Publish Message from the broker.
    //!
    //!\param[out] topstr => pointer to topic of the message
    //!\param[out] top_len => topic length
    //!\param[out] payload => pointer to payload
    //!\param[out] pay_len => payload length
    //!\param[out] retain => Tells whether its a Retained message or not
    //!\param[out] dup => Tells whether its a duplicate message or not
    //!\param[out] qos => Tells the Qos level
    //!
    //!\return none
    //****************************************************************************
    static void
    Mqtt_Recv(void *app_hndl, const char *topstr, long top_len, const void *payload,
    long pay_len, bool dup,unsigned char qos, bool retain)
    {

    char *output_str=(char*)malloc(top_len+1);
    memset(output_str,'\0',top_len+1);
    strncpy(output_str, (char*)topstr, top_len);
    output_str[top_len]='\0';


    // output_str=(char*)malloc(pay_len+1);
    // memset(output_str,'\0',pay_len+1);
    // strncpy(output_str, (char*)payload, pay_len); //getting msg here
    // output_str[pay_len]='\0';


    /* if(strncmp(output_str,TOPIC1, top_len) == 0)
    {
    ToggleLedState(LED1);
    }
    else if(strncmp(output_str,TOPIC2, top_len) == 0)
    {
    ToggleLedState(LED2);
    }
    else if(strncmp(output_str,TOPIC3, top_len) == 0)
    {
    ToggleLedState(LED3);
    }*/

    if(strncmp(output_str,TOPIC1, top_len) == 0)
    {
    char *output_str=(char*)malloc(pay_len+1);
    memset(output_str,'\0',pay_len+1);
    strncpy(output_str, (char*)payload, pay_len);
    output_str[pay_len]='\0';

    if(strncmp(output_str,Control1, pay_len) == 0)
    {
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    }
    else if(strncmp(output_str,Control2, pay_len) == 0)
    {
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    }
    }
    else if(strncmp(output_str,TOPIC2, top_len) == 0)
    {
    char *output_str=(char*)malloc(pay_len+1);
    memset(output_str,'\0',pay_len+1);
    strncpy(output_str, (char*)payload, pay_len);
    output_str[pay_len]='\0';

    if(strncmp(output_str,Control1, pay_len) == 0)
    {
    GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);
    }

    else if(strncmp(output_str,Control2, pay_len) == 0)
    {
    GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
    }
    }
    else if(strncmp(output_str,TOPIC3, top_len) == 0)
    {
    char *output_str=(char*)malloc(pay_len+1);
    memset(output_str,'\0',pay_len+1);
    strncpy(output_str, (char*)payload, pay_len);
    output_str[pay_len]='\0';

    if(strncmp(output_str,Control1, pay_len) == 0)
    {
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    }
    else if(strncmp(output_str,Control2, pay_len) == 0)
    {
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
    }
    }

    UART_PRINT("\n\rPublish Message Received");
    UART_PRINT("\n\rTopic: ");
    UART_PRINT("%s",output_str);
    free(output_str);
    UART_PRINT(" [Qos: %d] ",qos);
    if(retain)
    UART_PRINT(" [Retained]");
    if(dup)
    UART_PRINT(" [Duplicate]");

    output_str=(char*)malloc(pay_len+1);
    memset(output_str,'\0',pay_len+1);
    strncpy(output_str, (char*)payload, pay_len); //getting msg here
    output_str[pay_len]='\0';
    UART_PRINT("\n\rData is: ");
    UART_PRINT("%s",(char*)output_str);
    UART_PRINT("\n\r");
    free(output_str);

    return;
    }

    //****************************************************************************
    //! Defines sl_MqttEvt event handler.
    //! Client App needs to register this event handler with sl_ExtLib_mqtt_Init
    //! API. Background receive task invokes this handler whenever MQTT Client
    //! receives an ack(whenever user is in non-blocking mode) or encounters an error.
    //!
    //! param[out] evt => Event that invokes the handler. Event can be of the
    //! following types:
    //! MQTT_ACK - Ack Received
    //! MQTT_ERROR - unknown error
    //!
    //!
    //! \param[out] buf => points to buffer
    //! \param[out] len => buffer length
    //!
    //! \return none
    //****************************************************************************
    static void
    sl_MqttEvt(void *app_hndl, long evt, const void *buf,unsigned long len)
    {
    int i;
    switch(evt)
    {
    case SL_MQTT_CL_EVT_PUBACK:
    UART_PRINT("PubAck:\n\r");
    UART_PRINT("%s\n\r",buf);
    break;

    case SL_MQTT_CL_EVT_SUBACK:
    UART_PRINT("\n\rGranted QoS Levels are:\n\r");

    for(i=0;i<len;i++)
    {
    UART_PRINT("QoS %d\n\r",((unsigned char*)buf)[i]);
    }
    break;

    case SL_MQTT_CL_EVT_UNSUBACK:
    UART_PRINT("UnSub Ack \n\r");
    UART_PRINT("%s\n\r",buf);
    break;

    default:
    break;

    }
    }

    //****************************************************************************
    //
    //! callback event in case of MQTT disconnection
    //!
    //! \param app_hndl is the handle for the disconnected connection
    //!
    //! return none
    //
    //****************************************************************************
    static void
    sl_MqttDisconnect(void *app_hndl)
    {
    connect_config *local_con_conf;
    event_msg msg;
    local_con_conf = app_hndl;
    msg.hndl = app_hndl;
    msg.event = BROKER_DISCONNECTION;

    UART_PRINT("disconnect from broker %s\r\n",
    (local_con_conf->broker_config).server_info.server_addr);
    local_con_conf->is_connected = false;
    //
    // write message indicating publish message
    //
    osi_MsgQWrite(&g_PBQueue,&msg,OSI_NO_WAIT);

    }

    //****************************************************************************
    //
    //! Push Button Handler1(GPIOS2). Press push button2 (GPIOSW2) Whenever user
    //! wants to publish a message. Write message into message queue signaling the
    //! event publish messages
    //!
    //! \param none
    //!
    //! return none
    //
    //****************************************************************************
    void pushButtonInterruptHandler2()
    {
    event_msg msg;

    msg.event = PUSH_BUTTON_SW2_PRESSED;
    msg.hndl = NULL;
    //
    // write message indicating publish message
    //
    osi_MsgQWrite(&g_PBQueue,&msg,OSI_NO_WAIT);
    }

    //****************************************************************************
    //
    //! Push Button Handler3(GPIOS3). Press push button3 (GPIOSW3) Whenever user
    //! wants to publish a message. Write message into message queue signaling the
    //! event publish messages
    //!
    //! \param none
    //!
    //! return none
    //
    //****************************************************************************
    void pushButtonInterruptHandler3()
    {
    event_msg msg;
    msg.event = PUSH_BUTTON_SW3_PRESSED;
    msg.hndl = NULL;
    //
    // write message indicating exit from sending loop
    //
    osi_MsgQWrite(&g_PBQueue,&msg,OSI_NO_WAIT);

    }

    //****************************************************************************
    //
    //! Toggles the state of GPIOs(LEDs)
    //!
    //! \param LedNum is the enumeration for the GPIO to be toggled
    //!
    //! \return none
    //
    //****************************************************************************
    void ToggleLedState(ledEnum LedNum)
    {
    unsigned char ledstate = 0;
    switch(LedNum)
    {
    case LED1:
    ledstate = GPIO_IF_LedStatus(MCU_RED_LED_GPIO);
    if(!ledstate)
    {
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    }
    else
    {
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    }
    break;
    case LED2:
    ledstate = GPIO_IF_LedStatus(MCU_ORANGE_LED_GPIO);
    if(!ledstate)
    {
    GPIO_IF_LedOn(MCU_ORANGE_LED_GPIO);
    }
    else
    {
    GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
    }
    break;
    case LED3:
    ledstate = GPIO_IF_LedStatus(MCU_GREEN_LED_GPIO);
    if(!ledstate)
    {
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    }
    else
    {
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
    }
    break;
    default:
    break;
    }
    }

    //*****************************************************************************
    //
    //! Periodic Timer Interrupt Handler
    //!
    //! \param None
    //!
    //! \return None
    //
    //*****************************************************************************
    void
    TimerPeriodicIntHandler(void)
    {
    unsigned long ulInts;

    //
    // Clear all pending interrupts from the timer we are
    // currently using.
    //
    ulInts = MAP_TimerIntStatus(TIMERA0_BASE, true);
    MAP_TimerIntClear(TIMERA0_BASE, ulInts);

    //
    // Increment our interrupt counter.
    //
    g_usTimerInts++;
    if(!(g_usTimerInts & 0x1))
    {
    //
    // Off Led
    //
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    }
    else
    {
    //
    // On Led
    //
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    }
    }

    //****************************************************************************
    //
    //! Function to configure and start timer to blink the LED while device is
    //! trying to connect to an AP
    //!
    //! \param none
    //!
    //! return none
    //
    //****************************************************************************
    void LedTimerConfigNStart()
    {
    //
    // Configure Timer for blinking the LED for IP acquisition
    //
    Timer_IF_Init(PRCM_TIMERA0,TIMERA0_BASE,TIMER_CFG_PERIODIC,TIMER_A,0);
    Timer_IF_IntSetup(TIMERA0_BASE,TIMER_A,TimerPeriodicIntHandler);
    Timer_IF_Start(TIMERA0_BASE,TIMER_A,100);
    }

    //****************************************************************************
    //
    //! Disable the LED blinking Timer as Device is connected to AP
    //!
    //! \param none
    //!
    //! return none
    //
    //****************************************************************************
    void LedTimerDeinitStop()
    {
    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    Timer_IF_Stop(TIMERA0_BASE,TIMER_A);
    Timer_IF_DeInit(TIMERA0_BASE,TIMER_A);

    }

    //*****************************************************************************
    //
    //! Board Initialization & Configuration
    //!
    //! \param None
    //!
    //! \return None
    //
    //*****************************************************************************
    void BoardInit(void)
    {
    /* In case of TI-RTOS vector table is initialize by OS itself */
    #ifndef USE_TIRTOS
    //
    // Set vector table base
    //
    #if defined(ccs)
    IntVTableBaseSet((unsigned long)&g_pfnVectors[0]);
    #endif
    #if defined(ewarm)
    IntVTableBaseSet((unsigned long)&__vector_table);
    #endif
    #endif
    //
    // Enable Processor
    //
    MAP_IntMasterEnable();
    MAP_IntEnable(FAULT_SYSTICK);

    PRCMCC3200MCUInit();
    }

    //*****************************************************************************
    //
    //! Application startup display on UART
    //!
    //! \param none
    //!
    //! \return none
    //!
    //*****************************************************************************
    static void
    DisplayBanner(char * AppName)
    {

    UART_PRINT("\n\n\n\r");
    UART_PRINT("\t\t *************************************************\n\r");
    UART_PRINT("\t\t CC3200 %s Application \n\r", AppName);
    UART_PRINT("\t\t *************************************************\n\r");
    UART_PRINT("\n\n\n\r");
    }

    extern volatile unsigned long g_ulStatus;
    //*****************************************************************************
    //
    //! Task implementing MQTT client communication to other web client through
    //! a broker
    //!
    //! \param none
    //!
    //! This function
    //! 1. Initializes network driver and connects to the default AP
    //! 2. Initializes the mqtt library and set up MQTT connection configurations
    //! 3. set up the button events and their callbacks(for publishing)
    //! 4. handles the callback signals
    //!
    //! \return None
    //!
    //*****************************************************************************
    void MqttClient(void *pvParameters)
    {

    long lRetVal = -1;
    int iCount = 0;
    int iNumBroker = 0;
    int iConnBroker = 0;
    event_msg RecvQue;
    unsigned char policyVal;

    char cString[MAX_STRING_LENGTH+1];
    char cCharacter;
    int iStringLength = 0;

    connect_config *local_con_conf = (connect_config *)app_hndl;

    //
    // Configure LED
    //
    GPIO_IF_LedConfigure(LED1|LED2|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    //
    // 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);
    LOOP_FOREVER();
    }

    // switch on Green LED to indicate Simplelink is properly up
    GPIO_IF_LedOn(MCU_ON_IND);

    // 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_NAME, SecurityParams);
    if(lRetVal < 0)
    {
    UART_PRINT("Connection to an AP failed\n\r");
    LOOP_FOREVER();
    }

    lRetVal = sl_WlanProfileAdd(SSID_NAME,strlen(SSID_NAME),0,&SecurityParams,0,1,0);

    //set AUTO policy
    lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION,
    SL_CONNECTION_POLICY(1,0,0,0,0),
    &policyVal, 1 /*PolicyValLen*/);

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

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    UtilsDelay(20000000);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    //
    // Register Push Button Handlers
    //
    Button_IF_Init(pushButtonInterruptHandler2,pushButtonInterruptHandler3);

    //
    // Initialze MQTT client lib
    //
    lRetVal = sl_ExtLib_MqttClientInit(&Mqtt_Client);
    if(lRetVal != 0)
    {
    // lib initialization failed
    UART_PRINT("MQTT Client lib initialization failed\n\r");
    LOOP_FOREVER();
    }

    /******************* connection to the broker ***************************/
    iNumBroker = sizeof(usr_connect_config)/sizeof(connect_config);
    if(iNumBroker > MAX_BROKER_CONN)
    {
    UART_PRINT("Num of brokers are more then max num of brokers\n\r");
    LOOP_FOREVER();
    }

    connect_to_broker:
    while(iCount < iNumBroker)
    {
    //create client context
    local_con_conf[iCount].clt_ctx =
    sl_ExtLib_MqttClientCtxCreate(&local_con_conf[iCount].broker_config,
    &local_con_conf[iCount].CallBAcks,
    &(local_con_conf[iCount]));

    //
    // Set Client ID
    //
    sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
    SL_MQTT_PARAM_CLIENT_ID,
    local_con_conf[iCount].client_id,
    strlen((char*)(local_con_conf[iCount].client_id)));

    //
    // Set will Params
    //
    if(local_con_conf[iCount].will_params.will_topic != NULL)
    {
    sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
    SL_MQTT_PARAM_WILL_PARAM,
    &(local_con_conf[iCount].will_params),
    sizeof(SlMqttWill_t));
    }

    //
    // setting username and password
    //
    if(local_con_conf[iCount].usr_name != NULL)
    {
    sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
    SL_MQTT_PARAM_USER_NAME,
    local_con_conf[iCount].usr_name,
    strlen((char*)local_con_conf[iCount].usr_name));

    if(local_con_conf[iCount].usr_pwd != NULL)
    {
    sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
    SL_MQTT_PARAM_PASS_WORD,
    local_con_conf[iCount].usr_pwd,
    strlen((char*)local_con_conf[iCount].usr_pwd));
    }
    }

    //
    // connectin to the broker
    //
    if((sl_ExtLib_MqttClientConnect((void*)local_con_conf[iCount].clt_ctx,
    local_con_conf[iCount].is_clean,
    local_con_conf[iCount].keep_alive_time) & 0xFF) != 0)
    {
    UART_PRINT("\n\rBroker connect fail for conn no. %d \n\r",iCount+1);

    //delete the context for this connection
    sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx);

    break;
    }
    else
    {
    UART_PRINT("\n\rSuccess: conn to Broker no. %d\n\r ", iCount+1);
    local_con_conf[iCount].is_connected = true;
    iConnBroker++;
    }

    //
    // Subscribe to topics
    //

    if(sl_ExtLib_MqttClientSub((void*)local_con_conf[iCount].clt_ctx,
    local_con_conf[iCount].topic,
    local_con_conf[iCount].qos, TOPIC_COUNT) < 0)
    {
    UART_PRINT("\n\r Subscription Error for conn no. %d\n\r", iCount+1);
    UART_PRINT("Disconnecting from the broker\r\n");
    sl_ExtLib_MqttClientDisconnect(local_con_conf[iCount].clt_ctx);
    local_con_conf[iCount].is_connected = false;

    //delete the context for this connection
    sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx);
    iConnBroker--;
    break;
    }
    else
    {
    int iSub;
    UART_PRINT("Client subscribed on following topics:\n\r");
    for(iSub = 0; iSub < local_con_conf[iCount].num_topics; iSub++)
    {
    UART_PRINT("%s\n\r", local_con_conf[iCount].topic[iSub]);
    }
    }
    iCount++;
    }

    if(iConnBroker < 1)
    {
    //
    // no succesful connection to broker
    //
    goto end;
    }

    iCount = 0;

    Message("\t\t****************************************************\n\r");
    Message("\t\t\t CC3200 UART Echo Usage \n\r");
    Message("\t\t Type in a string of alphanumeric characters and \n\r");
    Message("\t\t pressenter, the string will be echoed. \n\r") ;
    Message("\t\t Note: if string length reaches 80 character it will \n\r");
    Message("\t\t echo the string without waiting for enter command \n\r");
    Message("\t\t ****************************************************\n\r");
    Message("\n\n\n\r");
    Message("cmd#");


    for(;;)
    {

    //
    // Fetching the input from the terminal.
    //
    cCharacter = UartGetChar();
    g_iCounter++;

    if(cCharacter == '\r' || cCharacter == '\n' ||
    (iStringLength >= MAX_STRING_LENGTH -1))
    {
    if(iStringLength >= MAX_STRING_LENGTH - 1)
    {
    UartPutChar(cCharacter);
    cString[iStringLength] = cCharacter;
    iStringLength++;
    }
    cString[iStringLength] = '\0';
    iStringLength = 0;
    //
    // Echoes the input string
    //
    Report("\n\rcmd#%s\n\rcmd#", cString);
    sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx,
    pub_topic_sw2,cString,strlen((char*)cString),QOS2,RETAIN);

    }
    else
    {
    UartPutChar(cCharacter);
    cString[iStringLength] = cCharacter;
    iStringLength++;
    }


    //***** By dinesh for testing purpose////*****//
    // osi_MsgQRead( &g_PBQueue, &RecvQue, OSI_WAIT_FOREVER);


    if(PUSH_BUTTON_SW2_PRESSED == RecvQue.event)
    {
    Button_IF_EnableInterrupt(SW2);
    //
    // send publish message
    //
    sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx,
    pub_topic_sw2,data_sw2,strlen((char*)data_sw2),QOS2,RETAIN);
    UART_PRINT("\n\r CC3200 Publishes the following message \n\r");
    UART_PRINT("Topic: %s\n\r",pub_topic_sw2);
    UART_PRINT("Data: %s\n\r",data_sw2);
    }
    else if(PUSH_BUTTON_SW3_PRESSED == RecvQue.event)
    {
    Button_IF_EnableInterrupt(SW3);
    //
    // send publish message
    //
    sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx,
    pub_topic_sw3,data_sw3,strlen((char*)data_sw3),QOS2,RETAIN);
    UART_PRINT("\n\r CC3200 Publishes the following message \n\r");
    UART_PRINT("Topic: %s\n\r",pub_topic_sw3);
    UART_PRINT("Data: %s\n\r",data_sw3);
    }
    else if(BROKER_DISCONNECTION == RecvQue.event)
    {
    iConnBroker--;
    /* Derive the value of the local_con_conf or clt_ctx from the message */
    sl_ExtLib_MqttClientCtxDelete(((connect_config*)(RecvQue.hndl))->clt_ctx);

    if(!IS_CONNECTED(g_ulStatus))
    {
    UART_PRINT("device has disconnected from AP \n\r");

    UART_PRINT("retry connection to the AP\n\r");

    while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus)))
    {
    osi_Sleep(10);
    }
    goto connect_to_broker;

    }
    if(iConnBroker < 1)
    {
    //
    // device not connected to any broker
    //
    goto end;
    }
    }
    }
    end:
    //
    // Deinitializating the client library
    //
    sl_ExtLib_MqttClientExit();
    UART_PRINT("\n\r Exiting the Application\n\r");

    LOOP_FOREVER();
    }

    //*****************************************************************************
    //
    //! Main
    //!
    //! \param none
    //!
    //! This function
    //! 1. Invokes the SLHost task
    //! 2. Invokes the MqttClient
    //!
    //! \return None
    //!
    //*****************************************************************************
    void main()
    {
    long lRetVal = -1;
    //
    // Initialize the board configurations
    //
    BoardInit();

    //
    // Pinmux for UART
    //
    PinMuxConfig();

    //
    // Configuring UART
    //
    InitTerm();

    //
    // Display Application Banner
    //
    DisplayBanner("MQTT_Client Uart Demo");

    //
    // Start the SimpleLink Host
    //
    lRetVal = VStartSimpleLinkSpawnTask(SPAWN_TASK_PRIORITY);
    if(lRetVal < 0)
    {
    ERR_PRINT(lRetVal);
    LOOP_FOREVER();
    }

    //
    // Start the MQTT Client task
    //
    osi_MsgQCreate(&g_PBQueue,"PBQueue",sizeof(event_msg),10);
    lRetVal = osi_TaskCreate(MqttClient,
    (const signed char *)"Mqtt Client App",
    OSI_STACK_SIZE, NULL, 2, NULL );

    if(lRetVal < 0)
    {
    ERR_PRINT(lRetVal);
    LOOP_FOREVER();
    }
    //
    // Start the task scheduler
    //
    osi_start();
    }