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.

CC3230S: CC3230S

Part Number: CC3230S
Other Parts Discussed in Thread: UNIFLASH

sl_WlanPolicySet mode is se to configured to establish connection in Auto mode, but no connection is established
following functions are called on poweron
Status = sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_PERSISTENT, sizeof(_u8), (_u8*) (&persistent));
if( Status )
{
/* error */
}

Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,0,0,0),NULL,0);

  • Hi,

    Do you have stored connection profiles inside device?

    Jan

  • Hi,

    i had used the following API to store the profile

    Index = sl_WlanProfileAdd((signed char*)SsidName, ssidLen, MacAddr, &secParams, NULL, 15,0);
    Display_printf(display,0,0,"Index--%d",Index);

    Tanks & regards,

    Sandeep.M

  • Hi,

    Please make sure at device webpages that connection profiles was successfully stored if your code have capability for AP mode connections.

    I am not sure how your code is designed. Maybe you can start with network terminal example or WiFi provisioning example.

    btw... Do you restart NWP after storing your profile? Why you disabling settings persistence inside your code?

    Jan

  • Hi Sandeep,

    Do you have the device set in STA mode?

    Also, do you see any Wi-Fi events indicating connection attempts, or does it not appear to attempt to perform the automatic connection?

    If you scan for Wi-Fi APs with your CC3230, do you see your SSID listed in the scan results?

    Regards,

    Michael

  • Hi Michel,

    i am connecting directly to the AP by using the sl_WlanConnect() API

    i am able to Scan and can see the SSID listed in the scan results

    ssl_WlanPolicySet returns  0
    scan resultsCount retutns 1.

    ssid name displayed from sl_WlanGetNetworkList    ssid : sandeep.

    sl_WlanPolicyGet result

    pPolicy : 1.

    pVal : 113.

    pValLen : 1.

    retutn value : 0.

    sl_WlanProfileGet  results

    Name : sandeep.

    Name : 7.

    return value  : 2.

    Priority : 15.

    macid : 34:3:de:11:93:3c.

    Tanks & regards,

    Sandeep.M

  • Hi,

    API sl_WlanConnect() is a manual connection. In this case are connection profiles and connection policies not used.

    Jan

  • Hi Jan,

    i made settings to operate in STA mode 

    ssl_WlanPolicySet returns  0

    but scan resultsCount retutns : -2073.

    Thanks & regards,

    Sandeep.M

  • Hi,

    Meaning of error -2073 is SL_ERROR_WLAN_GET_NETWORK_LIST_EAGAIN.

    This error is returned with not properly set scan policy or you call API too early and WLAN scan values are not ready yet.

    Jan

  • hi Jan,

    i added sleep statement it working fine, but not able join the network in auto mode.

    is Auto mode enabled difficultly or we need to configure auto mode?

    Thanks & regards,

    Sandeep.M

  • hi Jan,

    Status = sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
    Display_printf(display, 0, 0, "pPolicy : %d.\r\n", pPolicy);
    Display_printf(display, 0, 0, "pVal : %d.\r\n", pVal);
    Display_printf(display, 0, 0, "pValLen : %d.\r\n", pValLen);
    Display_printf(display, 0, 0, "Status : %d.\r\n", Status);
    if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
    {
    printf("Connection Policy is set to auto");
    }

    pPolicy : 1.

    pVal : 220.

    pValLen : 1.

    Status : 0.

    what does thes values mean are they correct?

    Thanks & regards,

    Sandeep.M

  • Hi,

    Usage of auto connection mode with connection profiles is pretty simple and even usage is easier than usage of manual connection. I am not sure what you did wrong.

    You need to:

    • set connection policy
    • set connection profile
    • set STA mode (if this is not already done)
    • after NWP restart you will be connected into network...

    Jan

  • Hi Jan,

    i have written code as below correct me if any changes requires

    status = sl_Start(NULL,NULL,NULL);
    Display_printf(display,0,0," Role-- = %d",status);
    if (ROLE_STA != status)
    {
    Display_printf(display,0,0,"failed ");
    //Role Error
    }
    status = sl_WlanSetMode(ROLE_STA);
    Display_printf(display,0,0," sl_WlanSetMode-- = %d",status);
    status = sl_Stop(SL_STOP_TIMEOUT);

    /* Host driver starts the network processor */
    if (sl_Start(NULL, NULL, NULL) < 0) {
    /* Error: Could not initialize WiFi */
    while (1);
    }

    status = sl_WlanPolicySet(SL_WLAN_POLICY_SCAN, SL_WLAN_SCAN_POLICY(1,1),
    (_u8*)&intervalInSeconds,sizeof(intervalInSeconds));
    Display_printf(display,0,0," sl_WlanPolicySet--%d",status);
    if( status )
    {
    /* error */
    }
    sleep(5);

    _i16 resultsCount = sl_WlanGetNetworkList(0,30,&netEntries[0]);
    Display_printf(display, 0, 0, "resultsCount : %d.\r\n", resultsCount);

    for(i =0;i<resultsCount;i++)
    {
    Display_printf(display, 0, 0, "ssid : %s.\r\n", netEntries[0].Ssid);
    }
    // Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,1,0,1),NULL,0);
    Status = sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
    Display_printf(display, 0, 0, "pPolicy : %d.\r\n", pPolicy);
    Display_printf(display, 0, 0, "pVal : %d.\r\n", pVal);
    Display_printf(display, 0, 0, "pValLen : %d.\r\n", pValLen);

    if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
    {
    printf("Connection Policy is set to auto");
    }
    /* secParams.Key = (signed char *)SECURITY_KEY;
    secParams.KeyLen = strlen((const char *)secParams.Key);
    secParams.Type = SECURITY_TYPE;*/
    //Index = sl_WlanProfileAdd((signed char*)SSID, 7, MacAddr1, &secParams, NULL, 15,0);
    //Display_printf(display,0,0,"Index--%d",Index);

    Status = sl_WlanProfileGet(Index, Name, &NameLength, MacAddr, &SecParams, &SecExtParams,&Priority);

    Display_printf(display, 0, 0, "Name : %s.\r\n", Name);
    Display_printf(display, 0, 0, "Name : %d.\r\n", NameLength);
    Display_printf(display, 0, 0, "Status : %d.\r\n", Status);
    Display_printf(display, 0, 0, "Priority : %d.\r\n", Priority);
    sprintf(mac_str,"%0x:%0x:%0x:%0x:%0x:%0x",MacAddr[0],MacAddr[1],MacAddr[2],MacAddr[3],MacAddr[4],MacAddr[5]);
    Display_printf(display, 0, 0, "macid : %s.\r\n", mac_str);
    if( Status )
    {
    /* error */
    }

    Regards,

    Sandeep.M

  • Hi,

    I am not sure what you want to achieve by that code. Your code do following things:

    • Set mode to STA
    • Set WLAN scan policy
    • List neighbours WLANs
    • Set connection policy
    • Read content of connection profile

    btw ... if you want connection policy can be set via Uniflash software as well.

    Jan

  • hi Jan,

    i am new to this, and its there any problem in my code please suggest 

    please let me know the flow

    i have already stored my profile.

    is it required every time to add profile ?

    and then call auto mode ?

    Regards,

    Sandeep.M

  • in my main function i am calling the following API

    Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,0,0,0),NULL,0);

  • Hi,

    I don't see any issue inside your code.

    Connection policy, scan policy and connection profiles are persistent unless you not disable this feature. That means you don't need to save them again once you save settings into sFlash using sl_ API. Once settings is save in sFlash and you start/restart NWP, device is automagically connected into network according set profiles.

    I am not sure why you not able accomplish this. Do you have disabled flash settings persistency by SL_DEVICE_GENERAL_PERSISTENT?

    Jan

  • Hi Jan,

    this is what i am doing 

    Status = sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_PERSISTENT, sizeof(_u8), (_u8*) (&persistent));
    if( Status )
    {
    /* error */
    }

    Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,0,0,0),NULL,0);
    Display_printf(display, 0, 0, "Status_policy : %d.\r\n", Status);

    status = sl_Start(NULL,NULL,NULL);
    Display_printf(display,0,0," Role-- = %d",status);
    if (ROLE_STA != status)
    {
    Display_printf(display,0,0,"failed ");
    //Role Error
    }
    status = sl_WlanSetMode(ROLE_STA);
    Display_printf(display,0,0," sl_WlanSetMode-- = %d",status);
    status = sl_Stop(SL_STOP_TIMEOUT);

    /* Host driver starts the network processor */
    if (sl_Start(NULL, NULL, NULL) < 0) {
    /* Error: Could not initialize WiFi */
    while (1);
    }

    status = sl_WlanPolicySet(SL_WLAN_POLICY_SCAN, SL_WLAN_SCAN_POLICY(1,1),
    (_u8*)&intervalInSeconds,sizeof(intervalInSeconds));
    Display_printf(display,0,0," sl_WlanPolicySet--%d",status);
    if( status )
    {
    /* error */
    }
    sleep(5);

    _i16 resultsCount = sl_WlanGetNetworkList(0,30,&netEntries[0]);
    Display_printf(display, 0, 0, "resultsCount : %d.\r\n", resultsCount);

    for(i =0;i<resultsCount;i++)
    {
    Display_printf(display, 0, 0, "ssid : %s.\r\n", netEntries[0].Ssid);
    }
    // Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,1,0,1),NULL,0);
    Status = sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
    Display_printf(display, 0, 0, "pPolicy : %d.\r\n", pPolicy);
    Display_printf(display, 0, 0, "pVal : %d.\r\n", pVal);
    Display_printf(display, 0, 0, "pValLen : %d.\r\n", pValLen);

    if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
    {
    printf("Connection Policy is set to auto");
    }
    /* secParams.Key = (signed char *)SECURITY_KEY;
    secParams.KeyLen = strlen((const char *)secParams.Key);
    secParams.Type = SECURITY_TYPE;*/
    //Index = sl_WlanProfileAdd((signed char*)SSID, 7, MacAddr1, &secParams, NULL, 15,0);
    //Display_printf(display,0,0,"Index--%d",Index);

    Status = sl_WlanProfileGet(Index, Name, &NameLength, MacAddr, &SecParams, &SecExtParams,&Priority);

    Display_printf(display, 0, 0, "Name : %s.\r\n", Name);
    Display_printf(display, 0, 0, "Name : %d.\r\n", NameLength);
    Display_printf(display, 0, 0, "Status : %d.\r\n", Status);
    Display_printf(display, 0, 0, "Priority : %d.\r\n", Priority);
    sprintf(mac_str,"%0x:%0x:%0x:%0x:%0x:%0x",MacAddr[0],MacAddr[1],MacAddr[2],MacAddr[3],MacAddr[4],MacAddr[5]);
    Display_printf(display, 0, 0, "macid : %s.\r\n", mac_str);
    if( Status )
    {
    /* error */
    }

    /* if (strlen(Name) != 0) {
    secParams.Key = (signed char *)SECURITY_KEY;
    secParams.KeyLen = strlen((const char *)secParams.Key);
    secParams.Type = SECURITY_TYPE;
    Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n", secParams.KeyLen);
    ret = sl_WlanConnect((signed char*)Name, strlen((const char*)Name),
    NULL, &secParams, NULL);
    }
    */
    /* if (strlen(SSID) != 0) {
    secParams.Key = (signed char *)SECURITY_KEY;
    secParams.KeyLen = strlen((const char *)secParams.Key);
    secParams.Type = SECURITY_TYPE;
    Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n", secParams.KeyLen);
    ret = sl_WlanConnect((signed char*)SSID, strlen((const char*)SSID),
    NULL, &secParams, NULL);
    }*/
    // Status = sl_WlanProfileDel(SL_WLAN_DEL_ALL_PROFILES);

    following are the display i am gettng on terminal

    Role-- = 0
    sl_WlanSetMode-- = 0
    sl_WlanPolicySet--0
    resultsCount : 1.

    ssid : sandeep.

    pPolicy : 1.

    pVal : 255.

    pValLen : 1.

    Name : sandeep.

    Name : 7.

    Status : 2.

    Priority : 15.

    macid : 34:3:de:11:93:3c.

    please suggest 

    Thanks & regards,

    Sandeep.M

  • Hi,

    How is set your persistent variable? In case is variable set to 0, system persistent configuration is disabled. All configuration done before NWP restart will be lost.

    Jan

  •  _u8 persistent = 1;

    Status = sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_PERSISTENT, sizeof(_u8), (_u8*) (&persistent));
    if( Status )
    {
    /* error */
    }

  • Hi,

    OK, in this case system persistent configuration is enabled and that line has no effect.

    I am not sure what can be reason of your issue. Please wait for additional comment from Michael. Maybe you can try to use Auto + Fast connect (1,1,0,0).

    Jan

  • i cant share the code in forum any other means?

  • Hi,

    You can use code syntaxhighlighter

    your code

    or you can insert file.

    Jan

  • 3704.network.c
    /*
     * Copyright (c) 2017-2019, 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.
     */
    
    #include <stdbool.h>
    #include <stdint.h>
    
    #include <ti/net/slnet.h>
    #include <ti/drivers/SPI.h>
    
    #include <ti/drivers/GPIO.h>
    #include <ti/drivers/net/wifi/simplelink.h>
    #include <ti/drivers/net/wifi/slnetifwifi.h>
    #include <ti/drivers/net/wifi/netapp.h>
    #include <ti/drivers/net/wifi/wlan.h>
    #include <ti/display/Display.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include <semaphore.h>
    #include <unistd.h>
    
    #include "ti_drivers_config.h"
    #include "pthread.h"
    /////////
    #include <string.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include "wificonfig.h"
    #include "mcu.h"
    
    /* Provisioning inactivity timeout in seconds */
    #define PROV_INACTIVITY_TIMEOUT (600)
    #define APPLICATION_NAME                      ("TCP Echo")
    #define APPLICATION_VERSION                   ("1.0.0.0")
    #define DEVICE_ERROR                          ("Device error, please refer \"DEVICE ERRORS CODES\" section in errors.h")
    #define WLAN_ERROR                            ("WLAN error, please refer \"WLAN ERRORS CODES\" section in errors.h")
    #define SL_STOP_TIMEOUT                       (200)
    
    #define TCPPORT                               (2020)
    //#define MESSAGE_LENGTH                        (4)
    #define SPAWN_TASK_PRIORITY                   (9)
    #define TASK_STACK_SIZE                       (2048)
    #define SLNET_IF_WIFI_PRIO                    (5)
    #define SLNET_IF_WIFI_NAME                    "CC32xx"
    
    //#define SSID_NAME                             "TEV_AP"                  /* AP SSID */
    #define SECURITY_TYPE                         SL_WLAN_SEC_TYPE_WPA_WPA2 /* Security type could be SL_WLAN_SEC_TYPE_OPEN */
    //#define SECURITY_KEY                          "raspberry"                /* Password of the secured AP */
    /*
    #define SEND_CIPHER                            "0000"
    #define VERIFY_IDENTITY                        "0001"
    #define RECEIVE_DATA                           "0010"
    #define START_STREAM                           "0011"
    #define STOP_STREAM                            "0100"
    #define STOP                                   "1111"
    
    #define ACK                                    "ACK_"
    #define nack                                   "NACK"*/
    char wsdSsidName[33] = "TEV_Honeywell";
    char SsidName[33];
    char psk[33];
    int8_t SECURITY_LEN;
    
    uint8_t ssidLen;
    typedef struct TaskArgs {
        void (*arg0)();
        uintptr_t arg1;
        uintptr_t arg2;
    } TaskArgs;
    
    
    pthread_t tcpThread = (pthread_t)NULL;
    pthread_t spawn_thread = (pthread_t)NULL;
    pthread_t tcpworker_thread = (pthread_t)NULL;
    int32_t             mode;
    Display_Handle display;
    char *AES_key = "5RqzBtDpA6SJ2uAliYGqhdO6DgDT98bdeqmfHJQUtrk=";
    int8_t       COUNT = 0;
    CryptoCC32XX_Handle      cryptoHandle;
    CryptoCC32XX_EncryptMethod config;
    int32_t CONFIG_CRYPTO_0;
    CryptoCC32XX_EncryptParams          AESparams;
     char               plainData[16] = "whatsoever123456";
     int                plainDataLen = sizeof(plainData);
     char               dec_data[1024] ;
     int               dec_DataLen ;
     char               cipherData[1024] = "gAAAAABf4H8Cyeqnpkg9_mxEIP1Zy3lg0ozXSUxpmDLPK4WiMqwrRfL9_rMnBsQLzF2ZCJyEWpGbfKYQEaJaiMkfQLjv9DI6iiiUFw1ue9YgK5oquO37Giljuo4E_qplvG8yefJXkgz6";
     int                cipherDataLen = 140;
    char                chiper_length[256] = "0140";
    
     char SEND_CIPHER[256]  ="0000";
     char VERIFY_IDENTITY[256]  ="0001";
     char RECEIVE_DATA[256]  ="0010";
     char START_STREAM[256]  ="0011";
     char STOP_STREAM[256]  ="0100";
     char STOP[256]  ="1111";
     char ACK[256]  = "ACK_";
     char NACK[256]  ="NACK";
     int8_t length_received[4];
     int8_t MESSAGE_LENGTH = 4;
    
    int ipointerToInitVector;
    extern void tcpHandler(uint32_t arg0, uint32_t arg1);
    extern void tcpWorker(uint32_t arg0, uint32_t arg1);
    //extern int32_t ti_net_SlNet_initConfig();
    void tcpConnector();
    void Connect(void);
    static uint32_t deviceConnected = false;
    static uint32_t ipAcquired = false;
    
    int32_t             mode;
    extern Display_Handle display;
    
    
    static sem_t sem;
    
    extern void startSNTP(void);
    
    static void initWiFi();
    
    
    void printError(char *errString, int code)
    {
        Display_printf(display, 0, 0, "Error! code = %d, Description = %s\n", code,
                errString);
        while(1);
    }
    
    /*
     *  ======== Network_init =======
     */
    void Network_init()
    {
        if (sem_init(&sem, 0, 0) != 0) {
            /* Error: sem_init failed */
            while (1);
        }
    }
    
    /*
     *  ======== Network_startup =======
     */
    void Network_startup()
    {
        int32_t status;
    
    
        /* Connect to the Access Point */
        initWiFi();
    
        /* Wait for the network stack to initialize and acquire an IP address */
        sem_wait(&sem);
    
        /* initialize SlNet interface(s) */
        status = ti_net_SlNet_initConfig();
        if (status < 0) {
            // ti_net_SlNet_initConfig failed
            Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
            while (1);
        }
    
        /* Turn LED OFF. It will be used as a connection indicator */
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
    
        /* Use SNTP to get the current time, as needed for SSL authentication */
        startSNTP();
     //  provisioningFxn();
      // sem_wait(&sem);
      //  startSNTP();
    
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
    }
    
    /*
     *  ======== Network_exit =======
     */
    void Network_exit()
    {
    }
    
    /*
     *
     *  SimpleLink Asynchronous Event Handlers -- Start
     *
     */
    
    /*
     *  ======== SimpleLinkHttpServerEventHandler ========
     */
    void SimpleLinkHttpServerEventHandler(
            SlNetAppHttpServerEvent_t *pSlHttpServerEvent,
            SlNetAppHttpServerResponse_t *pSlHttpServerResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestEventHandler ========
     */
    void SimpleLinkNetAppRequestEventHandler(SlNetAppRequest_t *pNetAppRequest,
            SlNetAppResponse_t *pNetAppResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestMemFreeEventHandler ========
     */
    void SimpleLinkNetAppRequestMemFreeEventHandler(uint8_t *buffer)
    {
    }
    
    /*
     *  ======== SimpleLinkWlanEventHandler ========
     *  SimpleLink Host Driver callback for handling WLAN connection or
     *  disconnection events.
     */
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        switch (pWlanEvent->Id) {
            case SL_WLAN_EVENT_CONNECT:
                deviceConnected = true;
                break;
    
            case SL_WLAN_EVENT_DISCONNECT:
                deviceConnected = false;
                break;
    
            case SL_WLAN_EVENT_PROVISIONING_STATUS:
                switch (pWlanEvent->Data.ProvisioningStatus.ProvisioningStatus) {
                    case SL_WLAN_PROVISIONING_CONFIRMATION_WLAN_CONNECT:
                        deviceConnected = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_CONFIRMATION_IP_ACQUIRED:
                        ipAcquired = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_STOPPED:
                        if (pWlanEvent->Data.ProvisioningStatus.Role == ROLE_STA) {
                            if (pWlanEvent->Data.ProvisioningStatus.WlanStatus ==
                                    SL_WLAN_STATUS_CONNECTED) {
                                /* The WiFi stack is ready and has an IP address */
                                provisioning = false;
                                sem_post(&sem);
                            }
                        }
    
                        break;
    
                    default:
                        break;
                }
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkFatalErrorEventHandler ========
     *  This function handles fatal errors
     *
     *  \param[in]  slFatalErrorEvent - Pointer to the fatal error event info
     *
     *  \return     None
     */
    void SimpleLinkFatalErrorEventHandler(SlDeviceFatal_t *slFatalErrorEvent)
    {
        switch (slFatalErrorEvent->Id) {
            case SL_DEVICE_EVENT_FATAL_DEVICE_ABORT:
                /* FATAL ERROR: Abort NWP event detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_DRIVER_ABORT:
                /* FATAL ERROR: Driver Abort detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_NO_CMD_ACK:
                /* FATAL ERROR: No Cmd Ack detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_SYNC_LOSS:
                /* FATAL ERROR: Sync loss detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_CMD_TIMEOUT:
                /* FATAL ERROR: Async event timeout detected */
                while (1);
    
            default:
                /* FATAL ERROR: Unspecified error detected */
                while (1);
        }
    }
    
    /*
     *  ======== SimpleLinkNetAppEventHandler ========
     *  SimpleLink Host Driver callback for asynchoronous IP address events.
     */
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if (pNetAppEvent == NULL) {
            return;
        }
    
        switch (pNetAppEvent->Id) {
            case SL_NETAPP_EVENT_IPV4_ACQUIRED:
            case SL_NETAPP_EVENT_IPV6_ACQUIRED:
                ipAcquired = true;
    
                /*  Signal that the WiFi stack is ready and has an IP address */
                sem_post(&sem);
    
                break;
    
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkSockEventHandler ========
     */
    void SimpleLinkSockEventHandler(SlSockEvent_t *pArgs)
    {
    }
    
    /*
     *  ======== SimpleLinkGeneralEventHandler ========
     */
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *sockEvent)
    {
    }
    
    /*
     *  ======== provisioningFxn ========
     */
    void provisioningFxn()
    {
        int32_t status;
        pthread_attr_t      pAttrs_spawn;
            struct sched_param  priParam;
            Display_printf(display, 0, 0, "entered provisioningFxn");
       // sl_NetAppStart(SL_NETAPP_HTTP_SERVER_ID);
            pthread_attr_init(&pAttrs_spawn);
               priParam.sched_priority = SPAWN_TASK_PRIORITY;
               status = pthread_attr_setschedparam(&pAttrs_spawn, &priParam);
               status |= pthread_attr_setstacksize(&pAttrs_spawn, TASK_STACK_SIZE);
    
               status = pthread_create(&spawn_thread, &pAttrs_spawn, sl_Task, NULL);
    
    
               if(status)
               {
                   printError("Task create failed", status);
               }
    
        /*mode = sl_Stop(SL_STOP_TIMEOUT);
           if (mode < 0)
           {
               Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
           }
    
        mode = sl_Start(0, 0, 0);
            if (mode < 0)
             {
                Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
             }
    */       if(1)
           {
               /* Set NWP role as STA */
    
               mode = sl_WlanSetMode(ROLE_AP);
               sl_WlanSet(SL_WLAN_CFG_AP_ID, SL_WLAN_AP_OPT_SSID, strlen(wsdSsidName),(const uint8_t *) wsdSsidName);
    
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
               }
    
               /* For changes to take affect, we restart the NWP */
               status = sl_Stop(SL_STOP_TIMEOUT);
               if (status < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
               }
    
               mode = sl_Start(0, 0, 0);
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
               }
           }
    
           if(mode != ROLE_AP)
           {
               printError("Failed to configure device to it's default state", mode);
           }
    
    
           tcpConnector();
    }
    
    /*
     *  ======== wlanConnect =======
     *  Secure connection parameters
     */
    static int wlanConnect()
    {
        SlWlanSecParams_t SecParams = {0};
        SlWlanSecParams_t secParams = {0};
        int ret = 0;
        SlNetCfgIpV4Args_t ipV4;
               uint16_t           len = sizeof(ipV4);
               uint16_t           dhcpIsOn;
               _u8 MacAddr1[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
               _i16 index, Status;
               signed char Name[32];
               _i16 NameLength;
               unsigned char MacAddr[6];
    
               SlWlanGetSecParamsExt_t SecExtParams;
               _u32 Priority,i;
               _i16 Index =0;
               char mac_str[10];
               _u8 pPolicy;
               _u8 pVal;
               _u8 pValLen;
               SlWlanNetworkEntry_t netEntries[30];
                          _i16 resultsCount = sl_WlanGetNetworkList(0,30,&netEntries[0]);
                          Display_printf(display, 0, 0, "resultsCount : %d.\r\n",  resultsCount);
    
                          for(i =0;i<resultsCount;i++)
                          {
                              Display_printf(display, 0, 0, "ssid : %s.\r\n",  netEntries[0].Ssid);
                          }
             // Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,1,0,1),NULL,0);
               Status =  sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
                   Display_printf(display, 0, 0, "pPolicy : %d.\r\n",  pPolicy);
                   Display_printf(display, 0, 0, "pVal : %d.\r\n",  pVal);
                   Display_printf(display, 0, 0, "pValLen : %d.\r\n",  pValLen);
    
                   if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
                   {
                       printf("Connection Policy is set to auto");
                   }
              /* secParams.Key = (signed char *)SECURITY_KEY;
                         secParams.KeyLen = strlen((const char *)secParams.Key);
                         secParams.Type = SECURITY_TYPE;*/
                         //Index = sl_WlanProfileAdd((signed char*)SSID,  7, MacAddr1, &secParams, NULL, 15,0);
                  //Display_printf(display,0,0,"Index--%d",Index);
    
               Status = sl_WlanProfileGet(Index, Name, &NameLength, MacAddr, &SecParams, &SecExtParams,&Priority);
    
               Display_printf(display, 0, 0, "Name : %s.\r\n",  Name);
               Display_printf(display, 0, 0, "Name : %d.\r\n",  NameLength);
               Display_printf(display, 0, 0, "Status : %d.\r\n",  Status);
               Display_printf(display, 0, 0, "Priority : %d.\r\n", Priority);
               sprintf(mac_str,"%0x:%0x:%0x:%0x:%0x:%0x",MacAddr[0],MacAddr[1],MacAddr[2],MacAddr[3],MacAddr[4],MacAddr[5]);
               Display_printf(display, 0, 0, "macid : %s.\r\n", mac_str);
               if( Status )
               {
               /* error */
               }
    
                 /*  if (strlen(Name) != 0) {
                       secParams.Key = (signed char *)SECURITY_KEY;
                               secParams.KeyLen = strlen((const char *)secParams.Key);
                               secParams.Type = SECURITY_TYPE;
                      Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                      ret = sl_WlanConnect((signed char*)Name, strlen((const char*)Name),
                              NULL, &secParams, NULL);
                  }
    */
              /*     if (strlen(SSID) != 0) {
            secParams.Key = (signed char *)SECURITY_KEY;
            secParams.KeyLen = strlen((const char *)secParams.Key);
            secParams.Type = SECURITY_TYPE;
            Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
            ret = sl_WlanConnect((signed char*)SSID, strlen((const char*)SSID),
                    NULL, &secParams, NULL);
        }*/
                 //  Status = sl_WlanProfileDel(SL_WLAN_DEL_ALL_PROFILES);
    
        return (ret);
    }
    
    /*
     *  ======== initWiFi =======
     *  Start the NWP and connect to AP
     */
    static void initWiFi()
    {
        int32_t status;
        uint32_t currButton;
        uint32_t prevButton = 0;
        _u32 intervalInSeconds = 20;
      /*  status = sl_WifiConfig();
        if (status < 0) {
             sl_WifiConfig failed
            while (1);
        }
    */
    
        /* Set connection variables to initial values */
        deviceConnected = false;
        ipAcquired = false;
        provisioning = false;
    
        status = sl_Start(NULL,NULL,NULL);
            Display_printf(display,0,0," Role-- = %d",status);
               if (ROLE_STA != status)
               {
                   Display_printf(display,0,0,"failed ");
                 //Role Error
               }
            status = sl_WlanSetMode(ROLE_STA);
            Display_printf(display,0,0," sl_WlanSetMode-- = %d",status);
            status = sl_Stop(SL_STOP_TIMEOUT);
    
        /* Host driver starts the network processor */
        if (sl_Start(NULL, NULL, NULL) < 0) {
            /* Error: Could not initialize WiFi */
            while (1);
        }
    
        status = sl_WlanPolicySet(SL_WLAN_POLICY_SCAN, SL_WLAN_SCAN_POLICY(1,1),
                 (_u8*)&intervalInSeconds,sizeof(intervalInSeconds));
                 Display_printf(display,0,0," sl_WlanPolicySet--%d",status);
                 if( status )
                 {
                  /* error */
                 }
                 sleep(5);
    
        if (wlanConnect() < 0) {
            /* Error: Could not connect to WiFi AP */
            while (1);
        }
    
        /*
         * Wait for the WiFi to connect to an AP. If a profile for the AP in
         * use has not been stored yet, press Board_GPIO_BUTTON0 to start
         * provisioning.
         */
      /*  while ((deviceConnected != true) || (ipAcquired != true) ||
                (provisioning == true)) {
    
             *  Start provisioning if a button is pressed. This could be done with
             *  GPIO interrupts, but for simplicity polling is used to check the
             *  button.
    
         //   currButton = GPIO_read(CONFIG_GPIO_BUTTON_0);
         //   if ((currButton == 0) && (prevButton != 0))
                if (wifiModeChange == TRUE)
            {
                provisioningFxn();
            }
            prevButton = currButton;
            usleep(50000);
        }*/
    }
    
    
    
    void tcpConnector()
    {
        int                 clientfd;
        int                 server;
        struct sockaddr_in  localAddr;
        int32_t             status = 0;
        struct sockaddr_in  clientAddr;
        socklen_t           addrlen = sizeof(clientAddr);
        char                send_buffer[256];
        int                 bytesSent;
        int16_t           bytesRcvd;
        int8_t            rxdata;
        char              temp_buffer[4];
    int i;
    Display_printf(display, 0, 0, "entered tcpconnect");
    
     /*  status = ti_net_SlNet_initConfig();
        if(0 != status)
        {
              Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
        }*/
    
        server = socket(AF_INET, SOCK_STREAM, 0);
        if (server == -1)
        {
                Display_printf(display, 0, 0, "tcpHandler: socket failed\n");
            }
    
        memset(&localAddr, 0, sizeof(localAddr));
        localAddr.sin_family = AF_INET;
        localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        localAddr.sin_port = htons(TCPPORT);
        status = bind(server, (struct sockaddr *)&localAddr, sizeof(localAddr));
        if (status == -1)
        {
            Display_printf(display, 0, 0, "tcpHandler: bind failed\n");
        }
    
        status = listen(server, 3);
        if (status == -1) {
            Display_printf(display, 0, 0, "tcpHandler: listen failed\n");
        }
    
    
        if ((clientfd = accept(server, (struct sockaddr *)&clientAddr, &addrlen)) != -1)
        {
            Display_printf(display, 0, 0,
                           "clientAddr = %x\n", clientAddr);
            Display_printf(display, 0, 0,
                    "tcpHandler: Creating thread clientfd = %x\n", clientfd);
    
    //        bytesSent = send(clientfd, send_buffer, 9, 0);
    //        Display_printf(display,0,0,"sent bytes--%d",bytesSent);
    //        Display_printf(display,0,0,"sent bytes--%s",send_buffer);
    //        if (bytesSent < 0 ) {
    //            Display_printf(display, 0, 0, "send failed.\n");
    //        }
    
            while ((bytesRcvd = recv(clientfd, send_buffer, MESSAGE_LENGTH, 0)) > 0)
            {
                Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
                COUNT++;
                Display_printf(display,0,0,"COUNT =%d",COUNT);
                memcpy(temp_buffer,send_buffer,4);
                rxdata = atoi(temp_buffer);
                Display_printf(display,0,0,"rxdata =%d",rxdata);
                if(COUNT == 1 && rxdata == 0)  //Request to send cipher text
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, chiper_length, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 2)//ack received
                {
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, cipherData, cipherDataLen, 0);
                 }
                else if(COUNT == 3)// ack received  no reply
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                }
    
                else if(COUNT == 4 && rxdata == 1)// Request to verify the deciphered text
                 {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                 }
                else if(COUNT == 5)// deciphered length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 6)// deciphered message
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    MESSAGE_LENGTH = 4;
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
    
                }
                else if(COUNT == 7 && rxdata == 10)// Request to receive network credentials
                {
                 memcpy(send_buffer,0,sizeof(send_buffer));
                 MESSAGE_LENGTH = 4;
                 bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 8)//SSID LENGTH
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
    
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                    ssidLen = MESSAGE_LENGTH;
    
                }
                else if(COUNT == 9)//SSID
                {
    
                   memcpy(SsidName,send_buffer,MESSAGE_LENGTH);
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, ACK, 4, 0);
                   MESSAGE_LENGTH = 4;
                 }
                else if(COUNT == 10)//psk length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                    SECURITY_LEN = MESSAGE_LENGTH;
                }
                else if(COUNT == 11) // psk
                {
                    memcpy(psk,send_buffer,MESSAGE_LENGTH);
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                }
                else if(COUNT == 12) // device_name_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                 }
                else if(COUNT == 13) // device_name
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                      bytesSent = send(clientfd, ACK, 4, 0);
                      MESSAGE_LENGTH = 4;
    
                }
                else if(COUNT == 14)//location_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 15)//loction_id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 16)//location name length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 17)//location_name
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT ==18)//org id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT ==19)//org id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 20)//logical devie id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 21)//logical devie id
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                     bytesSent = send(clientfd, ACK, 4, 0);
                     MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 22)//
                {
    
                    break;
                 }
    
    
    
    
    
    
            }
            Display_printf(display,0,0,"bytesRcvd-%d",bytesRcvd);
            Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
    
    
          }
    
        Display_printf(display,0,0,"after accept---");
        status =  sl_WlanDisconnect();
        Display_printf(display,0,0,"sl_WlanDisconnect status--%d",status);
        Connect();
    
        provisioning = FALSE;
    
    }
    
    
    
    void Connect(void)
    {
        SlWlanSecParams_t   secParams = {0};
        SlWlanSecParams_t   SecParams = {0};
        int16_t ret = 0;
        int16_t status;
        _i16 index, Status;
        _u8 MacAddr[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
        _u8 MacAddr1[10];
        char SsidName1[33];
        _u32 Priority;
        _i16 NameLength;
        SlNetCfgIpV4Args_t ipV4;
            uint16_t           len = sizeof(ipV4);
            uint16_t           dhcpIsOn;
            uint16_t           Index;
            SlWlanGetSecParamsExt_t SecExtParams;
            Display_printf(display,0,0,"entered connet func--%");
        mode = sl_WlanSetMode(ROLE_STA);
        Display_printf(display,0,0,"entered sta mode--%");
    
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
                   }
    
                   /* For changes to take affect, we restart the NWP */
                   status = sl_Stop(SL_STOP_TIMEOUT);
                   if (status < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
                   }
    
                   mode = sl_Start(0, 0, 0);
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
                   }
    
    
               if(mode != ROLE_STA)
               {
                   printError("Failed to configure device to it's default state", mode);
               }
    
               secParams.Key = (signed char *)psk;
               secParams.KeyLen = strlen((const char *)secParams.Key);
               secParams.Type = SECURITY_TYPE;
               Display_printf(display,0,0,"entered connet fun after apmodec--%");
        Index = sl_WlanProfileAdd((signed char*)SsidName, ssidLen, MacAddr, &secParams, NULL, 15,0);
        Display_printf(display,0,0,"Index--%d",Index);
      /*  Status = sl_WlanProfileGet(Index, (signed char*)SsidName1, &NameLength, MacAddr1, &SecParams, &SecExtParams, &Priority);
        Display_printf(display, 0, 0, "SsidName1  : %s.\r\n",SsidName1);
        Display_printf(display, 0, 0, "MacAddr1 : %s.\r\n",MacAddr1);
        Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
        Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", SecParams.Key);
        Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  SecParams.KeyLen);
        Display_printf(display, 0, 0, "SECURITY_LEN : %d.\r\n",  SECURITY_LEN);
        Display_printf(display, 0, 0, "ssidLen : %d.\r\n",  ssidLen);*/
    
       /* secParams.Key = (signed char *)psk;
                secParams.KeyLen = strlen((const char *)secParams.Key);
                secParams.Type = SECURITY_TYPE;*/
                Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
                    Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", secParams.Key);
                    Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                ret = sl_WlanConnect((signed char*)SsidName, strlen((const char*)SsidName),
                        NULL, &secParams, NULL);
        if (ret)
        {
    
            Display_printf(display,0,0,"Connection failed--%d",ret);
        }
    
    //FOR TESTING
    
        sl_NetCfgGet(SL_NETCFG_IPV4_STA_ADDR_MODE, &dhcpIsOn, &len,
                   (unsigned char *)&ipV4);
           Display_printf(display, 0, 0,
                   "CC32XX has connected to AP and acquired an IP address.\n");
           Display_printf(display, 0, 0, "IP Address: %ld.%ld.%ld.%ld\n",
                   SL_IPV4_BYTE(ipV4.Ip, 3), SL_IPV4_BYTE(ipV4.Ip, 2),
                   SL_IPV4_BYTE(ipV4.Ip, 1), SL_IPV4_BYTE(ipV4.Ip, 0));
    
    }
    

  • 6177.network.c
    /*
     * Copyright (c) 2017-2019, 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.
     */
    
    #include <stdbool.h>
    #include <stdint.h>
    
    #include <ti/net/slnet.h>
    #include <ti/drivers/SPI.h>
    
    #include <ti/drivers/GPIO.h>
    #include <ti/drivers/net/wifi/simplelink.h>
    #include <ti/drivers/net/wifi/slnetifwifi.h>
    #include <ti/drivers/net/wifi/netapp.h>
    #include <ti/drivers/net/wifi/wlan.h>
    #include <ti/display/Display.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include <semaphore.h>
    #include <unistd.h>
    
    #include "ti_drivers_config.h"
    #include "pthread.h"
    /////////
    #include <string.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include "wificonfig.h"
    #include "mcu.h"
    
    /* Provisioning inactivity timeout in seconds */
    #define PROV_INACTIVITY_TIMEOUT (600)
    #define APPLICATION_NAME                      ("TCP Echo")
    #define APPLICATION_VERSION                   ("1.0.0.0")
    #define DEVICE_ERROR                          ("Device error, please refer \"DEVICE ERRORS CODES\" section in errors.h")
    #define WLAN_ERROR                            ("WLAN error, please refer \"WLAN ERRORS CODES\" section in errors.h")
    #define SL_STOP_TIMEOUT                       (200)
    
    #define TCPPORT                               (2020)
    //#define MESSAGE_LENGTH                        (4)
    #define SPAWN_TASK_PRIORITY                   (9)
    #define TASK_STACK_SIZE                       (2048)
    #define SLNET_IF_WIFI_PRIO                    (5)
    #define SLNET_IF_WIFI_NAME                    "CC32xx"
    
    //#define SSID_NAME                             "TEV_AP"                  /* AP SSID */
    #define SECURITY_TYPE                         SL_WLAN_SEC_TYPE_WPA_WPA2 /* Security type could be SL_WLAN_SEC_TYPE_OPEN */
    //#define SECURITY_KEY                          "raspberry"                /* Password of the secured AP */
    /*
    #define SEND_CIPHER                            "0000"
    #define VERIFY_IDENTITY                        "0001"
    #define RECEIVE_DATA                           "0010"
    #define START_STREAM                           "0011"
    #define STOP_STREAM                            "0100"
    #define STOP                                   "1111"
    
    #define ACK                                    "ACK_"
    #define nack                                   "NACK"*/
    char wsdSsidName[33] = "TEV_Honeywell";
    char SsidName[33];
    char psk[33];
    int8_t SECURITY_LEN;
    
    uint8_t ssidLen;
    typedef struct TaskArgs {
        void (*arg0)();
        uintptr_t arg1;
        uintptr_t arg2;
    } TaskArgs;
    
    
    pthread_t tcpThread = (pthread_t)NULL;
    pthread_t spawn_thread = (pthread_t)NULL;
    pthread_t tcpworker_thread = (pthread_t)NULL;
    int32_t             mode;
    Display_Handle display;
    char *AES_key = "5RqzBtDpA6SJ2uAliYGqhdO6DgDT98bdeqmfHJQUtrk=";
    int8_t       COUNT = 0;
    CryptoCC32XX_Handle      cryptoHandle;
    CryptoCC32XX_EncryptMethod config;
    int32_t CONFIG_CRYPTO_0;
    CryptoCC32XX_EncryptParams          AESparams;
     char               plainData[16] = "whatsoever123456";
     int                plainDataLen = sizeof(plainData);
     char               dec_data[1024] ;
     int               dec_DataLen ;
     char               cipherData[1024] = "gAAAAABf4H8Cyeqnpkg9_mxEIP1Zy3lg0ozXSUxpmDLPK4WiMqwrRfL9_rMnBsQLzF2ZCJyEWpGbfKYQEaJaiMkfQLjv9DI6iiiUFw1ue9YgK5oquO37Giljuo4E_qplvG8yefJXkgz6";
     int                cipherDataLen = 140;
    char                chiper_length[256] = "0140";
    
     char SEND_CIPHER[256]  ="0000";
     char VERIFY_IDENTITY[256]  ="0001";
     char RECEIVE_DATA[256]  ="0010";
     char START_STREAM[256]  ="0011";
     char STOP_STREAM[256]  ="0100";
     char STOP[256]  ="1111";
     char ACK[256]  = "ACK_";
     char NACK[256]  ="NACK";
     int8_t length_received[4];
     int8_t MESSAGE_LENGTH = 4;
    
    int ipointerToInitVector;
    extern void tcpHandler(uint32_t arg0, uint32_t arg1);
    extern void tcpWorker(uint32_t arg0, uint32_t arg1);
    //extern int32_t ti_net_SlNet_initConfig();
    void tcpConnector();
    void Connect(void);
    static uint32_t deviceConnected = false;
    static uint32_t ipAcquired = false;
    
    int32_t             mode;
    extern Display_Handle display;
    
    
    static sem_t sem;
    
    extern void startSNTP(void);
    
    static void initWiFi();
    
    
    void printError(char *errString, int code)
    {
        Display_printf(display, 0, 0, "Error! code = %d, Description = %s\n", code,
                errString);
        while(1);
    }
    
    /*
     *  ======== Network_init =======
     */
    void Network_init()
    {
        if (sem_init(&sem, 0, 0) != 0) {
            /* Error: sem_init failed */
            while (1);
        }
    }
    
    /*
     *  ======== Network_startup =======
     */
    void Network_startup()
    {
        int32_t status;
    
    
        /* Connect to the Access Point */
        initWiFi();
    
        /* Wait for the network stack to initialize and acquire an IP address */
        sem_wait(&sem);
    
        /* initialize SlNet interface(s) */
        status = ti_net_SlNet_initConfig();
        if (status < 0) {
            // ti_net_SlNet_initConfig failed
            Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
            while (1);
        }
    
        /* Turn LED OFF. It will be used as a connection indicator */
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
    
        /* Use SNTP to get the current time, as needed for SSL authentication */
        startSNTP();
     //  provisioningFxn();
      // sem_wait(&sem);
      //  startSNTP();
    
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
    }
    
    /*
     *  ======== Network_exit =======
     */
    void Network_exit()
    {
    }
    
    /*
     *
     *  SimpleLink Asynchronous Event Handlers -- Start
     *
     */
    
    /*
     *  ======== SimpleLinkHttpServerEventHandler ========
     */
    void SimpleLinkHttpServerEventHandler(
            SlNetAppHttpServerEvent_t *pSlHttpServerEvent,
            SlNetAppHttpServerResponse_t *pSlHttpServerResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestEventHandler ========
     */
    void SimpleLinkNetAppRequestEventHandler(SlNetAppRequest_t *pNetAppRequest,
            SlNetAppResponse_t *pNetAppResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestMemFreeEventHandler ========
     */
    void SimpleLinkNetAppRequestMemFreeEventHandler(uint8_t *buffer)
    {
    }
    
    /*
     *  ======== SimpleLinkWlanEventHandler ========
     *  SimpleLink Host Driver callback for handling WLAN connection or
     *  disconnection events.
     */
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        switch (pWlanEvent->Id) {
            case SL_WLAN_EVENT_CONNECT:
                deviceConnected = true;
                break;
    
            case SL_WLAN_EVENT_DISCONNECT:
                deviceConnected = false;
                break;
    
            case SL_WLAN_EVENT_PROVISIONING_STATUS:
                switch (pWlanEvent->Data.ProvisioningStatus.ProvisioningStatus) {
                    case SL_WLAN_PROVISIONING_CONFIRMATION_WLAN_CONNECT:
                        deviceConnected = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_CONFIRMATION_IP_ACQUIRED:
                        ipAcquired = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_STOPPED:
                        if (pWlanEvent->Data.ProvisioningStatus.Role == ROLE_STA) {
                            if (pWlanEvent->Data.ProvisioningStatus.WlanStatus ==
                                    SL_WLAN_STATUS_CONNECTED) {
                                /* The WiFi stack is ready and has an IP address */
                                provisioning = false;
                                sem_post(&sem);
                            }
                        }
    
                        break;
    
                    default:
                        break;
                }
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkFatalErrorEventHandler ========
     *  This function handles fatal errors
     *
     *  \param[in]  slFatalErrorEvent - Pointer to the fatal error event info
     *
     *  \return     None
     */
    void SimpleLinkFatalErrorEventHandler(SlDeviceFatal_t *slFatalErrorEvent)
    {
        switch (slFatalErrorEvent->Id) {
            case SL_DEVICE_EVENT_FATAL_DEVICE_ABORT:
                /* FATAL ERROR: Abort NWP event detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_DRIVER_ABORT:
                /* FATAL ERROR: Driver Abort detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_NO_CMD_ACK:
                /* FATAL ERROR: No Cmd Ack detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_SYNC_LOSS:
                /* FATAL ERROR: Sync loss detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_CMD_TIMEOUT:
                /* FATAL ERROR: Async event timeout detected */
                while (1);
    
            default:
                /* FATAL ERROR: Unspecified error detected */
                while (1);
        }
    }
    
    /*
     *  ======== SimpleLinkNetAppEventHandler ========
     *  SimpleLink Host Driver callback for asynchoronous IP address events.
     */
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if (pNetAppEvent == NULL) {
            return;
        }
    
        switch (pNetAppEvent->Id) {
            case SL_NETAPP_EVENT_IPV4_ACQUIRED:
            case SL_NETAPP_EVENT_IPV6_ACQUIRED:
                ipAcquired = true;
    
                /*  Signal that the WiFi stack is ready and has an IP address */
                sem_post(&sem);
    
                break;
    
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkSockEventHandler ========
     */
    void SimpleLinkSockEventHandler(SlSockEvent_t *pArgs)
    {
    }
    
    /*
     *  ======== SimpleLinkGeneralEventHandler ========
     */
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *sockEvent)
    {
    }
    
    /*
     *  ======== provisioningFxn ========
     */
    void provisioningFxn()
    {
        int32_t status;
        pthread_attr_t      pAttrs_spawn;
            struct sched_param  priParam;
            Display_printf(display, 0, 0, "entered provisioningFxn");
       // sl_NetAppStart(SL_NETAPP_HTTP_SERVER_ID);
            pthread_attr_init(&pAttrs_spawn);
               priParam.sched_priority = SPAWN_TASK_PRIORITY;
               status = pthread_attr_setschedparam(&pAttrs_spawn, &priParam);
               status |= pthread_attr_setstacksize(&pAttrs_spawn, TASK_STACK_SIZE);
    
               status = pthread_create(&spawn_thread, &pAttrs_spawn, sl_Task, NULL);
    
    
               if(status)
               {
                   printError("Task create failed", status);
               }
    
        /*mode = sl_Stop(SL_STOP_TIMEOUT);
           if (mode < 0)
           {
               Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
           }
    
        mode = sl_Start(0, 0, 0);
            if (mode < 0)
             {
                Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
             }
    */       if(1)
           {
               /* Set NWP role as STA */
    
               mode = sl_WlanSetMode(ROLE_AP);
               sl_WlanSet(SL_WLAN_CFG_AP_ID, SL_WLAN_AP_OPT_SSID, strlen(wsdSsidName),(const uint8_t *) wsdSsidName);
    
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
               }
    
               /* For changes to take affect, we restart the NWP */
               status = sl_Stop(SL_STOP_TIMEOUT);
               if (status < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
               }
    
               mode = sl_Start(0, 0, 0);
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
               }
           }
    
           if(mode != ROLE_AP)
           {
               printError("Failed to configure device to it's default state", mode);
           }
    
    
           tcpConnector();
    }
    
    /*
     *  ======== wlanConnect =======
     *  Secure connection parameters
     */
    static int wlanConnect()
    {
        SlWlanSecParams_t SecParams = {0};
        SlWlanSecParams_t secParams = {0};
        int ret = 0;
        SlNetCfgIpV4Args_t ipV4;
               uint16_t           len = sizeof(ipV4);
               uint16_t           dhcpIsOn;
               _u8 MacAddr1[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
               _i16 index, Status;
               signed char Name[32];
               _i16 NameLength;
               unsigned char MacAddr[6];
    
               SlWlanGetSecParamsExt_t SecExtParams;
               _u32 Priority,i;
               _i16 Index =0;
               char mac_str[10];
               _u8 pPolicy;
               _u8 pVal;
               _u8 pValLen;
               SlWlanNetworkEntry_t netEntries[30];
                          _i16 resultsCount = sl_WlanGetNetworkList(0,30,&netEntries[0]);
                          Display_printf(display, 0, 0, "resultsCount : %d.\r\n",  resultsCount);
    
                          for(i =0;i<resultsCount;i++)
                          {
                              Display_printf(display, 0, 0, "ssid : %s.\r\n",  netEntries[0].Ssid);
                          }
             // Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,1,0,1),NULL,0);
               Status =  sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
                   Display_printf(display, 0, 0, "pPolicy : %d.\r\n",  pPolicy);
                   Display_printf(display, 0, 0, "pVal : %d.\r\n",  pVal);
                   Display_printf(display, 0, 0, "pValLen : %d.\r\n",  pValLen);
    
                   if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
                   {
                       printf("Connection Policy is set to auto");
                   }
              /* secParams.Key = (signed char *)SECURITY_KEY;
                         secParams.KeyLen = strlen((const char *)secParams.Key);
                         secParams.Type = SECURITY_TYPE;*/
                         //Index = sl_WlanProfileAdd((signed char*)SSID,  7, MacAddr1, &secParams, NULL, 15,0);
                  //Display_printf(display,0,0,"Index--%d",Index);
    
               Status = sl_WlanProfileGet(Index, Name, &NameLength, MacAddr, &SecParams, &SecExtParams,&Priority);
    
               Display_printf(display, 0, 0, "Name : %s.\r\n",  Name);
               Display_printf(display, 0, 0, "Name : %d.\r\n",  NameLength);
               Display_printf(display, 0, 0, "Status : %d.\r\n",  Status);
               Display_printf(display, 0, 0, "Priority : %d.\r\n", Priority);
               sprintf(mac_str,"%0x:%0x:%0x:%0x:%0x:%0x",MacAddr[0],MacAddr[1],MacAddr[2],MacAddr[3],MacAddr[4],MacAddr[5]);
               Display_printf(display, 0, 0, "macid : %s.\r\n", mac_str);
               if( Status )
               {
               /* error */
               }
    
                 /*  if (strlen(Name) != 0) {
                       secParams.Key = (signed char *)SECURITY_KEY;
                               secParams.KeyLen = strlen((const char *)secParams.Key);
                               secParams.Type = SECURITY_TYPE;
                      Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                      ret = sl_WlanConnect((signed char*)Name, strlen((const char*)Name),
                              NULL, &secParams, NULL);
                  }
    */
              /*     if (strlen(SSID) != 0) {
            secParams.Key = (signed char *)SECURITY_KEY;
            secParams.KeyLen = strlen((const char *)secParams.Key);
            secParams.Type = SECURITY_TYPE;
            Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
            ret = sl_WlanConnect((signed char*)SSID, strlen((const char*)SSID),
                    NULL, &secParams, NULL);
        }*/
                 //  Status = sl_WlanProfileDel(SL_WLAN_DEL_ALL_PROFILES);
    
        return (ret);
    }
    
    /*
     *  ======== initWiFi =======
     *  Start the NWP and connect to AP
     */
    static void initWiFi()
    {
        int32_t status;
        uint32_t currButton;
        uint32_t prevButton = 0;
        _u32 intervalInSeconds = 20;
      /*  status = sl_WifiConfig();
        if (status < 0) {
             sl_WifiConfig failed
            while (1);
        }
    */
    
        /* Set connection variables to initial values */
        deviceConnected = false;
        ipAcquired = false;
        provisioning = false;
    
        status = sl_Start(NULL,NULL,NULL);
            Display_printf(display,0,0," Role-- = %d",status);
               if (ROLE_STA != status)
               {
                   Display_printf(display,0,0,"failed ");
                 //Role Error
               }
            status = sl_WlanSetMode(ROLE_STA);
            Display_printf(display,0,0," sl_WlanSetMode-- = %d",status);
            status = sl_Stop(SL_STOP_TIMEOUT);
    
        /* Host driver starts the network processor */
        if (sl_Start(NULL, NULL, NULL) < 0) {
            /* Error: Could not initialize WiFi */
            while (1);
        }
    
        status = sl_WlanPolicySet(SL_WLAN_POLICY_SCAN, SL_WLAN_SCAN_POLICY(1,1),
                 (_u8*)&intervalInSeconds,sizeof(intervalInSeconds));
                 Display_printf(display,0,0," sl_WlanPolicySet--%d",status);
                 if( status )
                 {
                  /* error */
                 }
                 sleep(5);
    
        if (wlanConnect() < 0) {
            /* Error: Could not connect to WiFi AP */
            while (1);
        }
    
        /*
         * Wait for the WiFi to connect to an AP. If a profile for the AP in
         * use has not been stored yet, press Board_GPIO_BUTTON0 to start
         * provisioning.
         */
      /*  while ((deviceConnected != true) || (ipAcquired != true) ||
                (provisioning == true)) {
    
             *  Start provisioning if a button is pressed. This could be done with
             *  GPIO interrupts, but for simplicity polling is used to check the
             *  button.
    
         //   currButton = GPIO_read(CONFIG_GPIO_BUTTON_0);
         //   if ((currButton == 0) && (prevButton != 0))
                if (wifiModeChange == TRUE)
            {
                provisioningFxn();
            }
            prevButton = currButton;
            usleep(50000);
        }*/
    }
    
    
    
    void tcpConnector()
    {
        int                 clientfd;
        int                 server;
        struct sockaddr_in  localAddr;
        int32_t             status = 0;
        struct sockaddr_in  clientAddr;
        socklen_t           addrlen = sizeof(clientAddr);
        char                send_buffer[256];
        int                 bytesSent;
        int16_t           bytesRcvd;
        int8_t            rxdata;
        char              temp_buffer[4];
    int i;
    Display_printf(display, 0, 0, "entered tcpconnect");
    
     /*  status = ti_net_SlNet_initConfig();
        if(0 != status)
        {
              Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
        }*/
    
        server = socket(AF_INET, SOCK_STREAM, 0);
        if (server == -1)
        {
                Display_printf(display, 0, 0, "tcpHandler: socket failed\n");
            }
    
        memset(&localAddr, 0, sizeof(localAddr));
        localAddr.sin_family = AF_INET;
        localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        localAddr.sin_port = htons(TCPPORT);
        status = bind(server, (struct sockaddr *)&localAddr, sizeof(localAddr));
        if (status == -1)
        {
            Display_printf(display, 0, 0, "tcpHandler: bind failed\n");
        }
    
        status = listen(server, 3);
        if (status == -1) {
            Display_printf(display, 0, 0, "tcpHandler: listen failed\n");
        }
    
    
        if ((clientfd = accept(server, (struct sockaddr *)&clientAddr, &addrlen)) != -1)
        {
            Display_printf(display, 0, 0,
                           "clientAddr = %x\n", clientAddr);
            Display_printf(display, 0, 0,
                    "tcpHandler: Creating thread clientfd = %x\n", clientfd);
    
    //        bytesSent = send(clientfd, send_buffer, 9, 0);
    //        Display_printf(display,0,0,"sent bytes--%d",bytesSent);
    //        Display_printf(display,0,0,"sent bytes--%s",send_buffer);
    //        if (bytesSent < 0 ) {
    //            Display_printf(display, 0, 0, "send failed.\n");
    //        }
    
            while ((bytesRcvd = recv(clientfd, send_buffer, MESSAGE_LENGTH, 0)) > 0)
            {
                Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
                COUNT++;
                Display_printf(display,0,0,"COUNT =%d",COUNT);
                memcpy(temp_buffer,send_buffer,4);
                rxdata = atoi(temp_buffer);
                Display_printf(display,0,0,"rxdata =%d",rxdata);
                if(COUNT == 1 && rxdata == 0)  //Request to send cipher text
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, chiper_length, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 2)//ack received
                {
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, cipherData, cipherDataLen, 0);
                 }
                else if(COUNT == 3)// ack received  no reply
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                }
    
                else if(COUNT == 4 && rxdata == 1)// Request to verify the deciphered text
                 {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                 }
                else if(COUNT == 5)// deciphered length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 6)// deciphered message
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    MESSAGE_LENGTH = 4;
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
    
                }
                else if(COUNT == 7 && rxdata == 10)// Request to receive network credentials
                {
                 memcpy(send_buffer,0,sizeof(send_buffer));
                 MESSAGE_LENGTH = 4;
                 bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 8)//SSID LENGTH
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
    
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                    ssidLen = MESSAGE_LENGTH;
    
                }
                else if(COUNT == 9)//SSID
                {
    
                   memcpy(SsidName,send_buffer,MESSAGE_LENGTH);
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, ACK, 4, 0);
                   MESSAGE_LENGTH = 4;
                 }
                else if(COUNT == 10)//psk length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                    SECURITY_LEN = MESSAGE_LENGTH;
                }
                else if(COUNT == 11) // psk
                {
                    memcpy(psk,send_buffer,MESSAGE_LENGTH);
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                }
                else if(COUNT == 12) // device_name_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                 }
                else if(COUNT == 13) // device_name
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                      bytesSent = send(clientfd, ACK, 4, 0);
                      MESSAGE_LENGTH = 4;
    
                }
                else if(COUNT == 14)//location_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 15)//loction_id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 16)//location name length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 17)//location_name
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT ==18)//org id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT ==19)//org id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 20)//logical devie id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 21)//logical devie id
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                     bytesSent = send(clientfd, ACK, 4, 0);
                     MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 22)//
                {
    
                    break;
                 }
    
    
    
    
    
    
            }
            Display_printf(display,0,0,"bytesRcvd-%d",bytesRcvd);
            Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
    
    
          }
    
        Display_printf(display,0,0,"after accept---");
        status =  sl_WlanDisconnect();
        Display_printf(display,0,0,"sl_WlanDisconnect status--%d",status);
        Connect();
    
        provisioning = FALSE;
    
    }
    
    
    
    void Connect(void)
    {
        SlWlanSecParams_t   secParams = {0};
        SlWlanSecParams_t   SecParams = {0};
        int16_t ret = 0;
        int16_t status;
        _i16 index, Status;
        _u8 MacAddr[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
        _u8 MacAddr1[10];
        char SsidName1[33];
        _u32 Priority;
        _i16 NameLength;
        SlNetCfgIpV4Args_t ipV4;
            uint16_t           len = sizeof(ipV4);
            uint16_t           dhcpIsOn;
            uint16_t           Index;
            SlWlanGetSecParamsExt_t SecExtParams;
            Display_printf(display,0,0,"entered connet func--%");
        mode = sl_WlanSetMode(ROLE_STA);
        Display_printf(display,0,0,"entered sta mode--%");
    
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
                   }
    
                   /* For changes to take affect, we restart the NWP */
                   status = sl_Stop(SL_STOP_TIMEOUT);
                   if (status < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
                   }
    
                   mode = sl_Start(0, 0, 0);
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
                   }
    
    
               if(mode != ROLE_STA)
               {
                   printError("Failed to configure device to it's default state", mode);
               }
    
               secParams.Key = (signed char *)psk;
               secParams.KeyLen = strlen((const char *)secParams.Key);
               secParams.Type = SECURITY_TYPE;
               Display_printf(display,0,0,"entered connet fun after apmodec--%");
        Index = sl_WlanProfileAdd((signed char*)SsidName, ssidLen, MacAddr, &secParams, NULL, 15,0);
        Display_printf(display,0,0,"Index--%d",Index);
      /*  Status = sl_WlanProfileGet(Index, (signed char*)SsidName1, &NameLength, MacAddr1, &SecParams, &SecExtParams, &Priority);
        Display_printf(display, 0, 0, "SsidName1  : %s.\r\n",SsidName1);
        Display_printf(display, 0, 0, "MacAddr1 : %s.\r\n",MacAddr1);
        Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
        Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", SecParams.Key);
        Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  SecParams.KeyLen);
        Display_printf(display, 0, 0, "SECURITY_LEN : %d.\r\n",  SECURITY_LEN);
        Display_printf(display, 0, 0, "ssidLen : %d.\r\n",  ssidLen);*/
    
       /* secParams.Key = (signed char *)psk;
                secParams.KeyLen = strlen((const char *)secParams.Key);
                secParams.Type = SECURITY_TYPE;*/
                Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
                    Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", secParams.Key);
                    Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                ret = sl_WlanConnect((signed char*)SsidName, strlen((const char*)SsidName),
                        NULL, &secParams, NULL);
        if (ret)
        {
    
            Display_printf(display,0,0,"Connection failed--%d",ret);
        }
    
    //FOR TESTING
    
        sl_NetCfgGet(SL_NETCFG_IPV4_STA_ADDR_MODE, &dhcpIsOn, &len,
                   (unsigned char *)&ipV4);
           Display_printf(display, 0, 0,
                   "CC32XX has connected to AP and acquired an IP address.\n");
           Display_printf(display, 0, 0, "IP Address: %ld.%ld.%ld.%ld\n",
                   SL_IPV4_BYTE(ipV4.Ip, 3), SL_IPV4_BYTE(ipV4.Ip, 2),
                   SL_IPV4_BYTE(ipV4.Ip, 1), SL_IPV4_BYTE(ipV4.Ip, 0));
    
    }
    

  • 3884.network.c
    /*
     * Copyright (c) 2017-2019, 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.
     */
    
    #include <stdbool.h>
    #include <stdint.h>
    
    #include <ti/net/slnet.h>
    #include <ti/drivers/SPI.h>
    
    #include <ti/drivers/GPIO.h>
    #include <ti/drivers/net/wifi/simplelink.h>
    #include <ti/drivers/net/wifi/slnetifwifi.h>
    #include <ti/drivers/net/wifi/netapp.h>
    #include <ti/drivers/net/wifi/wlan.h>
    #include <ti/display/Display.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include <semaphore.h>
    #include <unistd.h>
    
    #include "ti_drivers_config.h"
    #include "pthread.h"
    /////////
    #include <string.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <ti/drivers/crypto/CryptoCC32XX.h>
    #include "wificonfig.h"
    #include "mcu.h"
    
    /* Provisioning inactivity timeout in seconds */
    #define PROV_INACTIVITY_TIMEOUT (600)
    #define APPLICATION_NAME                      ("TCP Echo")
    #define APPLICATION_VERSION                   ("1.0.0.0")
    #define DEVICE_ERROR                          ("Device error, please refer \"DEVICE ERRORS CODES\" section in errors.h")
    #define WLAN_ERROR                            ("WLAN error, please refer \"WLAN ERRORS CODES\" section in errors.h")
    #define SL_STOP_TIMEOUT                       (200)
    
    #define TCPPORT                               (2020)
    //#define MESSAGE_LENGTH                        (4)
    #define SPAWN_TASK_PRIORITY                   (9)
    #define TASK_STACK_SIZE                       (2048)
    #define SLNET_IF_WIFI_PRIO                    (5)
    #define SLNET_IF_WIFI_NAME                    "CC32xx"
    
    //#define SSID_NAME                             "TEV_AP"                  /* AP SSID */
    #define SECURITY_TYPE                         SL_WLAN_SEC_TYPE_WPA_WPA2 /* Security type could be SL_WLAN_SEC_TYPE_OPEN */
    //#define SECURITY_KEY                          "raspberry"                /* Password of the secured AP */
    /*
    #define SEND_CIPHER                            "0000"
    #define VERIFY_IDENTITY                        "0001"
    #define RECEIVE_DATA                           "0010"
    #define START_STREAM                           "0011"
    #define STOP_STREAM                            "0100"
    #define STOP                                   "1111"
    
    #define ACK                                    "ACK_"
    #define nack                                   "NACK"*/
    char wsdSsidName[33] = "TEV_Honeywell";
    char SsidName[33];
    char psk[33];
    int8_t SECURITY_LEN;
    
    uint8_t ssidLen;
    typedef struct TaskArgs {
        void (*arg0)();
        uintptr_t arg1;
        uintptr_t arg2;
    } TaskArgs;
    
    
    pthread_t tcpThread = (pthread_t)NULL;
    pthread_t spawn_thread = (pthread_t)NULL;
    pthread_t tcpworker_thread = (pthread_t)NULL;
    int32_t             mode;
    Display_Handle display;
    char *AES_key = "5RqzBtDpA6SJ2uAliYGqhdO6DgDT98bdeqmfHJQUtrk=";
    int8_t       COUNT = 0;
    CryptoCC32XX_Handle      cryptoHandle;
    CryptoCC32XX_EncryptMethod config;
    int32_t CONFIG_CRYPTO_0;
    CryptoCC32XX_EncryptParams          AESparams;
     char               plainData[16] = "whatsoever123456";
     int                plainDataLen = sizeof(plainData);
     char               dec_data[1024] ;
     int               dec_DataLen ;
     char               cipherData[1024] = "gAAAAABf4H8Cyeqnpkg9_mxEIP1Zy3lg0ozXSUxpmDLPK4WiMqwrRfL9_rMnBsQLzF2ZCJyEWpGbfKYQEaJaiMkfQLjv9DI6iiiUFw1ue9YgK5oquO37Giljuo4E_qplvG8yefJXkgz6";
     int                cipherDataLen = 140;
    char                chiper_length[256] = "0140";
    
     char SEND_CIPHER[256]  ="0000";
     char VERIFY_IDENTITY[256]  ="0001";
     char RECEIVE_DATA[256]  ="0010";
     char START_STREAM[256]  ="0011";
     char STOP_STREAM[256]  ="0100";
     char STOP[256]  ="1111";
     char ACK[256]  = "ACK_";
     char NACK[256]  ="NACK";
     int8_t length_received[4];
     int8_t MESSAGE_LENGTH = 4;
    
    int ipointerToInitVector;
    extern void tcpHandler(uint32_t arg0, uint32_t arg1);
    extern void tcpWorker(uint32_t arg0, uint32_t arg1);
    //extern int32_t ti_net_SlNet_initConfig();
    void tcpConnector();
    void Connect(void);
    static uint32_t deviceConnected = false;
    static uint32_t ipAcquired = false;
    
    int32_t             mode;
    extern Display_Handle display;
    
    
    static sem_t sem;
    
    extern void startSNTP(void);
    
    static void initWiFi();
    
    
    void printError(char *errString, int code)
    {
        Display_printf(display, 0, 0, "Error! code = %d, Description = %s\n", code,
                errString);
        while(1);
    }
    
    /*
     *  ======== Network_init =======
     */
    void Network_init()
    {
        if (sem_init(&sem, 0, 0) != 0) {
            /* Error: sem_init failed */
            while (1);
        }
    }
    
    /*
     *  ======== Network_startup =======
     */
    void Network_startup()
    {
        int32_t status;
    
    
        /* Connect to the Access Point */
        initWiFi();
    
        /* Wait for the network stack to initialize and acquire an IP address */
        sem_wait(&sem);
    
        /* initialize SlNet interface(s) */
        status = ti_net_SlNet_initConfig();
        if (status < 0) {
            // ti_net_SlNet_initConfig failed
            Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
            while (1);
        }
    
        /* Turn LED OFF. It will be used as a connection indicator */
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
    
        /* Use SNTP to get the current time, as needed for SSL authentication */
        startSNTP();
     //  provisioningFxn();
      // sem_wait(&sem);
      //  startSNTP();
    
        GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
    }
    
    /*
     *  ======== Network_exit =======
     */
    void Network_exit()
    {
    }
    
    /*
     *
     *  SimpleLink Asynchronous Event Handlers -- Start
     *
     */
    
    /*
     *  ======== SimpleLinkHttpServerEventHandler ========
     */
    void SimpleLinkHttpServerEventHandler(
            SlNetAppHttpServerEvent_t *pSlHttpServerEvent,
            SlNetAppHttpServerResponse_t *pSlHttpServerResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestEventHandler ========
     */
    void SimpleLinkNetAppRequestEventHandler(SlNetAppRequest_t *pNetAppRequest,
            SlNetAppResponse_t *pNetAppResponse)
    {
    }
    
    /*
     *  ======== SimpleLinkNetAppRequestMemFreeEventHandler ========
     */
    void SimpleLinkNetAppRequestMemFreeEventHandler(uint8_t *buffer)
    {
    }
    
    /*
     *  ======== SimpleLinkWlanEventHandler ========
     *  SimpleLink Host Driver callback for handling WLAN connection or
     *  disconnection events.
     */
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        switch (pWlanEvent->Id) {
            case SL_WLAN_EVENT_CONNECT:
                deviceConnected = true;
                break;
    
            case SL_WLAN_EVENT_DISCONNECT:
                deviceConnected = false;
                break;
    
            case SL_WLAN_EVENT_PROVISIONING_STATUS:
                switch (pWlanEvent->Data.ProvisioningStatus.ProvisioningStatus) {
                    case SL_WLAN_PROVISIONING_CONFIRMATION_WLAN_CONNECT:
                        deviceConnected = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_CONFIRMATION_IP_ACQUIRED:
                        ipAcquired = true;
                        break;
    
                    case SL_WLAN_PROVISIONING_STOPPED:
                        if (pWlanEvent->Data.ProvisioningStatus.Role == ROLE_STA) {
                            if (pWlanEvent->Data.ProvisioningStatus.WlanStatus ==
                                    SL_WLAN_STATUS_CONNECTED) {
                                /* The WiFi stack is ready and has an IP address */
                                provisioning = false;
                                sem_post(&sem);
                            }
                        }
    
                        break;
    
                    default:
                        break;
                }
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkFatalErrorEventHandler ========
     *  This function handles fatal errors
     *
     *  \param[in]  slFatalErrorEvent - Pointer to the fatal error event info
     *
     *  \return     None
     */
    void SimpleLinkFatalErrorEventHandler(SlDeviceFatal_t *slFatalErrorEvent)
    {
        switch (slFatalErrorEvent->Id) {
            case SL_DEVICE_EVENT_FATAL_DEVICE_ABORT:
                /* FATAL ERROR: Abort NWP event detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_DRIVER_ABORT:
                /* FATAL ERROR: Driver Abort detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_NO_CMD_ACK:
                /* FATAL ERROR: No Cmd Ack detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_SYNC_LOSS:
                /* FATAL ERROR: Sync loss detected */
                while (1);
    
            case SL_DEVICE_EVENT_FATAL_CMD_TIMEOUT:
                /* FATAL ERROR: Async event timeout detected */
                while (1);
    
            default:
                /* FATAL ERROR: Unspecified error detected */
                while (1);
        }
    }
    
    /*
     *  ======== SimpleLinkNetAppEventHandler ========
     *  SimpleLink Host Driver callback for asynchoronous IP address events.
     */
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if (pNetAppEvent == NULL) {
            return;
        }
    
        switch (pNetAppEvent->Id) {
            case SL_NETAPP_EVENT_IPV4_ACQUIRED:
            case SL_NETAPP_EVENT_IPV6_ACQUIRED:
                ipAcquired = true;
    
                /*  Signal that the WiFi stack is ready and has an IP address */
                sem_post(&sem);
    
                break;
    
            default:
                break;
        }
    }
    
    /*
     *  ======== SimpleLinkSockEventHandler ========
     */
    void SimpleLinkSockEventHandler(SlSockEvent_t *pArgs)
    {
    }
    
    /*
     *  ======== SimpleLinkGeneralEventHandler ========
     */
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *sockEvent)
    {
    }
    
    /*
     *  ======== provisioningFxn ========
     */
    void provisioningFxn()
    {
        int32_t status;
        pthread_attr_t      pAttrs_spawn;
            struct sched_param  priParam;
            Display_printf(display, 0, 0, "entered provisioningFxn");
       // sl_NetAppStart(SL_NETAPP_HTTP_SERVER_ID);
            pthread_attr_init(&pAttrs_spawn);
               priParam.sched_priority = SPAWN_TASK_PRIORITY;
               status = pthread_attr_setschedparam(&pAttrs_spawn, &priParam);
               status |= pthread_attr_setstacksize(&pAttrs_spawn, TASK_STACK_SIZE);
    
               status = pthread_create(&spawn_thread, &pAttrs_spawn, sl_Task, NULL);
    
    
               if(status)
               {
                   printError("Task create failed", status);
               }
    
        /*mode = sl_Stop(SL_STOP_TIMEOUT);
           if (mode < 0)
           {
               Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
           }
    
        mode = sl_Start(0, 0, 0);
            if (mode < 0)
             {
                Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
             }
    */       if(1)
           {
               /* Set NWP role as STA */
    
               mode = sl_WlanSetMode(ROLE_AP);
               sl_WlanSet(SL_WLAN_CFG_AP_ID, SL_WLAN_AP_OPT_SSID, strlen(wsdSsidName),(const uint8_t *) wsdSsidName);
    
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
               }
    
               /* For changes to take affect, we restart the NWP */
               status = sl_Stop(SL_STOP_TIMEOUT);
               if (status < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
               }
    
               mode = sl_Start(0, 0, 0);
               if (mode < 0)
               {
                   Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
               }
           }
    
           if(mode != ROLE_AP)
           {
               printError("Failed to configure device to it's default state", mode);
           }
    
    
           tcpConnector();
    }
    
    /*
     *  ======== wlanConnect =======
     *  Secure connection parameters
     */
    static int wlanConnect()
    {
        SlWlanSecParams_t SecParams = {0};
        SlWlanSecParams_t secParams = {0};
        int ret = 0;
        SlNetCfgIpV4Args_t ipV4;
               uint16_t           len = sizeof(ipV4);
               uint16_t           dhcpIsOn;
               _u8 MacAddr1[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
               _i16 index, Status;
               signed char Name[32];
               _i16 NameLength;
               unsigned char MacAddr[6];
    
               SlWlanGetSecParamsExt_t SecExtParams;
               _u32 Priority,i;
               _i16 Index =0;
               char mac_str[10];
               _u8 pPolicy;
               _u8 pVal;
               _u8 pValLen;
               SlWlanNetworkEntry_t netEntries[30];
                          _i16 resultsCount = sl_WlanGetNetworkList(0,30,&netEntries[0]);
                          Display_printf(display, 0, 0, "resultsCount : %d.\r\n",  resultsCount);
    
                          for(i =0;i<resultsCount;i++)
                          {
                              Display_printf(display, 0, 0, "ssid : %s.\r\n",  netEntries[0].Ssid);
                          }
             // Status = sl_WlanPolicySet(SL_WLAN_POLICY_CONNECTION,SL_WLAN_CONNECTION_POLICY(1,1,0,1),NULL,0);
               Status =  sl_WlanPolicyGet(SL_WLAN_POLICY_CONNECTION, &pPolicy, &pVal, &pValLen);
                   Display_printf(display, 0, 0, "pPolicy : %d.\r\n",  pPolicy);
                   Display_printf(display, 0, 0, "pVal : %d.\r\n",  pVal);
                   Display_printf(display, 0, 0, "pValLen : %d.\r\n",  pValLen);
    
                   if (pPolicy & SL_WLAN_CONNECTION_POLICY(1, 0 , 0 , 0 ))
                   {
                       printf("Connection Policy is set to auto");
                   }
              /* secParams.Key = (signed char *)SECURITY_KEY;
                         secParams.KeyLen = strlen((const char *)secParams.Key);
                         secParams.Type = SECURITY_TYPE;*/
                         //Index = sl_WlanProfileAdd((signed char*)SSID,  7, MacAddr1, &secParams, NULL, 15,0);
                  //Display_printf(display,0,0,"Index--%d",Index);
    
               Status = sl_WlanProfileGet(Index, Name, &NameLength, MacAddr, &SecParams, &SecExtParams,&Priority);
    
               Display_printf(display, 0, 0, "Name : %s.\r\n",  Name);
               Display_printf(display, 0, 0, "Name : %d.\r\n",  NameLength);
               Display_printf(display, 0, 0, "Status : %d.\r\n",  Status);
               Display_printf(display, 0, 0, "Priority : %d.\r\n", Priority);
               sprintf(mac_str,"%0x:%0x:%0x:%0x:%0x:%0x",MacAddr[0],MacAddr[1],MacAddr[2],MacAddr[3],MacAddr[4],MacAddr[5]);
               Display_printf(display, 0, 0, "macid : %s.\r\n", mac_str);
               if( Status )
               {
               /* error */
               }
    
                 /*  if (strlen(Name) != 0) {
                       secParams.Key = (signed char *)SECURITY_KEY;
                               secParams.KeyLen = strlen((const char *)secParams.Key);
                               secParams.Type = SECURITY_TYPE;
                      Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                      ret = sl_WlanConnect((signed char*)Name, strlen((const char*)Name),
                              NULL, &secParams, NULL);
                  }
    */
              /*     if (strlen(SSID) != 0) {
            secParams.Key = (signed char *)SECURITY_KEY;
            secParams.KeyLen = strlen((const char *)secParams.Key);
            secParams.Type = SECURITY_TYPE;
            Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
            ret = sl_WlanConnect((signed char*)SSID, strlen((const char*)SSID),
                    NULL, &secParams, NULL);
        }*/
                 //  Status = sl_WlanProfileDel(SL_WLAN_DEL_ALL_PROFILES);
    
        return (ret);
    }
    
    /*
     *  ======== initWiFi =======
     *  Start the NWP and connect to AP
     */
    static void initWiFi()
    {
        int32_t status;
        uint32_t currButton;
        uint32_t prevButton = 0;
        _u32 intervalInSeconds = 20;
      /*  status = sl_WifiConfig();
        if (status < 0) {
             sl_WifiConfig failed
            while (1);
        }
    */
    
        /* Set connection variables to initial values */
        deviceConnected = false;
        ipAcquired = false;
        provisioning = false;
    
        status = sl_Start(NULL,NULL,NULL);
            Display_printf(display,0,0," Role-- = %d",status);
               if (ROLE_STA != status)
               {
                   Display_printf(display,0,0,"failed ");
                 //Role Error
               }
            status = sl_WlanSetMode(ROLE_STA);
            Display_printf(display,0,0," sl_WlanSetMode-- = %d",status);
            status = sl_Stop(SL_STOP_TIMEOUT);
    
        /* Host driver starts the network processor */
        if (sl_Start(NULL, NULL, NULL) < 0) {
            /* Error: Could not initialize WiFi */
            while (1);
        }
    
        status = sl_WlanPolicySet(SL_WLAN_POLICY_SCAN, SL_WLAN_SCAN_POLICY(1,1),
                 (_u8*)&intervalInSeconds,sizeof(intervalInSeconds));
                 Display_printf(display,0,0," sl_WlanPolicySet--%d",status);
                 if( status )
                 {
                  /* error */
                 }
                 sleep(5);
    
        if (wlanConnect() < 0) {
            /* Error: Could not connect to WiFi AP */
            while (1);
        }
    
        /*
         * Wait for the WiFi to connect to an AP. If a profile for the AP in
         * use has not been stored yet, press Board_GPIO_BUTTON0 to start
         * provisioning.
         */
      /*  while ((deviceConnected != true) || (ipAcquired != true) ||
                (provisioning == true)) {
    
             *  Start provisioning if a button is pressed. This could be done with
             *  GPIO interrupts, but for simplicity polling is used to check the
             *  button.
    
         //   currButton = GPIO_read(CONFIG_GPIO_BUTTON_0);
         //   if ((currButton == 0) && (prevButton != 0))
                if (wifiModeChange == TRUE)
            {
                provisioningFxn();
            }
            prevButton = currButton;
            usleep(50000);
        }*/
    }
    
    
    
    void tcpConnector()
    {
        int                 clientfd;
        int                 server;
        struct sockaddr_in  localAddr;
        int32_t             status = 0;
        struct sockaddr_in  clientAddr;
        socklen_t           addrlen = sizeof(clientAddr);
        char                send_buffer[256];
        int                 bytesSent;
        int16_t           bytesRcvd;
        int8_t            rxdata;
        char              temp_buffer[4];
    int i;
    Display_printf(display, 0, 0, "entered tcpconnect");
    
     /*  status = ti_net_SlNet_initConfig();
        if(0 != status)
        {
              Display_printf(display, 0, 0, "Failed to initialize SlNetSock\n\r");
        }*/
    
        server = socket(AF_INET, SOCK_STREAM, 0);
        if (server == -1)
        {
                Display_printf(display, 0, 0, "tcpHandler: socket failed\n");
            }
    
        memset(&localAddr, 0, sizeof(localAddr));
        localAddr.sin_family = AF_INET;
        localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        localAddr.sin_port = htons(TCPPORT);
        status = bind(server, (struct sockaddr *)&localAddr, sizeof(localAddr));
        if (status == -1)
        {
            Display_printf(display, 0, 0, "tcpHandler: bind failed\n");
        }
    
        status = listen(server, 3);
        if (status == -1) {
            Display_printf(display, 0, 0, "tcpHandler: listen failed\n");
        }
    
    
        if ((clientfd = accept(server, (struct sockaddr *)&clientAddr, &addrlen)) != -1)
        {
            Display_printf(display, 0, 0,
                           "clientAddr = %x\n", clientAddr);
            Display_printf(display, 0, 0,
                    "tcpHandler: Creating thread clientfd = %x\n", clientfd);
    
    //        bytesSent = send(clientfd, send_buffer, 9, 0);
    //        Display_printf(display,0,0,"sent bytes--%d",bytesSent);
    //        Display_printf(display,0,0,"sent bytes--%s",send_buffer);
    //        if (bytesSent < 0 ) {
    //            Display_printf(display, 0, 0, "send failed.\n");
    //        }
    
            while ((bytesRcvd = recv(clientfd, send_buffer, MESSAGE_LENGTH, 0)) > 0)
            {
                Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
                COUNT++;
                Display_printf(display,0,0,"COUNT =%d",COUNT);
                memcpy(temp_buffer,send_buffer,4);
                rxdata = atoi(temp_buffer);
                Display_printf(display,0,0,"rxdata =%d",rxdata);
                if(COUNT == 1 && rxdata == 0)  //Request to send cipher text
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, chiper_length, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 2)//ack received
                {
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, cipherData, cipherDataLen, 0);
                 }
                else if(COUNT == 3)// ack received  no reply
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                }
    
                else if(COUNT == 4 && rxdata == 1)// Request to verify the deciphered text
                 {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                 }
                else if(COUNT == 5)// deciphered length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 6)// deciphered message
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    MESSAGE_LENGTH = 4;
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
    
                }
                else if(COUNT == 7 && rxdata == 10)// Request to receive network credentials
                {
                 memcpy(send_buffer,0,sizeof(send_buffer));
                 MESSAGE_LENGTH = 4;
                 bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                }
                else if(COUNT == 8)//SSID LENGTH
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
    
                    bytesSent = send(clientfd, ACK, MESSAGE_LENGTH, 0);
                    MESSAGE_LENGTH = rxdata;
                    ssidLen = MESSAGE_LENGTH;
    
                }
                else if(COUNT == 9)//SSID
                {
    
                   memcpy(SsidName,send_buffer,MESSAGE_LENGTH);
                   memcpy(send_buffer,0,sizeof(send_buffer));
                   bytesSent = send(clientfd, ACK, 4, 0);
                   MESSAGE_LENGTH = 4;
                 }
                else if(COUNT == 10)//psk length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                    SECURITY_LEN = MESSAGE_LENGTH;
                }
                else if(COUNT == 11) // psk
                {
                    memcpy(psk,send_buffer,MESSAGE_LENGTH);
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                }
                else if(COUNT == 12) // device_name_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                 }
                else if(COUNT == 13) // device_name
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                      bytesSent = send(clientfd, ACK, 4, 0);
                      MESSAGE_LENGTH = 4;
    
                }
                else if(COUNT == 14)//location_length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 15)//loction_id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 16)//location name length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 17)//location_name
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT ==18)//org id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT ==19)//org id
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 20)//logical devie id length
                {
                    memcpy(send_buffer,0,sizeof(send_buffer));
                    bytesSent = send(clientfd, ACK, 4, 0);
                    MESSAGE_LENGTH = rxdata;
                }
                else if(COUNT == 21)//logical devie id
                {
                     memcpy(send_buffer,0,sizeof(send_buffer));
                     bytesSent = send(clientfd, ACK, 4, 0);
                     MESSAGE_LENGTH = 4;
                }
                else if(COUNT == 22)//
                {
    
                    break;
                 }
    
    
    
    
    
    
            }
            Display_printf(display,0,0,"bytesRcvd-%d",bytesRcvd);
            Display_printf(display,0,0,"received/sent bytes--%s",send_buffer);
    
    
          }
    
        Display_printf(display,0,0,"after accept---");
        status =  sl_WlanDisconnect();
        Display_printf(display,0,0,"sl_WlanDisconnect status--%d",status);
        Connect();
    
        provisioning = FALSE;
    
    }
    
    
    
    void Connect(void)
    {
        SlWlanSecParams_t   secParams = {0};
        SlWlanSecParams_t   SecParams = {0};
        int16_t ret = 0;
        int16_t status;
        _i16 index, Status;
        _u8 MacAddr[] = {0x34,0x03,0xde,0x11,0x93,0x3c};
        _u8 MacAddr1[10];
        char SsidName1[33];
        _u32 Priority;
        _i16 NameLength;
        SlNetCfgIpV4Args_t ipV4;
            uint16_t           len = sizeof(ipV4);
            uint16_t           dhcpIsOn;
            uint16_t           Index;
            SlWlanGetSecParamsExt_t SecExtParams;
            Display_printf(display,0,0,"entered connet func--%");
        mode = sl_WlanSetMode(ROLE_STA);
        Display_printf(display,0,0,"entered sta mode--%");
    
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, WLAN_ERROR);
                   }
    
                   /* For changes to take affect, we restart the NWP */
                   status = sl_Stop(SL_STOP_TIMEOUT);
                   if (status < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, status, DEVICE_ERROR);
                   }
    
                   mode = sl_Start(0, 0, 0);
                   if (mode < 0)
                   {
                       Display_printf(display, 0, 0,"\n\r[line:%d, error code:%d] %s\n\r", __LINE__, mode, DEVICE_ERROR);
                   }
    
    
               if(mode != ROLE_STA)
               {
                   printError("Failed to configure device to it's default state", mode);
               }
    
               secParams.Key = (signed char *)psk;
               secParams.KeyLen = strlen((const char *)secParams.Key);
               secParams.Type = SECURITY_TYPE;
               Display_printf(display,0,0,"entered connet fun after apmodec--%");
        Index = sl_WlanProfileAdd((signed char*)SsidName, ssidLen, MacAddr, &secParams, NULL, 15,0);
        Display_printf(display,0,0,"Index--%d",Index);
      /*  Status = sl_WlanProfileGet(Index, (signed char*)SsidName1, &NameLength, MacAddr1, &SecParams, &SecExtParams, &Priority);
        Display_printf(display, 0, 0, "SsidName1  : %s.\r\n",SsidName1);
        Display_printf(display, 0, 0, "MacAddr1 : %s.\r\n",MacAddr1);
        Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
        Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", SecParams.Key);
        Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  SecParams.KeyLen);
        Display_printf(display, 0, 0, "SECURITY_LEN : %d.\r\n",  SECURITY_LEN);
        Display_printf(display, 0, 0, "ssidLen : %d.\r\n",  ssidLen);*/
    
       /* secParams.Key = (signed char *)psk;
                secParams.KeyLen = strlen((const char *)secParams.Key);
                secParams.Type = SECURITY_TYPE;*/
                Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                Display_printf(display, 0, 0, "Connecting to : %s.\r\n",SsidName);
                    Display_printf(display, 0, 0, "secParams.Key : %s.\r\n", secParams.Key);
                    Display_printf(display, 0, 0, "secParams.KeyLen : %d.\r\n",  secParams.KeyLen);
                ret = sl_WlanConnect((signed char*)SsidName, strlen((const char*)SsidName),
                        NULL, &secParams, NULL);
        if (ret)
        {
    
            Display_printf(display,0,0,"Connection failed--%d",ret);
        }
    
    //FOR TESTING
    
        sl_NetCfgGet(SL_NETCFG_IPV4_STA_ADDR_MODE, &dhcpIsOn, &len,
                   (unsigned char *)&ipV4);
           Display_printf(display, 0, 0,
                   "CC32XX has connected to AP and acquired an IP address.\n");
           Display_printf(display, 0, 0, "IP Address: %ld.%ld.%ld.%ld\n",
                   SL_IPV4_BYTE(ipV4.Ip, 3), SL_IPV4_BYTE(ipV4.Ip, 2),
                   SL_IPV4_BYTE(ipV4.Ip, 1), SL_IPV4_BYTE(ipV4.Ip, 0));
    
    }
    

  • Hi Jan ,

    my problem got resolved. MAC id was not correct

    Thanks & regards,

    Sandeep.M