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.

CC3220S-LAUNCHXL: Bring up TIDC-01005

Part Number: CC3220S-LAUNCHXL
Other Parts Discussed in Thread: TIDC-01005, UNIFLASH, CC3220S

Hi TI Wifi Experts,

I am working on bringing up TIDC-01005. first i have download and installed all the SDK match to the user guilde.

I loaded the Premade UniFlash ImageCreator Project and in Tera Term and I got:

[MQTT Thread] Connection to broker failed, Error code: -111 BRIDGE DISCONNECTION

  #define SL_ERROR_BSD_ECONNREFUSED (-111L) /* Connection refused */

This is likely the eclipse broker is not active anymore. Therefore, I do the following:

1. Download a new der from mosquitto.org

2. Changed the download der file to "eclipsecert.der"

3. Download a new der from github.com

4. Changed the download der file to "digicertca.der"

5. Go to uniflash advance -> userfiles

6. add all the dummy and the two downloaded .der files

7. burn and program image again

8. complete provisioning and I receive the same error.

Can you let me know what I missed? 

Thanks,

Shing 

 

  • Hi Shing,

    Did you update the MQTT server address in mqtt_client_task.c? What did you set it to?

    Best regards,

    Sarah

  • Hi Sarah,

    I didn't change the .c file. I was just loading the premade image with the new .der files in uniflash. 

    I will update the mqtt_client_task.c file in CCS as follow:

    URL: "mqtt://test.mosquitto.org"

    IP: "85.119.83.194"

    What should I do after I build the app.c in CCS? Do I need to make an image file and load it to the dev board, so I can update the userfiles with the new .der files?

    Thanks,

    Shing 

  • Hi Shing,

    You can use the same ImageCreator project, and replace the mcuimg.bin. You can do this from the Simple tab or the User Files. See the UniFlash ImageCreator SimpleLink Academy for details.

    Best regards,

    Sarah

  • Hi Sarah, 

    My problem doesn't resolve with the above updates. I outlined each of the steps I took. please let me know if I have missed anything. 

    step 1 - Updated the mqtt_client_task.c as follow:

    (I also tried: "mqtt://test.mosquitto.org" and "test.mosquitto.org")

    step 2 - Built (debug) in CCS

    step 3 - finded "wifi_doorlock_CC3220S_LAUNCHXL_tirtos_ccs.bin" in the project's debug folder and file name to "mcuimg.bin"

    step 4 - loaded the remade UniFlash ImageCreator Project to UniFlash

    step 5 - went to advance load the remade UniFlash ImageCreator Project to UniFlash

    step 6 - detected the existing "mcuimg.bin" from the sys folder, and "digicertca.der" and "eclipsecert.der" files from the top-level folder

    step 7 - added the new "mcuimg.bin" (originally "wifi_doorlock_CC3220S_LAUNCHXL_tirtos_ccs.bin") in the sys folder with "dummy-trusted-cert-key" and selected "dummy-trusted-cert" 

    step 8 - added the downloaded "digicertca.der" and "eclipsecert.der" files to the top level folder

    step 9 - in UniFlash: connect -> burn -> program image

    step 10 - change SOP to 100 -> power cycle

    step 12 - turn on Tara term

    step 11 - Finish AP provisioning

    Result - Got the same -111 error (after ~15mins it becomes -13)

    Thanks,

    Shing

  • Hi Shing,

    If you go to test.mosquitto.org, the server provides its own certificate for download. Have you tried this?

    Also be sure you updated Mqtt_Client_secure_files in mqtt_client_task.c to match the right certificate. You should replace eclipsecert.der with mosquitto.org.crt.

    You can reference the Secure Client Demo section of the Wi-Fi MQTT SimpleLink Academy.

    Best regards,

    Sarah

  • Hi Sarah,

    I followed the reference downloaded test.mosquitto.org and update the user file

    Update the Mqtt_Client_secure_files in mqtt_client_task.c

    but I am still getting the same -111 error 

    please let me know if i missed anything.

    Thanks

    Shing 

  • Hi Shing,

    Is your Mqtt_ClientCtx struct in mqtt_client_task.c using SERVER_ADDRESS or SERVER_IP_ADDRESS? If you are defining test.mosquitto.org, it should be SERVER_ADDRESS.

    Best regards,

    Sarah

  • Hi Sarah,

    I updated Mqtt_ClientCtx as above but I am still getting the same error -111.

    Tara term: 

    I attached the complete mqtt_client_task.c based on "simplelink_cc32xx_sdk_2_10_00_04"

    /*
     * Copyright (c) 2016, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     *
     * *  Neither the name of Texas Instruments Incorporated nor the names of
     *    its contributors may be used to endorse or promote products derived
     *    from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
     * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    /****************************************************************************************************************
                       INCLUDES
    ****************************************************************************************************************/
    
    /* Standard includes                                                          */
    #include <unistd.h>
    
    /* SimpleLink includes                                                        */
    #include <ti/drivers/net/wifi/simplelink.h>
    
    /* MQTT Library includes                                                      */
    #include <ti/net/mqtt/mqttclient.h>
    
    /* POSIX includes                                                             */
    #include "pthread.h"
    
    /* TI-Drivers includes                                                        */
    #include <ti/display/Display.h>
    
    /* Application includes                                                       */
    #include "Board.h"
    
    #include "wifi_doorlock_app.h"
    #include "mqtt_client_task.h"
    #include "motor_driver_if.h"
    
    /****************************************************************************************************************
                       DEFINES
    ****************************************************************************************************************/
    /* Define to support NTP */
    #define NTP_START_YEAR              (1900)
    #define CC32XX_MONTH_START_OFFSET   (1)
    
    /* Operate Lib in MQTT 3.1 mode.                                              */
    #define MQTT_3_1_1               false
    #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 SECURE_CLIENT
    
    /* Defining Broker IP address and port Number                                 */
    #define SERVER_ADDRESS           "test.mosquitto.org"
    #define SERVER_IP_ADDRESS        "85.119.83.194" //
    #define PORT_NUMBER              1883
    #define SECURED_PORT_NUMBER      8883
    #define LOOPBACK_PORT            1882
    
    /* Clean session flag                                                         */
    #define CLEAN_SESSION            true
    
    /* Retain Flag. Used in publish message.                                      */
    #define RETAIN_ENABLE            1
    
    #define LOCK_CONTROL_CMD_LENGTH  5
    
    #define TOPIC_START_INDEX       (12)
    
    #define CLIENT_NUM_SECURE_FILES 1
    
    /****************************************************************************************************************
                       LOCAL FUNCTION PROTOTYPES
    ****************************************************************************************************************/
    void *  MqttClientThread(void * pvParameters);
    int32_t MqttClient_start();
    void    Mqtt_ClientStop(uint8_t disconnect);
    
    /****************************************************************************************************************
                       GLOBAL VARIABLES
    ****************************************************************************************************************/
    
    /* MQTT RX task handle                                                        */
    pthread_t g_rx_task_hndl        = (pthread_t) NULL;
    
    /* Overall Application App Context                                            */
    extern Application_CB App_CB;
    extern Display_Handle display;
    
    /* Struct with parameters for MQTT connection                                 */
    MQTTClient_Params  MqttClientExample_params;
    
    /* Client ID                                                                  */
    /* If ClientId isn't set, the MAC address of the device will be copied into   */
    /* the ClientID parameter.                                                    */
    char ClientId[13] = {'\0'};
    
    /* Subscription topics and qos values                                         */
    char *topic[SUBSCRIPTION_TOPIC_COUNT] =
            { SUBSCRIPTION_TOPIC0, SUBSCRIPTION_TOPIC1, \
              SUBSCRIPTION_TOPIC2, SUBSCRIPTION_TOPIC3 };
    
    unsigned char qos[SUBSCRIPTION_TOPIC_COUNT] =
            { MQTT_QOS_2, MQTT_QOS_2, MQTT_QOS_2, MQTT_QOS_2 };
    
    /* Publishing topics and messages                                             */
    char *publish_topic[PUBLISH_TOPIC_COUNT] = { PUBLISH_TOPIC0 };
    
    char *publish_data[PUBLISH_DATA_COUNT] = { PUBLISH_TOPIC0_LOCKED, PUBLISH_TOPIC0_UNLOCKED };
    
    #ifdef  SECURE_CLIENT
    char *Mqtt_Client_secure_files[CLIENT_NUM_SECURE_FILES] = {"mosquitto.org.crt"};
    
    /* Initialization structure to be used with sl_ExtMqtt_Init API. In order to  */
    /* use secured socket method, the flag MQTTCLIENT_NETCONN_SEC, cipher,        */
    /* n_files and secure_files must be configured.                               */
    /* certificates also must be programmed  ("ca-cert.pem").                     */
    /* The first parameter is a bit mask which configures server address type and */
    /* security mode.                                                             */
    /* Server address type: IPv4, IPv6 and URL must be declared with The          */
    /* corresponding flag.                                                        */
    /* Security mode: The flag MQTTCLIENT_NETCONN_SEC enables the security (TLS)  */
    /* which includes domain name verification and certificate catalog            */
    /* verification, those verifications can be disabled by adding to the bit mask*/
    /* MQTTCLIENT_NETCONN_SKIP_DOMAIN_NAME_VERIFICATION and                       */
    /* MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION flags             */
    /* Example: MQTTCLIENT_NETCONN_IP6 | MQTTCLIENT_NETCONN_SEC |                 */
    /* MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION                   */
    /* For this bit mask, the IPv6 address type will be in use, the security      */
    /* feature will be enable and the certificate catalog verification will be    */
    /* skipped.                                                                   */
    /* Note: The domain name verification requires URL Server address type        */
    /*       otherwise, this verification will be disabled.                       */
    MQTTClient_ConnParams Mqtt_ClientCtx =
    {
         MQTTCLIENT_NETCONN_IP4 | MQTTCLIENT_NETCONN_SEC | MQTT_DEV_NETCONN_OPT_SKIP_CERTIFICATE_CATALOG_VERIFICATION | MQTTCLIENT_NETCONN_SKIP_DOMAIN_NAME_VERIFICATION,
         SERVER_ADDRESS,//SERVER_IP_ADDRESS,
         SECURED_PORT_NUMBER,
         SLNETSOCK_SEC_METHOD_SSLv3_TLSV1_2,
         SLNETSOCK_SEC_CIPHER_FULL_LIST,
         CLIENT_NUM_SECURE_FILES,
         Mqtt_Client_secure_files
    };
    #else
    MQTTClient_ConnParams Mqtt_ClientCtx =
    {
        MQTTCLIENT_NETCONN_URL,
        SERVER_ADDRESS,
        PORT_NUMBER, 0, 0, 0,
        NULL
    };
    #endif
    
    /* Initialize the will_param structure to the default will parameters         */
    MQTTClient_Will will_param =
    {
        WILL_TOPIC,
        WILL_MSG,
        WILL_QOS,
        WILL_RETAIN
    };
    
    uint16_t    mqttKeepAliveTimeout = 43200; // 43200 sec = 12hr * 60 min * 60 sec
    
    //*****************************************************************************
    //
    //! Task implementing MQTT Server plus client bridge
    //!
    //! This function
    //!    1. Initializes network driver and connects to the default AP
    //!    2. Initializes the mqtt client ans server libraries and set up MQTT
    //!       with the remote broker.
    //!    3. set up the button events and their callbacks(for publishing)
    //!    4. handles the callback signals
    //!
    //! \param  none
    //!
    //! \return None
    //!
    //*****************************************************************************
    void * MqttClient(void *pvParameters)
    {
        long lRetVal = -1;
        char *tmpBuff;
        char recvdMsg[256];
        int32_t iCount = 0;
        mqtt_task_states_t    mqttState = MQTT_LIB_INITIALIZATION;
        struct msgQueue queueElemRecv;
    
        memset(recvdMsg, 0x00, sizeof(recvdMsg));
    
        sem_post(&App_CB.mqttReady);
        sem_wait(&App_CB.startBarrier);
    
        while(1)
        {
            switch(mqttState)
            {
            case MQTT_LIB_INITIALIZATION:
            {
                lRetVal = MqttClient_start();
                if (lRetVal == -1)
                {
                    Display_printf(
                            display,
                            0,
                            0,
                            "\t [MQTT Thread] MQTT Client library initialization failed");
                    while (1);
                }
                else
                {
                    Display_printf(
                            display,
                            0,
                            0,
                            "[MQTT Thread] MQTT Client library initialized successfully");
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttInitialized);
    
                    if(GET_STATUS_BIT(App_CB.status, AppStatusBits_Connection) && GET_STATUS_BIT(App_CB.status, AppStatusBits_IpAcquired))
                    {
                        mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
                    }
                    else
                    {
                        mqttState = MQTT_WAITING_FOR_NETWORK_CONNECTION;
                    }
                }
            }
                break;
            case MQTT_WAITING_FOR_NETWORK_CONNECTION:
            {
                sem_wait(&App_CB.connectionDoneSignal);
                mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
            }
                break;
            case MQTT_CLIENT_CONNECTING_TO_BROKER:
            {
    
    #if CLEAN_SESSION == false
                bool clean = CLEAN_SESSION;
                MQTTClient_set(App_CB.mqttClientHandle, MQTT_CLIENT_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(App_CB.mqttClientHandle);
    
                /* 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)
                {
                    /* lib initialization failed                                      */
                    Display_printf(
                            display,
                            0,
                            0,
                            "\t [MQTT Thread] Connection to broker failed, Error code: %d",
                            lRetVal);
    
                    MQTTClient_disconnect(App_CB.mqttClientHandle);
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
                    Mqtt_ClientStop(1);
                    while (GET_STATUS_BIT(App_CB.status,
                                          AppStatusBits_MqttStopInProgress))
                    {
                        sleep(1);
                    }
                    mqttState = MQTT_LIB_INITIALIZATION;
                    sleep(1);
                }
                else
                {
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
                    mqttState = MQTT_CLIENT_CONNECTED;
                }
                /* Subscribe to topics when session is not stored by the server       */
                if (GET_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected)
                        && (0 == lRetVal))
                {
                    uint8_t subIndex;
                    MQTTClient_SubscribeParams subscriptionInfo[SUBSCRIPTION_TOPIC_COUNT];
    
                    for (subIndex = 0; subIndex < SUBSCRIPTION_TOPIC_COUNT;
                            subIndex++)
                    {
                        subscriptionInfo[subIndex].topic = topic[subIndex];
                        subscriptionInfo[subIndex].qos = qos[subIndex];
                    }
    
                    if (MQTTClient_subscribe(App_CB.mqttClientHandle,
                                             subscriptionInfo,
                                             SUBSCRIPTION_TOPIC_COUNT) < 0)
                    {
                        Display_printf(display, 0, 0,
                                       "\t [MQTT Thread] Subscription Error");
                        MQTTClient_disconnect(App_CB.mqttClientHandle);
    
                        /* Manually disconnected, need to reconnect to broker*/
                        SET_STATUS_BIT(App_CB.status,
                                       AppStatusBits_MqttStopInProgress);
                        Mqtt_ClientStop(1);
                        while (GET_STATUS_BIT(App_CB.status,
                                              AppStatusBits_MqttStopInProgress))
                        {
                            sleep(1);
                        }
                        mqttState = MQTT_LIB_INITIALIZATION;
                    }
                    else
                    {
                        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT;
                                iCount++)
                        {
                            Display_printf(display, 0, 0,
                                           "[MQTT Thread] Client subscribed on %s",
                                           topic[iCount]);
                        }
                    }
                }
            }
                break;
            case MQTT_CLIENT_CONNECTED:
            {
                /* handling the signals from various callbacks including the push button  */
                /* prompting the client to publish a msg on PUB_TOPIC OR msg received by  */
                /* the server on enrolled topic(for which the on-board client ha enrolled)*/
                /* from a local client(will be published to the remote broker by the      */
                /* client) OR msg received by the client from the remote broker (need to  */
                /* be sent to the server to see if any local client has subscribed on the */
                /* same topic).                                                           */
    
                /* waiting for signals                                                */
                mq_receive(App_CB.mqttQueue, (char*) &queueElemRecv,
                           sizeof(struct msgQueue), NULL);
    
                switch (queueElemRecv.event)
                {
                /* msg received by client from remote broker (on a topic      */
                /* subscribed by local client)                                */
                case MSG_RECV_BY_CLIENT:
                    tmpBuff = (char *) ((char *) queueElemRecv.msgPtr
                            + TOPIC_START_INDEX);
                    if (strncmp(tmpBuff, (const char*) topic[1],
                                queueElemRecv.topLen) == 0)
                    {
                        struct motorMsg queueElem;
    
                        strncpy(recvdMsg,
                                ((char*) queueElemRecv.msgPtr + TOPIC_START_INDEX
                                        + queueElemRecv.topLen + 1),
                                queueElemRecv.msgLen);
                        recvdMsg[queueElemRecv.msgLen] = '\0';
                        if ((strncmp(recvdMsg, "lock", sizeof(queueElemRecv.msgLen))
                                == 0) && !App_CB.locked)
                        {
                            queueElem.event = LOCK_MOTOR_CMD;
                            App_CB.locked = true;
                            if (Motor_SendMsgToQueue(&queueElem))
                            {
                                Display_printf(
                                        display, 0, 0,
                                        "\t [MQTT Thread] Queue is full");
                            }
                        }
                        else if ((strncmp(recvdMsg, "unlock",
                                          sizeof(queueElemRecv.msgLen)) == 0) && App_CB.locked)
                        {
                            queueElem.event = UNLOCK_MOTOR_CMD;
                            App_CB.locked = false;
                            if (Motor_SendMsgToQueue(&queueElem))
                            {
                                Display_printf(
                                        display, 0, 0,
                                        "\t [MQTT Thread] Queue is full");
                            }
                        }
                        else
                        {
                            Display_printf(display, 0, 0,
                                           "[MQTT Thread] Message: %s",
                                           recvdMsg);
                            Display_printf(
                                    display,
                                    0,
                                    0,
                                    "[MQTT Thread] Message ignored because lock is already in requested state or payload is invalid");
                            break;
                        }
                    }
                    else if (strncmp(tmpBuff, (const char*) topic[2],
                                     queueElemRecv.topLen) == 0)
                    {
                        char msg[30] = { '\0' };
    
                        strcpy(msg,
                               (App_CB.locked == true) ?
                               PUBLISH_TOPIC0_LOCKED :
                                                         PUBLISH_TOPIC0_UNLOCKED);
    
                        lRetVal = MQTTClient_publish(
                                App_CB.mqttClientHandle, (char*) publish_topic[0],
                                strlen((char*) publish_topic[0]), (char*) msg,
                                strlen((char*) msg),
                                MQTT_QOS_2 | ((RETAIN_ENABLE) ?
                                MQTT_PUBLISH_RETAIN :
                                                                0));
    
                        Display_printf(
                                display,
                                0,
                                0,
                                "\n\r [MQTT Thread] CC3200 Publishes the following message");
                        Display_printf(display, 0, 0, "[MQTT Thread] Topic: %s",
                                       publish_topic);
                        Display_printf(display, 0, 0, "[MQTT Thread] Data: %s",
                                       msg);
                    }
                    else if (strncmp(tmpBuff, (const char*) topic[3],
                                     queueElemRecv.topLen) == 0)
                    {
                        struct controlMsg controlMsg;
    
                        controlMsg.threadID = 1;
                        controlMsg.msg = CONTROL_MSG_OTA_START;
    
                        if (!GET_STATUS_BIT(App_CB.status,
                                            AppStatusBits_OtaInProgress))
                        {
                            mq_send(App_CB.controlQueue, (char *) &controlMsg,
                                    sizeof(struct controlMsg), NULL);
    
                            SET_STATUS_BIT(App_CB.status,
                                           AppStatusBits_OtaInProgress);
                        }
                    }
    
                    free(queueElemRecv.msgPtr);
                    break;
    
                    /* On-board client disconnected from remote broker, only      */
                    /* local MQTT network will work                               */
                case LOCAL_CLIENT_DISCONNECTION:
                    Display_printf(display, 0, 0,
                                   "\t [MQTT Thread] On-board Client Disconnected");
    
                    if(GET_STATUS_BIT(App_CB.status, AppStatusBits_Connection) && GET_STATUS_BIT(App_CB.status, AppStatusBits_IpAcquired))
                    {
                        MQTTClient_disconnect(App_CB.mqttClientHandle);
                        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
                        mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
                    }
                    else
                    {
                        Mqtt_ClientStop(1);
                        mqttState = MQTT_LIB_INITIALIZATION;
                    }
                    break;
    
                case THREAD_TERMINATE_REQ:
                    Display_printf(display, 0, 0,
                                   "[MQTT Thread] Terminating MQTT Client");
    
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
                    Mqtt_ClientStop(1);
                    pthread_exit(0);
                    return NULL;
    
                default:
                    break;
                }
                break;
            }
            }
        }
    }
    
    //*****************************************************************************
    //
    //! MQTT_SendMsgToQueue - Utility function that receive msgQueue parameter and
    //! tries to push it the queue with minimal time for timeout of 0.
    //! If the queue isn't full the parameter will be stored and the function
    //! will return 0.
    //! If the queue is full and the timeout expired (because the timeout parameter
    //! is 0 it will expire immediately), the parameter is thrown away and the
    //! function will return -1 as an error for full queue.
    //!
    //! \param[in] struct msgQueue *queueElement
    //!
    //! \return 0 on success, -1 on error
    //
    //*****************************************************************************
    int32_t MQTT_SendMsgToQueue(struct msgQueue *queueElement)
    {
        struct timespec abstime = { 0 };
    
        clock_gettime(CLOCK_REALTIME, &abstime);
    
        if (App_CB.mqttQueue)
        {
            /* send message to the queue                                         */
            if (mq_timedsend(App_CB.mqttQueue, (char *) queueElement,
                             sizeof(struct msgQueue), 0, &abstime) == 0)
            {
                return 0;
            }
        }
        return -1;
    }
    
    int32_t MqttClient_start()
    {
        int32_t lRetVal = -1;
    
        int32_t threadArg = 100;
        pthread_attr_t pAttrs;
        struct sched_param priParam;
    
        MqttClientExample_params.clientId = ClientId;
        MqttClientExample_params.connParams = &Mqtt_ClientCtx;
        MqttClientExample_params.mqttMode31 = MQTT_3_1;
        MqttClientExample_params.blockingSend = true;
    
        /* Initialize MQTT client lib                                             */
        App_CB.mqttClientHandle = MQTTClient_create(MqttClientCallback,
                                                    &MqttClientExample_params);
        if (App_CB.mqttClientHandle == NULL)
        {
            /* Lib initialization failed */
            Display_printf(display, 0, 0,
                           "\t [MQTT Thread] Error - MQTT client handle is null");
            return -1;
        }
    
        /* Open Client Receive Thread start the receive task. Set priority and    */
        /* stack size attributes                                                  */
        pthread_attr_init(&pAttrs);
        priParam.sched_priority = 4;
        lRetVal = pthread_attr_setschedparam(&pAttrs, &priParam);
        lRetVal |= pthread_attr_setstacksize(&pAttrs, MQTT_CLIENT_RX_TASK_SIZE);
        lRetVal |= pthread_attr_setdetachstate(&pAttrs, PTHREAD_CREATE_DETACHED);
        lRetVal |= pthread_create(&g_rx_task_hndl, &pAttrs, MqttClientThread,
                                  (void *) &threadArg);
        if (lRetVal != 0)
        {
            Display_printf(display, 0, 0,
                           "[MQTT Thread] Client Thread create failed");
            return -1;
        }
    
        /* setting will parameters                                                */
        MQTTClient_set(App_CB.mqttClientHandle, MQTTClient_WILL_PARAM, &will_param,
                       sizeof(will_param));
        MQTTClient_set(App_CB.mqttClientHandle, MQTTClient_KEEPALIVE_TIME,
                       &mqttKeepAliveTimeout, sizeof(mqttKeepAliveTimeout));
    
        return 0;
    }
    
    //*****************************************************************************
    //!
    //! MQTT Client stop - Unsubscribe from the subscription topics and exit the
    //! MQTT client lib.
    //!
    //! \param  none
    //!
    //! \return None
    //!
    //*****************************************************************************
    
    void Mqtt_ClientStop(uint8_t disconnect)
    {
        uint32_t iCount;
    
        MQTTClient_UnsubscribeParams subscriptionInfo[SUBSCRIPTION_TOPIC_COUNT];
    
        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT; iCount++)
        {
            subscriptionInfo[iCount].topic = topic[iCount];
        }
    
        MQTTClient_unsubscribe(App_CB.mqttClientHandle, subscriptionInfo,
        SUBSCRIPTION_TOPIC_COUNT);
        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT; iCount++)
        {
            Display_printf(display, 0, 0,
                           "[MQTT Thread] Unsubscribed from the topic %s",
                           topic[iCount]);
        }
    
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttInitialized);
    
        /* exiting the Client library                                             */
        MQTTClient_delete(App_CB.mqttClientHandle);
    
        Display_printf(display, 0, 0, "[MQTT Thread] MQTT Client Handle deleted");
    
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
    }
    
    void *MqttClientThread(void * pvParameters)
    {
        struct msgQueue queueElement;
        struct msgQueue queueElemRecv;
    
        MQTTClient_run((MQTTClient_Handle) pvParameters);
    
        /* Check if MQTT thread is already being stopped */
        if(!GET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress))
        {
            SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
    
            queueElement.event = LOCAL_CLIENT_DISCONNECTION;
            queueElement.msgPtr = NULL;
    
            /* write message indicating disconnect Broker message.                    */
            if (MQTT_SendMsgToQueue(&queueElement))
            {
                Display_printf(
                        display,
                        0,
                        0,
                        "\t [MQTT Thread] Queue is full, throw first msg and send the new one");
                mq_receive(App_CB.mqttQueue, (char*) &queueElemRecv,
                           sizeof(struct msgQueue), NULL);
                MQTT_SendMsgToQueue(&queueElement);
            }
        }
    
        pthread_exit(0);
    
        return NULL;
    }
    

    Thanks,

    Shing 

  • Hi Shing,

    Did you follow the other steps in the Wi-Fi MQTT lab? MQTTCLIENT_NETCONN_IP4 should be MQTTCLIENT_NETCONN_URL.

    Best regards,

    Sarah

  • Hi Sarah,

    Starting "Configuring the Secure Client Demo"

    task 1: Enabling the secured client

    step 1: update "MQTTClient_ConnParams Mqtt_ClientCtx"

    commanded out the existing parameter and add the updated MQTTClient_ConnParams Mqtt_ClientCtx

    step 2: 

    step 3:

    step 4: I can't find where to update the date and time

    step 5: I can't the function WifiInt() and MQTT_IF_Init()

    -----Complete code modification-----

    flash the board with new .bin and the .crt file

    run trar term and I am getting a subscription error this time

      

    please let me know if i have missed anything

    Thanks,

    Shing 

  • Hi Shing,

    I am able to run the same demo successfully. Did you make any other changes to the application? What error code is MqttClient_subscribe() returning?

    Best regards,

    Sarah

  • Hi Sarah,

    I re-import the project and redo the code updates, but I am still getting the same error as above. Can you post your code?

    here is mine (I only touched the mqtt_client_task.c)

    /*
     * Copyright (c) 2016, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     *
     * *  Neither the name of Texas Instruments Incorporated nor the names of
     *    its contributors may be used to endorse or promote products derived
     *    from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
     * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    /****************************************************************************************************************
                       INCLUDES
    ****************************************************************************************************************/
    
    /* Standard includes                                                          */
    #include <unistd.h>
    
    /* SimpleLink includes                                                        */
    #include <ti/drivers/net/wifi/simplelink.h>
    
    /* MQTT Library includes                                                      */
    #include <ti/net/mqtt/mqttclient.h>
    
    /* POSIX includes                                                             */
    #include "pthread.h"
    
    /* TI-Drivers includes                                                        */
    #include <ti/display/Display.h>
    
    /* Application includes                                                       */
    #include "Board.h"
    
    #include "wifi_doorlock_app.h"
    #include "mqtt_client_task.h"
    #include "motor_driver_if.h"
    
    /****************************************************************************************************************
                       DEFINES
    ****************************************************************************************************************/
    /* Define to support NTP */
    #define NTP_START_YEAR              (1900)
    #define CC32XX_MONTH_START_OFFSET   (1)
    
    /* Operate Lib in MQTT 3.1 mode.                                              */
    #define MQTT_3_1_1               false
    #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 SECURE_CLIENT
    
    /* Defining Broker IP address and port Number                                 */
    
     #define MQTT_CONNECTION_FLAGS       MQTTCLIENT_NETCONN_URL | MQTTCLIENT_NETCONN_SEC \
                                         | MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION
     #define MQTT_CONNECTION_ADDRESS     "test.mosquitto.org"
     #define MQTT_CONNECTION_PORT_NUMBER  8883
    
    
    #define SERVER_ADDRESS           "m2m.eclipse.org"
    #define SERVER_IP_ADDRESS        "198.41.30.241"
    #define PORT_NUMBER              1883
    #define SECURED_PORT_NUMBER      8883
    #define LOOPBACK_PORT            1882
    
    /* Clean session flag                                                         */
    #define CLEAN_SESSION            true
    
    /* Retain Flag. Used in publish message.                                      */
    #define RETAIN_ENABLE            1
    
    #define LOCK_CONTROL_CMD_LENGTH  5
    
    #define TOPIC_START_INDEX       (12)
    
    #define CLIENT_NUM_SECURE_FILES 1
    
    /****************************************************************************************************************
                       LOCAL FUNCTION PROTOTYPES
    ****************************************************************************************************************/
    void *  MqttClientThread(void * pvParameters);
    int32_t MqttClient_start();
    void    Mqtt_ClientStop(uint8_t disconnect);
    
    /****************************************************************************************************************
                       GLOBAL VARIABLES
    ****************************************************************************************************************/
    
    /* MQTT RX task handle                                                        */
    pthread_t g_rx_task_hndl        = (pthread_t) NULL;
    
    /* Overall Application App Context                                            */
    extern Application_CB App_CB;
    extern Display_Handle display;
    
    /* Struct with parameters for MQTT connection                                 */
    MQTTClient_Params  MqttClientExample_params;
    
    /* Client ID                                                                  */
    /* If ClientId isn't set, the MAC address of the device will be copied into   */
    /* the ClientID parameter.                                                    */
    char ClientId[13] = {'\0'};
    
    /* Subscription topics and qos values                                         */
    char *topic[SUBSCRIPTION_TOPIC_COUNT] =
            { SUBSCRIPTION_TOPIC0, SUBSCRIPTION_TOPIC1, \
              SUBSCRIPTION_TOPIC2, SUBSCRIPTION_TOPIC3 };
    
    unsigned char qos[SUBSCRIPTION_TOPIC_COUNT] =
            { MQTT_QOS_2, MQTT_QOS_2, MQTT_QOS_2, MQTT_QOS_2 };
    
    /* Publishing topics and messages                                             */
    char *publish_topic[PUBLISH_TOPIC_COUNT] = { PUBLISH_TOPIC0 };
    
    char *publish_data[PUBLISH_DATA_COUNT] = { PUBLISH_TOPIC0_LOCKED, PUBLISH_TOPIC0_UNLOCKED };
    
    #ifdef  SECURE_CLIENT
    char *Mqtt_Client_secure_files[CLIENT_NUM_SECURE_FILES] = {"mosquitto.org.crt"};
    
    /* Initialization structure to be used with sl_ExtMqtt_Init API. In order to  */
    /* use secured socket method, the flag MQTTCLIENT_NETCONN_SEC, cipher,        */
    /* n_files and secure_files must be configured.                               */
    /* certificates also must be programmed  ("ca-cert.pem").                     */
    /* The first parameter is a bit mask which configures server address type and */
    /* security mode.                                                             */
    /* Server address type: IPv4, IPv6 and URL must be declared with The          */
    /* corresponding flag.                                                        */
    /* Security mode: The flag MQTTCLIENT_NETCONN_SEC enables the security (TLS)  */
    /* which includes domain name verification and certificate catalog            */
    /* verification, those verifications can be disabled by adding to the bit mask*/
    /* MQTTCLIENT_NETCONN_SKIP_DOMAIN_NAME_VERIFICATION and                       */
    /* MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION flags             */
    /* Example: MQTTCLIENT_NETCONN_IP6 | MQTTCLIENT_NETCONN_SEC |                 */
    /* MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION                   */
    /* For this bit mask, the IPv6 address type will be in use, the security      */
    /* feature will be enable and the certificate catalog verification will be    */
    /* skipped.                                                                   */
    /* Note: The domain name verification requires URL Server address type        */
    /*       otherwise, this verification will be disabled.                       */
    MQTTClient_ConnParams Mqtt_ClientCtx =
    {
          MQTT_CONNECTION_FLAGS,                  // connection flags
          MQTT_CONNECTION_ADDRESS,                // server address
          MQTT_CONNECTION_PORT_NUMBER,            // port number of MQTT server
          SLNETSOCK_SEC_METHOD_SSLv3_TLSV1_2,     // method for secure socket
          SLNETSOCK_SEC_CIPHER_FULL_LIST,         // cipher for secure socket
          1,                                      // number of files for secure connection
          Mqtt_Client_secure_files
    
    
         //MQTTCLIENT_NETCONN_IP4 | MQTTCLIENT_NETCONN_SEC | MQTT_DEV_NETCONN_OPT_SKIP_CERTIFICATE_CATALOG_VERIFICATION | MQTTCLIENT_NETCONN_SKIP_DOMAIN_NAME_VERIFICATION,
         //SERVER_IP_ADDRESS,
         //SECURED_PORT_NUMBER,
         //SLNETSOCK_SEC_METHOD_SSLv3_TLSV1_2,
         //SLNETSOCK_SEC_CIPHER_FULL_LIST,
         //CLIENT_NUM_SECURE_FILES,
    
    };
    #else
    MQTTClient_ConnParams Mqtt_ClientCtx =
    {
        //MQTTCLIENT_NETCONN_URL,
        //SERVER_ADDRESS,
        //PORT_NUMBER, 0, 0, 0,
        //NULL
    };
    #endif
    
    /* Initialize the will_param structure to the default will parameters         */
    MQTTClient_Will will_param =
    {
        WILL_TOPIC,
        WILL_MSG,
        WILL_QOS,
        WILL_RETAIN
    };
    
    uint16_t    mqttKeepAliveTimeout = 43200; // 43200 sec = 12hr * 60 min * 60 sec
    
    //*****************************************************************************
    //
    //! Task implementing MQTT Server plus client bridge
    //!
    //! This function
    //!    1. Initializes network driver and connects to the default AP
    //!    2. Initializes the mqtt client ans server libraries and set up MQTT
    //!       with the remote broker.
    //!    3. set up the button events and their callbacks(for publishing)
    //!    4. handles the callback signals
    //!
    //! \param  none
    //!
    //! \return None
    //!
    //*****************************************************************************
    void * MqttClient(void *pvParameters)
    {
        long lRetVal = -1;
        char *tmpBuff;
        char recvdMsg[256];
        int32_t iCount = 0;
        mqtt_task_states_t    mqttState = MQTT_LIB_INITIALIZATION;
        struct msgQueue queueElemRecv;
    
        memset(recvdMsg, 0x00, sizeof(recvdMsg));
    
        sem_post(&App_CB.mqttReady);
        sem_wait(&App_CB.startBarrier);
    
        while(1)
        {
            switch(mqttState)
            {
            case MQTT_LIB_INITIALIZATION:
            {
                lRetVal = MqttClient_start();
                if (lRetVal == -1)
                {
                    Display_printf(
                            display,
                            0,
                            0,
                            "\t [MQTT Thread] MQTT Client library initialization failed");
                    while (1);
                }
                else
                {
                    Display_printf(
                            display,
                            0,
                            0,
                            "[MQTT Thread] MQTT Client library initialized successfully");
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttInitialized);
    
                    if(GET_STATUS_BIT(App_CB.status, AppStatusBits_Connection) && GET_STATUS_BIT(App_CB.status, AppStatusBits_IpAcquired))
                    {
                        mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
                    }
                    else
                    {
                        mqttState = MQTT_WAITING_FOR_NETWORK_CONNECTION;
                    }
                }
            }
                break;
            case MQTT_WAITING_FOR_NETWORK_CONNECTION:
            {
                sem_wait(&App_CB.connectionDoneSignal);
                mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
            }
                break;
            case MQTT_CLIENT_CONNECTING_TO_BROKER:
            {
    
    #if CLEAN_SESSION == false
                bool clean = CLEAN_SESSION;
                MQTTClient_set(App_CB.mqttClientHandle, MQTT_CLIENT_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(App_CB.mqttClientHandle);
    
                /* 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)
                {
                    /* lib initialization failed                                      */
                    Display_printf(
                            display,
                            0,
                            0,
                            "\t [MQTT Thread] Connection to broker failed, Error code: %d",
                            lRetVal);
    
                    MQTTClient_disconnect(App_CB.mqttClientHandle);
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
                    Mqtt_ClientStop(1);
                    while (GET_STATUS_BIT(App_CB.status,
                                          AppStatusBits_MqttStopInProgress))
                    {
                        sleep(1);
                    }
                    mqttState = MQTT_LIB_INITIALIZATION;
                    sleep(1);
                }
                else
                {
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
                    mqttState = MQTT_CLIENT_CONNECTED;
                }
                /* Subscribe to topics when session is not stored by the server       */
                if (GET_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected)
                        && (0 == lRetVal))
                {
                    uint8_t subIndex;
                    MQTTClient_SubscribeParams subscriptionInfo[SUBSCRIPTION_TOPIC_COUNT];
    
                    for (subIndex = 0; subIndex < SUBSCRIPTION_TOPIC_COUNT;
                            subIndex++)
                    {
                        subscriptionInfo[subIndex].topic = topic[subIndex];
                        subscriptionInfo[subIndex].qos = qos[subIndex];
                    }
    
                    if (MQTTClient_subscribe(App_CB.mqttClientHandle,
                                             subscriptionInfo,
                                             SUBSCRIPTION_TOPIC_COUNT) < 0)
                    {
                        Display_printf(display, 0, 0,
                                       "\t [MQTT Thread] Subscription Error");
                        MQTTClient_disconnect(App_CB.mqttClientHandle);
    
                        /* Manually disconnected, need to reconnect to broker*/
                        SET_STATUS_BIT(App_CB.status,
                                       AppStatusBits_MqttStopInProgress);
                        Mqtt_ClientStop(1);
                        while (GET_STATUS_BIT(App_CB.status,
                                              AppStatusBits_MqttStopInProgress))
                        {
                            sleep(1);
                        }
                        mqttState = MQTT_LIB_INITIALIZATION;
                    }
                    else
                    {
                        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT;
                                iCount++)
                        {
                            Display_printf(display, 0, 0,
                                           "[MQTT Thread] Client subscribed on %s",
                                           topic[iCount]);
                        }
                    }
                }
            }
                break;
            case MQTT_CLIENT_CONNECTED:
            {
                /* handling the signals from various callbacks including the push button  */
                /* prompting the client to publish a msg on PUB_TOPIC OR msg received by  */
                /* the server on enrolled topic(for which the on-board client ha enrolled)*/
                /* from a local client(will be published to the remote broker by the      */
                /* client) OR msg received by the client from the remote broker (need to  */
                /* be sent to the server to see if any local client has subscribed on the */
                /* same topic).                                                           */
    
                /* waiting for signals                                                */
                mq_receive(App_CB.mqttQueue, (char*) &queueElemRecv,
                           sizeof(struct msgQueue), NULL);
    
                switch (queueElemRecv.event)
                {
                /* msg received by client from remote broker (on a topic      */
                /* subscribed by local client)                                */
                case MSG_RECV_BY_CLIENT:
                    tmpBuff = (char *) ((char *) queueElemRecv.msgPtr
                            + TOPIC_START_INDEX);
                    if (strncmp(tmpBuff, (const char*) topic[1],
                                queueElemRecv.topLen) == 0)
                    {
                        struct motorMsg queueElem;
    
                        strncpy(recvdMsg,
                                ((char*) queueElemRecv.msgPtr + TOPIC_START_INDEX
                                        + queueElemRecv.topLen + 1),
                                queueElemRecv.msgLen);
                        recvdMsg[queueElemRecv.msgLen] = '\0';
                        if ((strncmp(recvdMsg, "lock", sizeof(queueElemRecv.msgLen))
                                == 0) && !App_CB.locked)
                        {
                            queueElem.event = LOCK_MOTOR_CMD;
                            App_CB.locked = true;
                            if (Motor_SendMsgToQueue(&queueElem))
                            {
                                Display_printf(
                                        display, 0, 0,
                                        "\t [MQTT Thread] Queue is full");
                            }
                        }
                        else if ((strncmp(recvdMsg, "unlock",
                                          sizeof(queueElemRecv.msgLen)) == 0) && App_CB.locked)
                        {
                            queueElem.event = UNLOCK_MOTOR_CMD;
                            App_CB.locked = false;
                            if (Motor_SendMsgToQueue(&queueElem))
                            {
                                Display_printf(
                                        display, 0, 0,
                                        "\t [MQTT Thread] Queue is full");
                            }
                        }
                        else
                        {
                            Display_printf(display, 0, 0,
                                           "[MQTT Thread] Message: %s",
                                           recvdMsg);
                            Display_printf(
                                    display,
                                    0,
                                    0,
                                    "[MQTT Thread] Message ignored because lock is already in requested state or payload is invalid");
                            break;
                        }
                    }
                    else if (strncmp(tmpBuff, (const char*) topic[2],
                                     queueElemRecv.topLen) == 0)
                    {
                        char msg[30] = { '\0' };
    
                        strcpy(msg,
                               (App_CB.locked == true) ?
                               PUBLISH_TOPIC0_LOCKED :
                                                         PUBLISH_TOPIC0_UNLOCKED);
    
                        lRetVal = MQTTClient_publish(
                                App_CB.mqttClientHandle, (char*) publish_topic[0],
                                strlen((char*) publish_topic[0]), (char*) msg,
                                strlen((char*) msg),
                                MQTT_QOS_2 | ((RETAIN_ENABLE) ?
                                MQTT_PUBLISH_RETAIN :
                                                                0));
    
                        Display_printf(
                                display,
                                0,
                                0,
                                "\n\r [MQTT Thread] CC3200 Publishes the following message");
                        Display_printf(display, 0, 0, "[MQTT Thread] Topic: %s",
                                       publish_topic);
                        Display_printf(display, 0, 0, "[MQTT Thread] Data: %s",
                                       msg);
                    }
                    else if (strncmp(tmpBuff, (const char*) topic[3],
                                     queueElemRecv.topLen) == 0)
                    {
                        struct controlMsg controlMsg;
    
                        controlMsg.threadID = 1;
                        controlMsg.msg = CONTROL_MSG_OTA_START;
    
                        if (!GET_STATUS_BIT(App_CB.status,
                                            AppStatusBits_OtaInProgress))
                        {
                            mq_send(App_CB.controlQueue, (char *) &controlMsg,
                                    sizeof(struct controlMsg), NULL);
    
                            SET_STATUS_BIT(App_CB.status,
                                           AppStatusBits_OtaInProgress);
                        }
                    }
    
                    free(queueElemRecv.msgPtr);
                    break;
    
                    /* On-board client disconnected from remote broker, only      */
                    /* local MQTT network will work                               */
                case LOCAL_CLIENT_DISCONNECTION:
                    Display_printf(display, 0, 0,
                                   "\t [MQTT Thread] On-board Client Disconnected");
    
                    if(GET_STATUS_BIT(App_CB.status, AppStatusBits_Connection) && GET_STATUS_BIT(App_CB.status, AppStatusBits_IpAcquired))
                    {
                        MQTTClient_disconnect(App_CB.mqttClientHandle);
                        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
                        mqttState = MQTT_CLIENT_CONNECTING_TO_BROKER;
                    }
                    else
                    {
                        Mqtt_ClientStop(1);
                        mqttState = MQTT_LIB_INITIALIZATION;
                    }
                    break;
    
                case THREAD_TERMINATE_REQ:
                    Display_printf(display, 0, 0,
                                   "[MQTT Thread] Terminating MQTT Client");
    
                    SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
                    Mqtt_ClientStop(1);
                    pthread_exit(0);
                    return NULL;
    
                default:
                    break;
                }
                break;
            }
            }
        }
    }
    
    //*****************************************************************************
    //
    //! MQTT_SendMsgToQueue - Utility function that receive msgQueue parameter and
    //! tries to push it the queue with minimal time for timeout of 0.
    //! If the queue isn't full the parameter will be stored and the function
    //! will return 0.
    //! If the queue is full and the timeout expired (because the timeout parameter
    //! is 0 it will expire immediately), the parameter is thrown away and the
    //! function will return -1 as an error for full queue.
    //!
    //! \param[in] struct msgQueue *queueElement
    //!
    //! \return 0 on success, -1 on error
    //
    //*****************************************************************************
    int32_t MQTT_SendMsgToQueue(struct msgQueue *queueElement)
    {
        struct timespec abstime = { 0 };
    
        clock_gettime(CLOCK_REALTIME, &abstime);
    
        if (App_CB.mqttQueue)
        {
            /* send message to the queue                                         */
            if (mq_timedsend(App_CB.mqttQueue, (char *) queueElement,
                             sizeof(struct msgQueue), 0, &abstime) == 0)
            {
                return 0;
            }
        }
        return -1;
    }
    
    int32_t MqttClient_start()
    {
        int32_t lRetVal = -1;
    
        int32_t threadArg = 100;
        pthread_attr_t pAttrs;
        struct sched_param priParam;
    
        MqttClientExample_params.clientId = ClientId;
        MqttClientExample_params.connParams = &Mqtt_ClientCtx;
        MqttClientExample_params.mqttMode31 = MQTT_3_1;
        MqttClientExample_params.blockingSend = true;
    
        /* Initialize MQTT client lib                                             */
        App_CB.mqttClientHandle = MQTTClient_create(MqttClientCallback,
                                                    &MqttClientExample_params);
        if (App_CB.mqttClientHandle == NULL)
        {
            /* Lib initialization failed */
            Display_printf(display, 0, 0,
                           "\t [MQTT Thread] Error - MQTT client handle is null");
            return -1;
        }
    
        /* Open Client Receive Thread start the receive task. Set priority and    */
        /* stack size attributes                                                  */
        pthread_attr_init(&pAttrs);
        priParam.sched_priority = 4;
        lRetVal = pthread_attr_setschedparam(&pAttrs, &priParam);
        lRetVal |= pthread_attr_setstacksize(&pAttrs, MQTT_CLIENT_RX_TASK_SIZE);
        lRetVal |= pthread_attr_setdetachstate(&pAttrs, PTHREAD_CREATE_DETACHED);
        lRetVal |= pthread_create(&g_rx_task_hndl, &pAttrs, MqttClientThread,
                                  (void *) &threadArg);
        if (lRetVal != 0)
        {
            Display_printf(display, 0, 0,
                           "[MQTT Thread] Client Thread create failed");
            return -1;
        }
    
        /* setting will parameters                                                */
        MQTTClient_set(App_CB.mqttClientHandle, MQTTClient_WILL_PARAM, &will_param,
                       sizeof(will_param));
        MQTTClient_set(App_CB.mqttClientHandle, MQTTClient_KEEPALIVE_TIME,
                       &mqttKeepAliveTimeout, sizeof(mqttKeepAliveTimeout));
    
        return 0;
    }
    
    //*****************************************************************************
    //!
    //! MQTT Client stop - Unsubscribe from the subscription topics and exit the
    //! MQTT client lib.
    //!
    //! \param  none
    //!
    //! \return None
    //!
    //*****************************************************************************
    
    void Mqtt_ClientStop(uint8_t disconnect)
    {
        uint32_t iCount;
    
        MQTTClient_UnsubscribeParams subscriptionInfo[SUBSCRIPTION_TOPIC_COUNT];
    
        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT; iCount++)
        {
            subscriptionInfo[iCount].topic = topic[iCount];
        }
    
        MQTTClient_unsubscribe(App_CB.mqttClientHandle, subscriptionInfo,
        SUBSCRIPTION_TOPIC_COUNT);
        for (iCount = 0; iCount < SUBSCRIPTION_TOPIC_COUNT; iCount++)
        {
            Display_printf(display, 0, 0,
                           "[MQTT Thread] Unsubscribed from the topic %s",
                           topic[iCount]);
        }
    
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttConnected);
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttInitialized);
    
        /* exiting the Client library                                             */
        MQTTClient_delete(App_CB.mqttClientHandle);
    
        Display_printf(display, 0, 0, "[MQTT Thread] MQTT Client Handle deleted");
    
        CLR_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
    }
    
    void *MqttClientThread(void * pvParameters)
    {
        struct msgQueue queueElement;
        struct msgQueue queueElemRecv;
    
        MQTTClient_run((MQTTClient_Handle) pvParameters);
    
        /* Check if MQTT thread is already being stopped */
        if(!GET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress))
        {
            SET_STATUS_BIT(App_CB.status, AppStatusBits_MqttStopInProgress);
    
            queueElement.event = LOCAL_CLIENT_DISCONNECTION;
            queueElement.msgPtr = NULL;
    
            /* write message indicating disconnect Broker message.                    */
            if (MQTT_SendMsgToQueue(&queueElement))
            {
                Display_printf(
                        display,
                        0,
                        0,
                        "\t [MQTT Thread] Queue is full, throw first msg and send the new one");
                mq_receive(App_CB.mqttQueue, (char*) &queueElemRecv,
                           sizeof(struct msgQueue), NULL);
                MQTT_SendMsgToQueue(&queueElement);
            }
        }
    
        pthread_exit(0);
    
        return NULL;
    }
    

    What error code is MqttClient_subscribe() returning?--> I don't know how to check it. can you guild me on how to do it, plesae?

    Thanks,

    Shing 

  • Hi Sarah,

    I added a print statement following the error message using %d for the int16_t return

    and it shows: 537051569

    Thanks,

    Shing 

  • Hi Shing,

    That will not work. You need to use a variable to capture the return value from the original call to MQTTClient_subscribe (like ret = ...) and print that variable instead.

    Best regards,

    Sarah

  • Hi Sarah,

    you mean i need to do something like:

    ret = MQTTClient_subscribe();

    then printf  ret in tera term?

    Thanks,

    Shing 

  • Hi Shing,

    Yes, but you need to call the full MQTTClient_subscribe command with the handle, subscription info, and topic count.

    Best regards,

    Sarah

  • Hi Sarah,

    it is -7

    thanks,

    Shing

  • Hi Shing,

    That (-7) error could be MQTT_PACKET_ERR_NOTCONN from the MQTT library. This is if the device is not getting a response from the server during subscribe.

    Could you try another Access Point or internet connection? Some company networks will block certain websites or ports.

    Best regards,

    Sarah

  • Hi Sarah,

    I'm using my home AP. I have two Ubiquiti (Model:UAP-AC-Lite) APs and tried all 2 and still getting the same error.  I have several google home products connected to the same wifi AP without any issue. 

    Could you recommend a way I can tackle this issue?

    Thanks,

    Shing 

  • Hi Shing,

    My attached code is working as expected. If this does not work for you, then you should look into testing on another setup.

    wifi_doorlock_CC3220S_LAUNCHXL_tirtos_ccs.zip

    wifi_doolock_CC3220S_UniFlash.zip

    Best regards,

    Sarah

  • Hi Sarah,

    Thank you for sharing your code. Unfortunately, I am still getting the same error (-7).

    So I am now looking at my AP settings. Could you recommend what AP settings I should be looking at?

    Thanks,

    Shing

  • Hi Sarah,

    Just want to verify if you use dummy-trust-cert-key from the playground when overwriting the .bin file  

    and use the following file name 

    Thanks,

    Shing 

  • Hi Shing,

    I used the dummy-root-ca-cert-key and dummy-root-ca-cert. You can also load the binary from the Simple page, and it will sign the image with this key automatically.

    Best regards,

    Sarah

  • Hi Sarah,

    Used the right keys, but still getting the same error. can you give me a pointer on what to look at in my AP setup?

    Thanks,

    Shing 

  • Hi Sarah,

    I notice the time printed in tera term is not my local time. 

    in the user guide

    it says "Without setting the RTC to the current network time, the connection to the server could
    fail or the device could be exposed to an insecure connection."

    Could this be the root cause of error -7?

    Thanks,

    Shing

  • Hi Shing,

    Yes this could cause issues - Can you verify if you are able to set time correctly? 

  • Hi Vincent,

    is there a tutorial that teaches me how to verify that? I cant find the setime() in wifi_doorlock_app.c 

    Thanks,

    Shing

  • You should have an set time function in the example - you can set a breakpoint there and see if this function is returning a 0 or error code afterwards.

  • Hi Vincent,

    I updated the setTime to my local time in Network_IF_SetTime() function in network_if.c.

    my time is set to my local time and is correct however, I am still getting the -7 error. Can you give me some pointers on how to resolve this? if it is like what Sarah says it's about my AP setting. can you give me some insight into what setting I should be looking at?

    Thanks,

    Shing 

  • Can you find which specific function is returning the -7 error? Also, have you tried other MQTT brokers?

  • Hi Vincent,

    it is MQTTClient_subscribe. do you have any recommend broker?

    per Sarah, "That (-7) error could be MQTT_PACKET_ERR_NOTCONN from the MQTT library. This is if the device is not getting a response from the server during subscribe."

    Thanks,

    Shing 

  • Hi Vincent,

    my first error was "SL_SOCKET_ASYNC_EVENT socket event 2, do restart". i searched on the form and found https://e2e.ti.com/support/wireless-connectivity/wi-fi-group/wifi/f/wi-fi-forum/598998/cc3200-launchxl-sock-event-handler-sock-event---unexpected-event-20x-during-https-get

    it recommended using the latest SDK, but I downloaded and used Sarah's code, so SDK should not be an issue, correct?

    Thanks,

    Shing 

  • This error typically happens when the server is not responding - I would try mosquitto broker or IBM. You could also sniffer the Wi-Fi traffic to be able to see if you are getting responses to the server. 

  • I am using mosquitto right now. 

    address: test.mosquitto.org

    port:8883

    i also use the .crt file from https://test.mosquitto.org/

  • Is it possible to capture a WI-Fi sniffer capture of this?

  • never done this before. working on it.

  • Hi Vincent,

    this is the wifi sniffer capture from starting to the -7 error :

    tera term display:

    Thanks,

    Shing

  • Hi Shing,

    Can you share the file .pcap capture?

    Thanks,

    VInce 

  • Thanks Shing, i will review and get back to you shortly.

  • Hi Shing,

    Looks like you captured this on a secure network (WPA/WPA2). Can you reconfigure the network to be open and recapture?

  • Hi Shing,

    Thanks. Looks like either your capture is missing data, or you are filtering this capture and i don't see any of the packets showing you connecting to an AP or trying to connect.

  • Hi Vincent,

    This time I verified myTidevBoard is connected to AP in tera term

    and in my network display

    Wifi capture - open network-08272021.zip

  • Hi Shing,

    Reviewing these captures and i still don't see our device connecting to the AP, or trying to send data. Can you use a different Access point or mobile hotspot to test?

  • Hi Vincent,

    I don't have another AP nor a hotspot available to me. I try the OOB demo again and everything is working fine. i can toggle D10 and the accelerometer are both working fine.

    it seems that there is no network issue with my AP system. Can it be that we are using a different protocol i in the door lock example? 

    Thanks,

    Shing 

  • Hi Shing,

    I am unsure the reason for this - From the logs you shared it appears the device is not connected to the AP. 

  • Hi Vincent,

    I tried agin

    it seems the board was trying to talk before -7 error.

    Wifi capture - open network-08302021.zip 

    if my board isn't talking, what would cause that?

    Thanks

    shing 

  • Hi Shing,

    Your captures still don't show connection to the network, but do show you are connected because you are sending those specific packets. Likely your sniffer setup is not correct and is missing packets.