/* * Application's entry point */ int main(int argc, char** argv) { _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU These functions needs to be implemented in PAL */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) { CLI_Write(" Failed to configure the device in its default state \n\r"); } LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); /* * Assumption is that the device is configured in station mode already * and it is in its default state */ /* Initializing the CC3100 device */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device started as STATION \n\r"); /* Set the power policy to always On (SL_ALWAYS_ON_POLICY) * Both NWP and Wifi will remain active * Other Valid options are: * - SL_NORMAL_POLICY * - SL_LOW_POWER_POLICY * - SL_LONG_SLEEP_INTERVAL_POLICY * * For Long sleep policy the max sleep time can be defined by * _u16 pBuff[4] = {0, 0, time, 0}, time:100-2000 in ms * sl_WlanPolicySet(SL_POLICY_PM , SL_LONG_SLEEP_INTERVAL_POLICY, pBuff, sizeof(pBuff)*/ retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_ALWAYS_ON_POLICY, NULL,0); if(retVal < 0) LOOP_FOREVER(); CLI_Write(" Power mode enabled \n\r"); /* Stop the CC3100 device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) LOOP_FOREVER(); return 0; }
//**************************************************************************** // //! \brief Obtain the file from the server //! //! This function requests the file from the server and save it on serial flash. //! To request a different file for different user needs to modify the //! PREFIX_BUFFER macros. //! //! \param[in] cli - Instance of the HTTP connection //! //! \return 0 for success and negative for error // //**************************************************************************** static int GetData(HTTPCli_Handle cli) { long lRetVal = 0; long fileHandle = -1; unsigned long Token = 0; int id; int len=0; bool moreFlag = 0; HTTPCli_Field fields[3] = { {HTTPCli_FIELD_NAME_HOST, HOST_NAME}, {HTTPCli_FIELD_NAME_ACCEPT, "text/html, application/xhtml+xml, */*"}, {NULL, NULL} }; const char *ids[4] = { HTTPCli_FIELD_NAME_CONTENT_LENGTH, HTTPCli_FIELD_NAME_TRANSFER_ENCODING, HTTPCli_FIELD_NAME_CONNECTION, NULL }; UART_PRINT("Start downloading the file\r\n"); // Set request fields HTTPCli_setRequestFields(cli, fields); memset(g_buff, 0, sizeof(g_buff)); // Make HTTP 1.1 GET request lRetVal = HTTPCli_sendRequest(cli, HTTPCli_METHOD_GET, PREFIX_BUFFER, 0); if (lRetVal < 0) { // error ASSERT_ON_ERROR(TCP_SEND_ERROR); } // Test getResponseStatus: handle lRetVal = HTTPCli_getResponseStatus(cli); if (lRetVal != 200) { FlushHTTPResponse(cli); if(lRetVal == 404) { ASSERT_ON_ERROR(FILE_NOT_FOUND_ERROR); } ASSERT_ON_ERROR(INVALID_SERVER_RESPONSE); } HTTPCli_setResponseFields(cli, ids); // Read response headers while ((id = HTTPCli_getResponseField(cli, (char *)g_buff, sizeof(g_buff), &moreFlag)) != HTTPCli_FIELD_ID_END) { if(id == 0) { UART_PRINT("Content length: %s\n\r", g_buff); } else if(id == 1) { if(!strncmp((const char *)g_buff, "chunked", sizeof("chunked"))) { UART_PRINT("Chunked transfer encoding\n\r"); } } else if(id == 2) { if(!strncmp((const char *)g_buff, "close", sizeof("close"))) { ASSERT_ON_ERROR(FORMAT_NOT_SUPPORTED); } } } // Open file to save the downloaded file lRetVal = sl_FsOpen((_u8 *)FILE_NAME, FS_MODE_OPEN_WRITE, &Token, &fileHandle); if(lRetVal < 0) { // File Doesn't exit create a new of 40 KB file lRetVal = sl_FsOpen((unsigned char *)FILE_NAME, \ FS_MODE_OPEN_CREATE(SIZE_40K, \ _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE), &Token, &fileHandle); ASSERT_ON_ERROR(lRetVal); } while(1) { len = HTTPCli_readResponseBody(cli, (char *)g_buff, sizeof(g_buff) - 1, &moreFlag); if(len < 0) { // Close file without saving lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1); return lRetVal; } lRetVal = sl_FsWrite(fileHandle, bytesReceived, (unsigned char *)g_buff, len); if(lRetVal < len) { UART_PRINT("Failed during writing the file, Error-code: %d\r\n", \ FILE_WRITE_ERROR); // Close file without saving lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1); return lRetVal; } bytesReceived +=len; if ((len - 2) >= 0 && g_buff[len - 2] == '\r' && g_buff [len - 1] == '\n'){ break; } if(!moreFlag) { break; } } // // If user file has checksum which can be used to verify the temporary // file then file should be verified // In case of invalid file (FILE_NAME) should be closed without saving to // recover the previous version of file // // Save and close file UART_PRINT("Total bytes received: %d\n\r", bytesReceived); lRetVal = sl_FsClose(fileHandle, 0, 0, 0); ASSERT_ON_ERROR(lRetVal); return SUCCESS; }
//***************************************************************************** //! \brief This function puts the device in its default state. It: //! - Set the mode to STATION //! - Configures connection policy to Auto and AutoSmartConfig //! - Deletes all the stored profiles //! - Enables DHCP //! - Disables Scan policy //! - Sets Tx power to maximum //! - Sets power policy to normal //! - Unregister mDNS services //! - Remove all filters //! //! \param none //! \return On success, zero is returned. On error, negative is returned //***************************************************************************** static long ConfigureSimpleLinkToDefaultState() { SlVersionFull ver = {0}; _WlanRxFilterOperationCommandBuff_t RxFilterIdMask = {0}; unsigned char ucVal = 1; unsigned char ucConfigOpt = 0; unsigned char ucConfigLen = 0; unsigned char ucPower = 0; long lRetVal = -1; long lMode = -1; lMode = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lMode); // If the device is not in station-mode, try configuring it in station-mode if (ROLE_STA != lMode) { if (ROLE_AP == lMode) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } // Switch to STA role and restart lRetVal = sl_WlanSetMode(ROLE_STA); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is in station again if (ROLE_STA != lRetVal) { // We don't want to proceed if the device is not coming up in STA-mode return DEVICE_NOT_IN_STATION_MODE; } } // Get the device's version-information ucConfigOpt = SL_DEVICE_GENERAL_VERSION; ucConfigLen = sizeof(ver); lRetVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &ucConfigOpt, &ucConfigLen, (unsigned char *)(&ver)); ASSERT_ON_ERROR(lRetVal); UART_PRINT("Host Driver Version: %s\n\r",SL_DRIVER_VERSION); UART_PRINT("Build Version %d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d\n\r", ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3], ver.ChipFwAndPhyVersion.FwVersion[0],ver.ChipFwAndPhyVersion.FwVersion[1], ver.ChipFwAndPhyVersion.FwVersion[2],ver.ChipFwAndPhyVersion.FwVersion[3], ver.ChipFwAndPhyVersion.PhyVersion[0],ver.ChipFwAndPhyVersion.PhyVersion[1], ver.ChipFwAndPhyVersion.PhyVersion[2],ver.ChipFwAndPhyVersion.PhyVersion[3]); // Set connection policy to Auto + SmartConfig // (Device's default connection policy) lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0); ASSERT_ON_ERROR(lRetVal); // Remove all profiles lRetVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(lRetVal); // // Device in station-mode. Disconnect previous connection if any // The function returns 0 if 'Disconnected done', negative number if already // disconnected Wait for 'disconnection' event if 0 is returned, Ignore // other return-codes // lRetVal = sl_WlanDisconnect(); if(0 == lRetVal) { // Wait while(IS_CONNECTED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } // Enable DHCP client lRetVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&ucVal); ASSERT_ON_ERROR(lRetVal); // Disable scan ucConfigOpt = SL_SCAN_POLICY(0); lRetVal = sl_WlanPolicySet(SL_POLICY_SCAN , ucConfigOpt, NULL, 0); ASSERT_ON_ERROR(lRetVal); // Set Tx power level for station mode // Number between 0-15, as dB offset from max power - 0 will set max power ucPower = 0; lRetVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&ucPower); ASSERT_ON_ERROR(lRetVal); // Set PM policy to normal lRetVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0); ASSERT_ON_ERROR(lRetVal); // Unregister mDNS services lRetVal = sl_NetAppMDNSUnRegisterService(0, 0); ASSERT_ON_ERROR(lRetVal); // Remove all 64 filters (8*8) memset(RxFilterIdMask.FilterIdMask, 0xFF, 8); lRetVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t)); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); ASSERT_ON_ERROR(lRetVal); InitializeAppVariables(); return lRetVal; // Success }
//***************************************************************************** // //! Network_IF_InitDriver //! The function initializes a CC3200 device and triggers it to start operation //! //! \param uiMode (device mode in which device will be configured) //! //! \return 0 : sucess, -ve : failure // //***************************************************************************** long Network_IF_InitDriver(unsigned int uiMode) { long lRetVal = -1; // Reset CC3200 Network State Machine InitializeAppVariables(); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of application // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state \n\r"); LOOP_FOREVER(); } UART_PRINT("Device is configured in default state \n\r"); // // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(NULL,NULL,NULL); if (lRetVal < 0 || lRetVal != ROLE_STA) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } UART_PRINT("Started SimpleLink Device: STA Mode\n\r"); if(uiMode == ROLE_AP) { UART_PRINT("Switching to AP mode on application request\n\r"); // Switch to AP role and restart lRetVal = sl_WlanSetMode(uiMode); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is up in AP Mode if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif } } else { // We don't want to proceed if the device is not coming up in AP-mode ASSERT_ON_ERROR(DEVICE_NOT_IN_AP_MODE); } UART_PRINT("Re-started SimpleLink Device: AP Mode\n\r"); } else if(uiMode == ROLE_P2P) { UART_PRINT("Switching to P2P mode on application request\n\r"); // Switch to AP role and restart lRetVal = sl_WlanSetMode(uiMode); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(0xFF); lRetVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(lRetVal); // Check if the device is in station again if (ROLE_P2P != lRetVal) { // We don't want to proceed if the device is not coming up in P2P-mode ASSERT_ON_ERROR(DEVICE_NOT_IN_P2P_MODE); } UART_PRINT("Re-started SimpleLink Device: P2P Mode\n\r"); } else { // Device already started in STA-Mode } return 0; }
/* * Application's entry point */ int main(int argc, char** argv) { SlSecParams_t secParams = {0}; _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc.) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) CLI_Write(" Failed to configure the device in its default state \n\r"); LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); /* * Initializing the CC3100 device * Assumption is that the device is configured in station mode already * and it is in its default state */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device started as STATION \n\r"); /* Delete all profiles (0xFF) stored and reset policy settings */ retVal = sl_WlanProfileDel(0xFF); if(retVal < 0) { LOOP_FOREVER(); } retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION , SL_CONNECTION_POLICY(0, 0, 0, 0, 0), 0, 0); if(retVal < 0) { LOOP_FOREVER(); } /* Add unsecured AP profile with priority 6 (7 is highest) */ retVal = sl_WlanProfileAdd((_i8 *)UNSEC_SSID_NAME, pal_Strlen(UNSEC_SSID_NAME), g_BSSID, 0, 0, 6, 0); if(retVal < 0) { LOOP_FOREVER(); } /* Add WPA2 secured AP profile with priority 7 (highest) */ secParams.Type = SL_SEC_TYPE_WPA; secParams.Key = SEC_SSID_KEY; secParams.KeyLen = pal_Strlen(SEC_SSID_KEY); retVal = sl_WlanProfileAdd((_i8 *)SEC_SSID_NAME, pal_Strlen(SEC_SSID_NAME), g_BSSID, &secParams, 0, 7, 0); if(retVal < 0) { LOOP_FOREVER(); } /* * Enable auto connect (connection to stored profiles according to priority) * Connection should first be established to higher (secured) profile as in * this example */ retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION , SL_CONNECTION_POLICY(1,0,0,0,0), 0, 0); if(retVal < 0) { LOOP_FOREVER(); } /* Wait for the connection to be established */ while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); } CLI_Write(" Device connected to the AP using 'auto' connection policy\n\r"); /* Delete all profiles (0xFF) stored */ retVal = sl_WlanProfileDel(0xFF); if(retVal < 0) { LOOP_FOREVER(); } g_Status = 0; /* Restart the device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) { LOOP_FOREVER(); } retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } /* * Set connection policy to Fast - Device will connect to the last connected AP. * This feature can be used to reconnect to AP */ retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 1, 0, 0, 0), 0, 0); if(retVal < 0) { LOOP_FOREVER(); } /* Connect to the open AP */ retVal = establishConnectionWithAP(); if(retVal < 0) { CLI_Write(" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write(" Device was connected to the AP using host-driver API \n\r"); g_Status = 0; /* Status variable */ /* Restart the Device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) { LOOP_FOREVER(); } retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } /* Wait for the connection to be established */ while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); } CLI_Write(" Device connected to the AP using 'fast' connection policy\n\r"); /* Delete all profiles (0xFF) stored */ retVal = sl_WlanProfileDel(0xFF); if(retVal < 0) { LOOP_FOREVER(); } /* Set Auto SmartConfig policy */ retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION , SL_CONNECTION_POLICY(1,0,0,0,1), 0, 0); if(retVal < 0) { LOOP_FOREVER(); } /* Restart the Device */ g_Status = 0; retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) { LOOP_FOREVER(); } retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } /* * After restarting , device will wait for a command for 2 second and start * the SmartConfig process if no command is received */ CLI_Write(" Device waiting to be connected using SmartConfig technology \n\r"); while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); } CLI_Write(" Device connected to the AP \n\r"); /* * Cleaning all profiles and setting the default connection policy before exiting the application * Set connection policy to Auto + SmartConfig (Device's default connection policy) */ retVal = sl_WlanProfileDel(0xFF); if(retVal < 0) { LOOP_FOREVER(); } retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0); if(retVal < 0) { LOOP_FOREVER(); } return 0; }
//***************************************************************************** // //! \brief Connecting to a WLAN Accesspoint //! This function connects to the required AP (SSID_NAME). //! This code example assumes the AP doesn't use WIFI security. //! The function will return only once we are connected //! and have acquired IP address //! //! \param[in] None //! //! \return 0 means success, -1 means failure //! //! \note //! //! \warning If the WLAN connection fails or we don't aquire an IP address, //! We will be stuck in this function forever. // //***************************************************************************** int WlanConnect() { int iRetCode = 0; int iRetVal = 0; int iConnect = 0; unsigned char ucQueueMsg = 0; SlSecParams_t secParams; secParams.Key = (signed char *)SECURITY_KEY; secParams.KeyLen = strlen((const char *)secParams.Key); secParams.Type = SECURITY_TYPE; // // Set up the watchdog interrupt handler. // WDT_IF_Init(WatchdogIntHandler, MILLISECONDS_TO_TICKS(WD_PERIOD_MS)); /* Enabling the Sleep clock for the Watch Dog Timer*/ MAP_PRCMPeripheralClkEnable(PRCM_WDT, PRCM_SLP_MODE_CLK); g_ucFeedWatchdog = 1; g_ucWdogCount = 0; while(!(ucQueueMsg & (EVENT_IP_ACQUIRED|CONNECTION_FAILED))) { UART_PRINT("Trying to connect to AP: "); UART_PRINT(SSID_NAME); UART_PRINT("\n\r"); sl_WlanConnect((signed char *)SSID_NAME, strlen((const char *)SSID_NAME), 0, &secParams, 0); iConnect = 0; do{ osi_MsgQRead(&g_tConnection, &ucQueueMsg, OSI_WAIT_FOREVER); switch(ucQueueMsg) { case EVENT_CONNECTION: iConnect = 1; break; case EVENT_IP_ACQUIRED: iRetVal = 0; break; case WDOG_EXPIRED: // // disconnect from the Access Point // if(iConnect) { WlanDisconnect(); } // // stop the simplelink with reqd. timeout value (30 ms) // sl_Stop(SL_STOP_TIMEOUT); UART_PRINT("sl stop\n\r"); MAP_UtilsDelay(8000); // // starting the simplelink // sl_Start(NULL, NULL, NULL); UART_PRINT("sl start\n\r"); break; case EVENT_DISCONNECTION: iConnect = 0; break; case CONNECTION_FAILED: iRetVal = -1; break; default: UART_PRINT("unexpected event\n\r"); break; } }while(ucQueueMsg == (unsigned char)EVENT_CONNECTION); } iRetCode = MAP_WatchdogRunning(WDT_BASE); if(iRetCode) { WDT_IF_DeInit(); MAP_PRCMPeripheralClkDisable(PRCM_WDT, PRCM_RUN_MODE_CLK); } ASSERT_ON_ERROR(iRetVal); return(iRetVal); }
long ConnectToNetwork() { long lRetVal = -1; unsigned int uiConnectTimeoutCnt =0; //Start Simplelink Device lRetVal = sl_Start(NULL,NULL,NULL); ASSERT_ON_ERROR(lRetVal); if(lRetVal != ROLE_STA) { if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } // // Configure to STA Mode // lRetVal = ConfigureMode(ROLE_STA); if(lRetVal !=ROLE_STA) { UART_PRINT("Unable to set STA mode...\n\r"); lRetVal = sl_Stop(SL_STOP_TIMEOUT); CLR_STATUS_BIT_ALL(g_ulStatus); return DEVICE_NOT_IN_STATION_MODE; } } //waiting for the device to Auto Connect while(uiConnectTimeoutCnt<AUTO_CONNECTION_TIMEOUT_COUNT && ((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))) { //Turn Green LED On GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); osi_Sleep(50); //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); osi_Sleep(50); uiConnectTimeoutCnt++; } //Couldn't connect Using Auto Profile if(uiConnectTimeoutCnt==AUTO_CONNECTION_TIMEOUT_COUNT) { CLR_STATUS_BIT_ALL(g_ulStatus); //Turn Green LED On GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { MAP_UtilsDelay(500); } //Turn Green LED Off GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); } return SUCCESS; }
//**************************************************************************** // //! \brief Opening a server side socket and receiving data //! //! This function opens a TCP socket in Listen mode and waits for an incoming //! TCP connection. If a socket connection is established then the function //! will try to read 1000 TCP packets from the connected client. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. //! //! \note This function will wait for an incoming connection till one //! is established // //**************************************************************************** static int BsdTcpServer(unsigned short Port) { SlSockAddrIn_t Addr; SlSockAddrIn_t LocalAddr; int idx; int AddrSize; int SockID; int Status; int newSockID; long LoopCount = 0; long nonBlocking = 1; for (idx=0 ; idx<BUF_SIZE ; idx++) { uBuf.BsdBuf[idx] = (char)(idx % 10); } LocalAddr.sin_family = SL_AF_INET; LocalAddr.sin_port = sl_Htons((unsigned short)Port); LocalAddr.sin_addr.s_addr = 0; SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); ASSERT_ON_ERROR(SockID); AddrSize = sizeof(SlSockAddrIn_t); Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize); if( Status < 0 ) { /* error */ sl_Close(SockID); ASSERT_ON_ERROR(Status); } Status = sl_Listen(SockID, 0); if( Status < 0 ) { sl_Close(SockID); ASSERT_ON_ERROR(Status); } Status = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlocking, sizeof(nonBlocking)); ASSERT_ON_ERROR(Status); newSockID = SL_EAGAIN; while( newSockID < 0 && IS_IP_ACQUIRED(g_ulStatus)) { newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize); if( newSockID == SL_EAGAIN ) { /* Wait for 1 ms */ Delay(1); } else if( newSockID < 0 ) { sl_Close(SockID); ASSERT_ON_ERROR(newSockID); } } if(! IS_IP_ACQUIRED(g_ulStatus)) { return CLIENT_DISCONNECTED; } // run 'iperf -c <device IP> -i 1 -t 10000' command on PC/Smartphone while (LoopCount < TCP_PACKET_COUNT) { Status = sl_Recv(newSockID, uBuf.BsdBuf, BUF_SIZE, 0); if( Status <= 0 ) { /* error */ ASSERT_ON_ERROR(sl_Close(newSockID)); ASSERT_ON_ERROR(sl_Close(SockID)); ASSERT_ON_ERROR(Status); } LoopCount++; } GPIO_IF_LedOn(MCU_EXECUTE_SUCCESS_IND); ASSERT_ON_ERROR(sl_Close(newSockID)); ASSERT_ON_ERROR(sl_Close(SockID)); return SUCCESS; }
//***************************************************************************** // //! RxStatisticsCollect //! //! This function //! 1. Function for performing the statistics by listening on the //! channel given by the user. //! //! \return none // //***************************************************************************** static int RxStatisticsCollect() { int iSoc; char acBuffer[1500]; SlGetRxStatResponse_t rxStatResp; //char cChar; int iIndex; int iChannel; long lRetVal = -1; int iRightInput = 0; char acCmdStore[512]; struct SlTimeval_t timeval; timeval.tv_sec = 0; // Seconds timeval.tv_usec = 20000; // Microseconds. // //Clear all fields to defaults // rxStatResp.ReceivedValidPacketsNumber = 0; rxStatResp.ReceivedFcsErrorPacketsNumber = 0; rxStatResp.ReceivedAddressMismatchPacketsNumber = 0; rxStatResp.AvarageMgMntRssi = 0; rxStatResp.AvarageDataCtrlRssi = 0; for(iIndex = 0 ; iIndex < SIZE_OF_RSSI_HISTOGRAM ; iIndex++) { rxStatResp.RssiHistogram[iIndex] = 0; } for(iIndex = 0 ; iIndex < NUM_OF_RATE_INDEXES ; iIndex++) { rxStatResp.RateHistogram[iIndex] = 0; } rxStatResp.GetTimeStamp = 0; rxStatResp.StartTimeStamp = 0; // //Prompt the user for channel number // do { UART_PRINT("\n\rEnter the channel to listen[1-13]:"); // // Wait to receive a character over UART // lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. Display a prompt. // UART_PRINT("\n\rEnter Valid Input."); iRightInput = 0; } else { iChannel = (int)strtoul(acCmdStore,0,10); if(iChannel <= 0 || iChannel > 13) { UART_PRINT("\n\rWrong Input"); iRightInput = 0; } else { iRightInput = 1; } } }while(!iRightInput); UART_PRINT("\n\rPress any key to start collecting statistics..."); // // Wait to receive a character over UART // MAP_UARTCharGet(CONSOLE); // //Start Rx statistics collection // lRetVal = sl_WlanRxStatStart(); ASSERT_ON_ERROR(lRetVal); // //Open Socket on the channel to listen // iSoc = sl_Socket(SL_AF_RF,SL_SOCK_RAW,iChannel); ASSERT_ON_ERROR(iSoc); // Enable receive timeout lRetVal = sl_SetSockOpt(iSoc,SL_SOL_SOCKET,SL_SO_RCVTIMEO, &timeval, \ sizeof(timeval)); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Recv(iSoc,acBuffer,1470,0); if(lRetVal < 0 && lRetVal != SL_EAGAIN) { //error ASSERT_ON_ERROR(sl_Close(iSoc)); ASSERT_ON_ERROR(lRetVal); } UART_PRINT("\n\rPress any key to stop and display the statistics..."); // // Wait to receive a character over UART // MAP_UARTCharGet(CONSOLE); // //Get the Statistics collected in this time window // lRetVal = sl_WlanRxStatGet(&rxStatResp,0); if(lRetVal < 0) { //error ASSERT_ON_ERROR(sl_Close(iSoc)); ASSERT_ON_ERROR(lRetVal); } // //Printing the collected statistics // UART_PRINT("\n\n\n\r\t\t=========================================== \n \ \r"); UART_PRINT("\n\r\t\t\t\tRx Statistics \n\r"); UART_PRINT("\t\t=========================================== \n\r"); UART_PRINT("\n\n\rThe data sampled over %ld microsec\n\n\r", \ (unsigned int)(rxStatResp.GetTimeStamp - rxStatResp.StartTimeStamp)); UART_PRINT("Number of Valid Packets Received: %d\n\r", rxStatResp.ReceivedValidPacketsNumber); UART_PRINT("Number of Packets Received Packets with FCS: %d\n\r", rxStatResp.ReceivedFcsErrorPacketsNumber); UART_PRINT("Number of Packets Received Packets with PLCP: %d\n\n\r", \ rxStatResp.ReceivedAddressMismatchPacketsNumber); UART_PRINT("Average Rssi for management packets: %d\ \n\rAverage Rssi for other packets: %d\n\r", rxStatResp.AvarageMgMntRssi,rxStatResp.AvarageDataCtrlRssi); for(iIndex = 0 ; iIndex < SIZE_OF_RSSI_HISTOGRAM ; iIndex++) { UART_PRINT("Number of packets with RSSI in range %d dbm - %d dbm: %d\n\r", ((-40+(-8*iIndex))),((-40+(-8*(iIndex+1)))+1), rxStatResp.RssiHistogram[iIndex]); } UART_PRINT("\n\r"); //for(iIndex = 0 ; iIndex < NUM_OF_RATE_INDEXES ; iIndex++) iIndex = 0; { UART_PRINT("Number of Packets with Rate 1Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 2Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 5.5Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 11Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 6Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 9Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 12Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 18Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 24Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 36Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 48Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate 54Mbps : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_0 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_1 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_2 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_3 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_4 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_5 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_6 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); UART_PRINT("Number of Packets with Rate MCS_7 : %d\n\r", rxStatResp.RateHistogram[iIndex++]); } // //Stop Rx statistics collection // lRetVal = sl_WlanRxStatStop(); ASSERT_ON_ERROR(lRetVal); // //Close the socket // lRetVal = sl_Close(iSoc); ASSERT_ON_ERROR(lRetVal); return SUCCESS; }
//***************************************************************************** // //!This function creates rx filters. Two filters are defined in this example: //!(1) Drop incoming packets according to source MAC address //!(2) Drop incoming packets according to source IP address //! //! \param None //! //! \return 0 on success, -1 on failure //! //***************************************************************************** static int CreateFilters() { long lRetVal; SlrxFilterID_t FilterId = 0; SlrxFilterRuleType_t RuleType; SlrxFilterFlags_t FilterFlags; SlrxFilterRule_t Rule; SlrxFilterTrigger_t Trigger; SlrxFilterAction_t Action; unsigned char ucMacMask[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; unsigned char ucIPMask[4] = {0xFF, 0xFF, 0xFF, 0xFF}; /*************************************************************************/ /* Build filter to drop incoming packets according to source MAC address */ /*************************************************************************/ // //define filter as parent // Trigger.ParentFilterID = 0; // //no trigger to activate the filter. // Trigger.Trigger = NO_TRIGGER; // //connection state and role // Trigger.TriggerArgConnectionState.IntRepresentation = \ RX_FILTER_CONNECTION_STATE_STA_CONNECTED; Trigger.TriggerArgRoleStatus.IntRepresentation = RX_FILTER_ROLE_STA; // // header and Combination types are only supported. Combination for logical // AND/OR between two filters // RuleType = HEADER; Rule.HeaderType.RuleHeaderfield = MAC_SRC_ADDRESS_FIELD; memcpy( Rule.HeaderType.RuleHeaderArgsAndMask.RuleHeaderArgs.RxFilterDB6BytesRuleArgs[0], g_ucMacAddress , SL_MAC_ADDR_LEN); memcpy( Rule.HeaderType.RuleHeaderArgsAndMask.RuleHeaderArgsMask, ucMacMask, SL_MAC_ADDR_LEN); Rule.HeaderType.RuleCompareFunc = COMPARE_FUNC_EQUAL; // //Action // Action.ActionType.IntRepresentation = RX_FILTER_ACTION_DROP; FilterFlags.IntRepresentation = RX_FILTER_BINARY; lRetVal = sl_WlanRxFilterAdd(RuleType, FilterFlags, &Rule, &Trigger, &Action, &FilterId); ASSERT_ON_ERROR(lRetVal); /*************************************************************************/ /* Build filter to drop incoming packets according to source IP address */ /*************************************************************************/ // //define filter as parent // Trigger.ParentFilterID = 0; // //no trigger to activate the filter. // Trigger.Trigger = NO_TRIGGER; // //connection state and role // Trigger.TriggerArgConnectionState.IntRepresentation = \ RX_FILTER_CONNECTION_STATE_STA_CONNECTED; Trigger.TriggerArgRoleStatus.IntRepresentation = RX_FILTER_ROLE_STA; // // header and Combination types are only supported. Combination for logical // AND/OR between two filters // RuleType = HEADER; Rule.HeaderType.RuleHeaderfield = IPV4_SRC_ADRRESS_FIELD; memcpy(Rule.HeaderType.RuleHeaderArgsAndMask.RuleHeaderArgs.RxFilterDB4BytesRuleArgs[0], g_ucIpAddress , IP_ADDR_LENGTH); memcpy(Rule.HeaderType.RuleHeaderArgsAndMask.RuleHeaderArgsMask, ucIPMask, IP_ADDR_LENGTH); Rule.HeaderType.RuleCompareFunc = COMPARE_FUNC_EQUAL; // //Action // Action.ActionType.IntRepresentation = RX_FILTER_ACTION_DROP; FilterFlags.IntRepresentation = RX_FILTER_BINARY; lRetVal = sl_WlanRxFilterAdd(RuleType, FilterFlags, &Rule, &Trigger, &Action, &FilterId); ASSERT_ON_ERROR(lRetVal); return 0; }
//***************************************************************************** // //! This function opens a TCP socket in Listen mode and waits for an incoming //! TCP connection.. If a socket connection is established then the function //! will try to read 1000 TCP packets from the connected client. //! //! \param port number on which the server will be listening on //! //! \return 0 on success, -ve on Error. //! //***************************************************************************** static long BsdTcpServer(unsigned short Port) { SlSockAddrIn_t Addr; SlSockAddrIn_t LocalAddr; int indexCount,iAddrSize,SockID,iStatus,newSockID; long LoopCount = 0; long nonBlocking = 1; SlTimeval_t timeVal; for (indexCount=0 ; indexCount<BUF_SIZE ; indexCount++) { g_uBuf.cBsdBuf[indexCount] = (char)(indexCount % 10); } LocalAddr.sin_family = SL_AF_INET; LocalAddr.sin_port = sl_Htons((unsigned short)Port); LocalAddr.sin_addr.s_addr = 0; SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); ASSERT_ON_ERROR(SockID); iAddrSize = sizeof(SlSockAddrIn_t); iStatus = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, iAddrSize); if( iStatus < 0 ) { // error ASSERT_ON_ERROR(sl_Close(SockID)); ASSERT_ON_ERROR(iStatus); } iStatus = sl_Listen(SockID, 0); if( iStatus < 0 ) { sl_Close(SockID); ASSERT_ON_ERROR(iStatus); } iStatus = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, \ &nonBlocking, sizeof(nonBlocking)); newSockID = SL_EAGAIN; while( newSockID < 0 ) { newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr, (SlSocklen_t*)&iAddrSize); if( newSockID == SL_EAGAIN ) { MAP_UtilsDelay(80000); } else if( newSockID < 0 ) { ASSERT_ON_ERROR(sl_Close(SockID)); // error ASSERT_ON_ERROR(newSockID); } } timeVal.tv_sec = 1; timeVal.tv_usec = 0; if( newSockID >= 0 ) { iStatus = sl_SetSockOpt(newSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO, &timeVal, sizeof(timeVal)); ASSERT_ON_ERROR(iStatus); } while (LoopCount < PACKET_COUNT) { iStatus = sl_Recv(newSockID, g_uBuf.cBsdBuf, BUF_SIZE, 0); if( iStatus <= 0 ) { // error ASSERT_ON_ERROR(sl_Close(newSockID)); ASSERT_ON_ERROR(sl_Close(SockID)); ASSERT_ON_ERROR(iStatus); } LoopCount++; } ASSERT_ON_ERROR(sl_Close(newSockID)); ASSERT_ON_ERROR(sl_Close(SockID)); return 0; }
STATIC void wlan_set_channel (uint8_t channel) { wlan_obj.channel = channel; ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_CHANNEL, 1, &channel)); }
STATIC void wlan_set_mode (uint mode) { wlan_obj.mode = mode; ASSERT_ON_ERROR(sl_WlanSetMode(mode)); }
void wlan_sl_init (int8_t mode, const char *ssid, uint8_t ssid_len, uint8_t auth, const char *key, uint8_t key_len, uint8_t channel, uint8_t antenna, bool add_mac) { // stop the servers wlan_servers_stop(); // do a basic start wlan_first_start(); // close any active connections wlan_sl_disconnect(); // Remove all profiles ASSERT_ON_ERROR(sl_WlanProfileDel(0xFF)); // Enable the DHCP client uint8_t value = 1; ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE, 1, 1, &value)); // Set PM policy to normal ASSERT_ON_ERROR(sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0)); // Unregister mDNS services ASSERT_ON_ERROR(sl_NetAppMDNSUnRegisterService(0, 0)); // Stop the internal HTTP server sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); // Remove all 64 filters (8 * 8) _WlanRxFilterOperationCommandBuff_t RxFilterIdMask; memset ((void *)&RxFilterIdMask, 0 ,sizeof(RxFilterIdMask)); memset(RxFilterIdMask.FilterIdMask, 0xFF, 8); ASSERT_ON_ERROR(sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t))); #if MICROPY_HW_ANTENNA_DIVERSITY // set the antenna type wlan_set_antenna (antenna); #endif // switch to the requested mode wlan_set_mode(mode); // stop and start again (we need to in the propper mode from now on) wlan_reenable(mode); // Set Tx power level for station or AP mode // Number between 0-15, as dB offset from max power - 0 will set max power uint8_t ucPower = 0; if (mode == ROLE_AP) { ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_AP_TX_POWER, sizeof(ucPower), (unsigned char *)&ucPower)); // configure all parameters wlan_set_ssid (ssid, ssid_len, add_mac); wlan_set_security (auth, key, key_len); wlan_set_channel (channel); // set the country _u8* country = (_u8*)"EU"; ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE, 2, country)); SlNetCfgIpV4Args_t ipV4; ipV4.ipV4 = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 IP address ipV4.ipV4Mask = (_u32)SL_IPV4_VAL(255,255,255,0); // _u32 Subnet mask for this AP ipV4.ipV4Gateway = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 Default gateway address ipV4.ipV4DnsServer = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 DNS server address ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, sizeof(SlNetCfgIpV4Args_t), (_u8 *)&ipV4)); SlNetAppDhcpServerBasicOpt_t dhcpParams; dhcpParams.lease_time = 4096; // lease time (in seconds) of the IP Address dhcpParams.ipv4_addr_start = SL_IPV4_VAL(192,168,1,2); // first IP Address for allocation. dhcpParams.ipv4_addr_last = SL_IPV4_VAL(192,168,1,254); // last IP Address for allocation. ASSERT_ON_ERROR(sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID)); // Stop DHCP server before settings ASSERT_ON_ERROR(sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, sizeof(SlNetAppDhcpServerBasicOpt_t), (_u8* )&dhcpParams)); // set parameters ASSERT_ON_ERROR(sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID)); // Start DHCP server with new settings // stop and start again wlan_reenable(mode); } else { // STA and P2P modes ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, sizeof(ucPower), (unsigned char *)&ucPower)); // set connection policy to Auto + Fast (tries to connect to the last connected AP) ASSERT_ON_ERROR(sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 1, 0, 0, 0), NULL, 0)); } // set current time and date (needed to validate certificates) wlan_set_current_time (pyb_rtc_get_seconds()); // start the servers before returning wlan_servers_start(); }
//**************************************************************************** // //! \brief Configuring the Connection Policy //! //! This function configures different Connection Policy such as FAST,AUTO,OPEN //! //! \param[in] None //! //! \return 0 on success else error code //! //! \note // //**************************************************************************** static long SetConnectionPolicy() { unsigned char policyVal; long lRetVal = -1; /* Clear all stored profiles and reset the policies */ lRetVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(0,0,0,0,0), 0, 0); ASSERT_ON_ERROR(lRetVal); //Add Profile /* user needs to change SSID_NAME = "<Secured AP>" SECURITY_TYPE = SL_SEC_TYPE_WPA SECURITY_KEY = "<password>" and set the priority as per requirement to connect with a secured AP */ SlSecParams_t secParams; secParams.Key = SECURITY_KEY; secParams.KeyLen = strlen(SECURITY_KEY); secParams.Type = SECURITY_TYPE; lRetVal = sl_WlanProfileAdd(SSID_NAME,strlen(SSID_NAME),0,&secParams,0,1,0); ASSERT_ON_ERROR(lRetVal); //set AUTO policy lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1,0,0,0,0), &policyVal, 1 /*PolicyValLen*/); ASSERT_ON_ERROR(lRetVal); //wait until IP is acquired while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { _SlNonOsMainLoopTask(); } CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); // // ****** Put breakpoint here ****** // If control comes here- means device connected to AP in auto mode // // Disconnect from AP lRetVal = sl_WlanDisconnect(); if(0 == lRetVal) { // Wait while(IS_CONNECTED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } //delete profiles lRetVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(lRetVal); //set Auto SmartConfig policy lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1,0,0,0,1), &policyVal,0); ASSERT_ON_ERROR(lRetVal); // reset the NWP lRetVal = ResetNwp(); ASSERT_ON_ERROR(lRetVal); // wait for smart config to complete and device to connect to an AP //wait until IP is acquired while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { _SlNonOsMainLoopTask(); } CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); // // ****** Put breakpoint here ****** // If control comes here- means device connected to AP in smartconfig mode // /* Delete all profiles (0xFF) stored */ lRetVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(lRetVal); // reset the NWP lRetVal = ResetNwp(); ASSERT_ON_ERROR(lRetVal); /* Set connection policy to Fast, Device will connect to last connected AP. * This feature can be used to reconnect to AP */ lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION , \ SL_CONNECTION_POLICY(1,1,0,0,0), 0, 0); ASSERT_ON_ERROR(lRetVal); /* Connect to the open AP */ lRetVal = sl_WlanConnect(SSID_NAME, strlen(SSID_NAME), 0, 0, 0); ASSERT_ON_ERROR(lRetVal); //wait until IP is acquired while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { _SlNonOsMainLoopTask(); } CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); // Add unsecured AP profile with priority 6 (7 is highest) // Because of a limitation in SDK-0.5 which prevents the automatic addition // of the profile (fast), the application is required to explicitly add it. // The limitation shall be addressed in subsequent SDK release, and the below // lines for adding the profile can be removed then...! secParams.Key = ""; secParams.KeyLen = 0; secParams.Type = SL_SEC_TYPE_OPEN; lRetVal = sl_WlanProfileAdd((signed char*)SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0, 6, 0); ASSERT_ON_ERROR(lRetVal); // reset the NWP lRetVal = ResetNwp(); ASSERT_ON_ERROR(lRetVal); /* Wait for the connection to be established */ while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { _SlNonOsMainLoopTask(); } // // ****** Put breakpoint here ****** // If control comes here- means device connected to AP in FAST mode // //remove all policies lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(0,0,0,0,0), &policyVal,0); ASSERT_ON_ERROR(lRetVal); return SUCCESS; }
/* * Application's entry point */ int main(int argc, char** argv) { _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU These functions needs to be implemented in PAL */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) { CLI_Write(" Failed to configure the device in its default state \n\r"); } LOOP_FOREVER(); } /* * Assumption is that the device is configured in station mode already * and it is in its default state */ /* Initializing the CC3100 device */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); CLI_Write(" Starting smartconfig process \n\r"); /* Connect to our AP using SmartConfig method */ retVal = SmartConfigConnect(); if(retVal < 0) { CLI_Write(" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection established w/ AP and IP is acquired \n\r"); /* Delete all profiles */ retVal = sl_WlanProfileDel(WLAN_DEL_ALL_PROFILES); if(retVal < 0) LOOP_FOREVER(); return 0; }
//***************************************************************************** // //! UARTCommandHandler //! //! @brief The function handles commands arrived from CLI //! //! @param usBuffer is the receive buffer from the UART interface to PC //! //! @return 0 on success or error code on failure //! // //***************************************************************************** long UARTCommandHandler(char *usBuffer) { int iIndex = 0; int iParamcount = 0; long lRetVal = -1; signed char cStatus1 = 0; signed char cStatus2 = 0; if(usBuffer == NULL) { UART_PRINT("Null pointer\r\n"); return -1; } switch(usBuffer[1]) { //********************************************** // Case 01: Connect to default AP //********************************************** case UART_COMMAND_SIMPLE_CONFIG_START: if(!IS_CONNECTED(Network_IF_CurrentMCUState())) { LedTimerConfigNStart(); // Setting Acess Point's security parameters SecurityParams.Key = (signed char *)SECURITY_KEY; SecurityParams.KeyLen = strlen(SECURITY_KEY); SecurityParams.Type = SECURITY_TYPE; lRetVal = Network_IF_ConnectAP(SSID_NAME,SecurityParams); if(lRetVal < 0) { UART_PRINT("Error: %d Connecting to an AP.", lRetVal); return lRetVal; } } // // Disable the LED blinking Timer as Device is connected to AP // LedTimerDeinitStop(); // // Switch ON RED LED to indicate that Device acquired an IP // GPIO_IF_LedOn(MCU_IP_ALLOC_IND); DispatcherUartSendPacket((char*)pucUARTOKString, sizeof(pucUARTOKString)); break; //********************************************** // Case 02: Configure sender (source) email //********************************************** // TODO Phase 2: Include /* case UART_COMMAND_EMAIL_SOURCE: memset(serveruser,0,sizeof(serveruser)); memset(pcServerpass,0,sizeof(pcServerpass)); pcOfserveruser = &serveruser[0]; ofpcServerpass = &pcServerpass[0]; // '<' To maintain RFC 2821 format *pcOfserveruser++= '<'; iIndex = 2; while ((int)usBuffer[iIndex] != 0x0D) { //look for comma ',' for separation of params if((int)usBuffer[iIndex] == 44) { iParamcount++; } else { if(iParamcount==1) { //Enter smtp server username (email address) *pcOfserveruser++ = usBuffer[iIndex]; } if(iParamcount==2) { //Enter username's password *ofpcServerpass++ = usBuffer[iIndex]; } } iIndex++; } // '>' To maintain RFC 2821 format *pcOfserveruser++= '>'; *pcOfserveruser++= '\0'; *ofpcServerpass++= '\0'; //Set variables in smtp.c cStatus1 = smtpSetVariable(serveruser, USERNAME_VAR); cStatus2 = smtpSetVariable(pcServerpass, PASSWORD_VAR); //If error in return if(cStatus1 == 0 && cStatus2 == 0) { DispatcherUartSendPacket((char*)pucUARTOKString, sizeof(pucUARTOKString)); } else { DispatcherUartSendPacket((char*)putUARTErrorInputString, \ sizeof(putUARTErrorInputString)); } break; */ //********************************************** // Case 03: Configure sender (source) email //********************************************** case UART_COMMAND_EMAIL_HEADER: memset(pcEmailto,0,sizeof(pcEmailto)); pcOfemailto = &pcEmailto[0]; pcOfemailsubject = &pcEmailsubject[0]; // '<' To maintain RFC 2821 format *pcOfemailto++= '<'; iIndex = 2; while ((int)usBuffer[iIndex] != 0x0D && usBuffer[iIndex] != '\0') { //look for comma ',' for separation of params if((int)usBuffer[iIndex] == 44) { iParamcount++; } else { if(iParamcount==1) { //Enter destination email address *pcOfemailto++ = usBuffer[iIndex]; } if(iParamcount==2) { //Enter email subject *pcOfemailsubject++ = usBuffer[iIndex]; } } iIndex++; } // '>' To maintain RFC 2821 format *pcOfemailto++= '>'; *pcOfemailto++= '\0'; *pcOfemailsubject= '\0'; SlNetAppDestination_t destEmailAdd; memcpy(destEmailAdd.Email,pcEmailto,strlen(pcEmailto)+1); cStatus1 = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID,NETAPP_DEST_EMAIL, \ strlen(pcEmailto)+1, \ (unsigned char *)&destEmailAdd); SlNetAppEmailSubject_t emailSubject; memcpy(emailSubject.Value,pcEmailsubject,strlen(pcEmailsubject)+1); cStatus2 = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID,NETAPP_SUBJECT, \ strlen(pcEmailsubject)+1, \ (unsigned char *)&emailSubject); // Check for Error in setting the variables if(cStatus1 == 0 && cStatus2 == 0) { DispatcherUartSendPacket((char*)pucUARTOKString, \ sizeof(pucUARTOKString)); } else { DispatcherUartSendPacket((char*)putUARTErrorInputString, \ sizeof(putUARTErrorInputString)); } break; //********************************************** // Case 04: Record email message //********************************************** case UART_COMMAND_EMAIL_MESSAGE: pcOfemailmessage = &pcEmailmessage[0]; //Enter "Message" iIndex =3; while ((int)usBuffer[iIndex] != 0x0D && usBuffer[iIndex] != '\0') { if((int)usBuffer[iIndex] == 62) { iParamcount++; } else { if(iParamcount==0) { *pcOfemailmessage++ = usBuffer[iIndex]; } } iIndex++; } *pcOfemailmessage= '\0'; /* TODO here unsigned char is converting to char */ DispatcherUartSendPacket((char*)pucUARTOKString, \ sizeof(pucUARTOKString)); break; //********************************************** // Case 05: Send email message using configurations //********************************************** case UART_COMMAND_EMAIL_SEND: { // reset Orange LED state GPIO_IF_LedOff(MCU_SENDING_DATA_IND); // TODO: If no destination email given, default to hardcoded value SlNetAppEmailOpt_t eMailServerSetting; lRetVal = Network_IF_GetHostIP(GMAIL_HOST_NAME, &eMailServerSetting.Ip); if(lRetVal >= 0) { eMailServerSetting.Family = AF_INET; eMailServerSetting.Port = GMAIL_HOST_PORT; eMailServerSetting.SecurityMethod = SL_SO_SEC_METHOD_SSLV3; eMailServerSetting.SecurityCypher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_MD5; lRetVal = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID, \ NETAPP_ADVANCED_OPT, \ sizeof(SlNetAppEmailOpt_t), \ (unsigned char*)&eMailServerSetting); ASSERT_ON_ERROR(lRetVal); } else { UART_PRINT("Error:%d GetHostIP.", lRetVal); return -1; } g_cConnectStatus = sl_NetAppEmailConnect(); // If return -1, throw connect error if(g_cConnectStatus == -1) { DispatcherUartSendPacket((char*)pucUARTErrorSocketCreateString, \ sizeof(pucUARTErrorSocketCreateString)); } // If return -2, throw socket option error if(g_cConnectStatus == -2) { DispatcherUartSendPacket((char*)pucUARTErrorSocketOptionString, \ sizeof(pucUARTErrorSocketOptionString)); } if(g_cConnectStatus == 0) { SlNetAppServerError_t sEmailErrorInfo; long lRetCode = SL_EMAIL_ERROR_FAILED; if((lRetCode = sl_NetAppEmailSend(pcEmailto,pcEmailsubject, \ pcEmailmessage, \ &sEmailErrorInfo)) == SL_EMAIL_ERROR_NONE) { // Blink LED7 to indicate email has been sent for(iIndex=0 ;iIndex<5 ;iIndex++) { MAP_UtilsDelay(6000000); GPIO_IF_LedOff(MCU_SENDING_DATA_IND); MAP_UtilsDelay(6000000); GPIO_IF_LedOn(MCU_SENDING_DATA_IND); } DispatcherUartSendPacket((char*)putUARTFinishString, \ sizeof(putUARTFinishString)); } else { lRetVal = EmailHandleERROR(lRetCode,(char*)sEmailErrorInfo.Value); ASSERT_ON_ERROR(lRetVal); } } } break; case UART_COMMAND_SMART_CONFIG: GPIO_IF_LedOff(MCU_IP_ALLOC_IND); DispatcherUartSendPacket((char*)pucUARTSmartConfigString, \ sizeof(pucUARTSmartConfigString)); // Start LED blinking Timer LedTimerConfigNStart(); //Reset the Network Status before Entering Smart Config Network_IF_UnsetMCUMachineState(STATUS_BIT_CONNECTION); Network_IF_UnsetMCUMachineState(STATUS_BIT_IP_AQUIRED); // start smart config process lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); while (!(IS_CONNECTED(Network_IF_CurrentMCUState())) || \ !(IS_IP_ACQUIRED(Network_IF_CurrentMCUState()))) { MAP_UtilsDelay(100); } LedTimerDeinitStop(); GPIO_IF_LedOn(MCU_IP_ALLOC_IND); break; default: DispatcherUartSendPacket((char*)pucUARTErrorString, \ sizeof(pucUARTErrorString)); break; } return SUCCESS; }
//***************************************************************************** // //! UserInput //! //! This function //! 1. Function for reading the user input for UDP RX/TX //! //! \return none // //***************************************************************************** long UserInput() { int iInput = 0; char acCmdStore[50]; int lRetVal; int iRightInput = 0; unsigned long ulUserInputData = 0; UART_PRINT("Default settings: SSID Name: %s, PORT = %d, Packet Count = %d, " "Destination IP: %d.%d.%d.%d\n\r", SSID_NAME, g_uiPortNum, g_ulPacketCount, SL_IPV4_BYTE(g_ulDestinationIp,3), SL_IPV4_BYTE(g_ulDestinationIp,2), SL_IPV4_BYTE(g_ulDestinationIp,1), SL_IPV4_BYTE(g_ulDestinationIp,0)); do { UART_PRINT("\r\nOptions:\r\n1. Send UDP packets.\r\n2. Receive UDP " "packets.\r\n3. Settings.\r\n4. Exit\r\n"); UART_PRINT("Enter the option to use: "); lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. Display a prompt. // UART_PRINT("\n\n\rEnter Valid Input."); } else { iInput = (int)strtoul(acCmdStore,0,10); if(iInput == 1) { UART_PRINT("Run iperf command \"iperf.exe -u -s -i 1\" and " "press Enter\n\r"); // // Wait to receive a character over UART // MAP_UARTCharGet(CONSOLE); UART_PRINT("Sending UDP packets...\n\r"); // Before proceeding, please make sure to have a server // waiting on PORT_NUM lRetVal = BsdUdpClient(g_uiPortNum); ASSERT_ON_ERROR(lRetVal); } else if(iInput == 2) { UART_PRINT("Run iperf command \"iperf.exe -u -c %d.%d.%d.%d -i 1 " "-t 100000\" and press Enter\n\r", SL_IPV4_BYTE(g_ulIpAddr,3), SL_IPV4_BYTE(g_ulIpAddr,2), SL_IPV4_BYTE(g_ulIpAddr,1), SL_IPV4_BYTE(g_ulIpAddr,0)); // // Wait to receive a character over UART // MAP_UARTCharGet(CONSOLE); UART_PRINT("Receiving UDP packets...\n\r"); // After calling this function, you can start sending data // to CC3200 IP address on PORT_NUM lRetVal = BsdUdpServer(g_uiPortNum); ASSERT_ON_ERROR(lRetVal); } else if(iInput == 3) { iRightInput = 0; do { UART_PRINT("\n\rSetting Options:\n\r1. PORT\n\r2. Packet " "Count\n\r3. Destination IP\n\r4. Main Menu\r\n"); UART_PRINT("Enter the option to use: "); lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. Display prompt. // UART_PRINT("\n\n\rEnter Valid Input."); } else { iInput = (int)strtoul(acCmdStore,0,10); //SettingInput(iInput); switch(iInput) { case 1: do { UART_PRINT("Enter new Port: "); lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. // Display a prompt. // UART_PRINT("\n\rEnter Valid Input."); iRightInput = 0; } else { ulUserInputData = (int)strtoul(acCmdStore,0,10); if(ulUserInputData <= 0 || ulUserInputData > 65535) { UART_PRINT("\n\rWrong Input"); iRightInput = 0; } else { g_uiPortNum = ulUserInputData; iRightInput = 1; } } UART_PRINT("\r\n"); }while(!iRightInput); iRightInput = 0; break; case 2: do { UART_PRINT("Enter Packet Count: "); lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. // Display a prompt. // UART_PRINT("\n\rEnter Valid Input."); iRightInput = 0; } else { ulUserInputData = (int)strtoul(acCmdStore,0,10); if(ulUserInputData <= 0 || ulUserInputData > 9999999) { UART_PRINT("\n\rWrong Input"); iRightInput = 0; } else { g_ulPacketCount = ulUserInputData; iRightInput = 1; } } UART_PRINT("\r\n"); }while(!iRightInput); iRightInput = 0; break; case 3: do { UART_PRINT("Enter Destination IP: "); lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal == 0) { // // No input. Just an enter pressed probably. // Display a prompt. // UART_PRINT("\n\rEnter Valid Input."); iRightInput = 0; } else { if(IpAddressParser(acCmdStore) < 0) { UART_PRINT("\n\rWrong Input"); iRightInput = 0; } else { iRightInput = 1; } } UART_PRINT("\r\n"); }while(!iRightInput); iRightInput = 0; break; case 4: iRightInput = 1; break; default: break; } } }while(!iRightInput); } else if(iInput == 4) { break; } else { UART_PRINT("\n\n\rWrong Input"); } } UART_PRINT("\n\r"); }while(1); return 0 ; }
/* * Application's entry point */ int main(int argc, char** argv) { _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) CLI_Write((_u8 *)" Failed to configure the device in its default state \n\r"); LOOP_FOREVER(); } CLI_Write((_u8 *)" Device is configured in default state \n\r"); /* * Assumption is that the device is configured in station mode already * and it is in its default state */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write((_u8 *)" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write((_u8 *)" Device started as STATION \n\r"); /* Connecting to WLAN AP */ retVal = establishConnectionWithAP(); if(retVal < 0) { CLI_Write((_u8 *)" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write((_u8 *)" Connection established w/ AP and IP is acquired \n\r"); CLI_Write((_u8 *)" Pinging...! \n\r"); retVal = checkLanConnection(); if(retVal < 0) { CLI_Write((_u8 *)" Device couldn't connect to LAN \n\r"); LOOP_FOREVER(); } CLI_Write((_u8 *)" Device successfully connected to the LAN\r\n"); retVal = checkInternetConnection(); if(retVal < 0) { CLI_Write((_u8 *)" Device couldn't connect to the internet \n\r"); LOOP_FOREVER(); } CLI_Write((_u8 *)" Device successfully connected to the internet \n\r"); return 0; }
//**************************************************************************** // //! \brief Opening a UDP server side socket and receiving data //! //! This function opens a UDP socket in Listen mode and waits for an incoming //! UDP connection. //! If a socket connection is established then the function will try to //! read 1000 UDP packets from the connected client. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, Negative value on Error. // //**************************************************************************** int BsdUdpServer(unsigned short usPort) { SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; int iCounter; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; short sTestBufLen; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the UDP server socket address sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short)usPort); sLocalAddr.sin_addr.s_addr = 0; iAddrSize = sizeof(SlSockAddrIn_t); // creating a UDP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( iSockID < 0 ) { // error ASSERT_ON_ERROR(UCP_SERVER_FAILED); } // binding the UDP socket to the UDP server address iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize); if( iStatus < 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_SERVER_FAILED); } // no listen or accept is required as UDP is connectionless protocol /// waits for 1000 packets from a UDP client while (lLoopCount < g_ulPacketCount) { iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0, ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize ); if( iStatus < 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_SERVER_FAILED); } lLoopCount++; } UART_PRINT("Recieved %u packets successfully\n\r",g_ulPacketCount); //closing the socket after receiving 1000 packets sl_Close(iSockID); return SUCCESS; }
//***************************************************************************** // //! This funtion includes the following steps: //! -open a user file for writing //! -write "Old MacDonalds" child song 37 times to get just below a 64KB file //! -close the user file //! //! /param[out] ulToken : file token //! /param[out] lFileHandle : file handle //! //! /return 0:Success, -ve: failure // //***************************************************************************** long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle) { long lRetVal = -1; int iLoopCnt = 0; // // create a user file // lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME, FS_MODE_OPEN_CREATE(65536, \ _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE), ulToken, lFileHandle); if(lRetVal < 0) { // // File may already be created // lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0); ASSERT_ON_ERROR(lRetVal); } else { // // close the user file // lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0); if (SL_RET_CODE_OK != lRetVal) { ASSERT_ON_ERROR(FILE_CLOSE_ERROR); } } // // open a user file for writing // lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME, FS_MODE_OPEN_WRITE, ulToken, lFileHandle); if(lRetVal < 0) { lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0); ASSERT_ON_ERROR(FILE_OPEN_WRITE_FAILED); } // // write "Old MacDonalds" child song as many times to get just below a 64KB file // for (iLoopCnt = 0; iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald)); iLoopCnt++) { lRetVal = sl_FsWrite(*lFileHandle, (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)), (unsigned char *)gaucOldMacDonald, sizeof(gaucOldMacDonald)); if (lRetVal < 0) { lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0); ASSERT_ON_ERROR(FILE_WRITE_FAILED); } } // // close the user file // lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0); if (SL_RET_CODE_OK != lRetVal) { ASSERT_ON_ERROR(FILE_CLOSE_ERROR); } return SUCCESS; }
int connectToAccessPoint(){ long lRetVal = -1; GPIO_IF_LedConfigure(LED1|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); lRetVal = InitializeAppVariables(); ASSERT_ON_ERROR(lRetVal); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state \n\r"); return lRetVal; } UART_PRINT("Device is configured in default state \n\r"); CLR_STATUS_BIT_ALL(g_ulStatus); /// // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { UART_PRINT("Failed to start the device \n\r"); return lRetVal; } UART_PRINT("Device started as STATION \n\r"); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } UART_PRINT("Connection established w/ AP and IP is aquired \n\r"); return 0; }
//***************************************************************************** // //! Network_IF_ConnectAP Connect to an Access Point using the specified SSID //! //! \param[in] pcSsid is a string of the AP's SSID //! \param[in] SecurityParams is Security parameter for AP //! //! \return On success, zero is returned. On error, -ve value is returned // //***************************************************************************** long Network_IF_ConnectAP(char *pcSsid, SlSecParams_t SecurityParams) { #ifndef NOTERM char acCmdStore[128]; unsigned short usConnTimeout; unsigned char ucRecvdAPDetails; #endif long lRetVal; unsigned long ulIP = 0; unsigned long ulSubMask = 0; unsigned long ulDefGateway = 0; unsigned long ulDns = 0; // // Disconnect from the AP // Network_IF_DisconnectFromAP(); // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait for ~10 sec to check if connection to desire AP succeeds // while(g_usConnectIndex < 15) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(IS_CONNECTED(g_ulStatus) && IS_IP_ACQUIRED(g_ulStatus)) { break; } g_usConnectIndex++; } #ifndef NOTERM // // Check and loop until AP connection successful, else ask new AP SSID name // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { // // Disconnect the previous attempt // Network_IF_DisconnectFromAP(); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); UART_PRINT("Device could not connect to %s\n\r",pcSsid); do { ucRecvdAPDetails = 0; UART_PRINT("\n\r\n\rPlease enter the AP(open) SSID name # "); // // Get the AP name to connect over the UART // lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal > 0) { // remove start/end spaces if any lRetVal = TrimSpace(acCmdStore); // // Parse the AP name // strncpy(pcSsid, acCmdStore, lRetVal); if(pcSsid != NULL) { ucRecvdAPDetails = 1; pcSsid[lRetVal] = '\0'; } } }while(ucRecvdAPDetails == 0); // // Reset Security Parameters to OPEN security type // SecurityParams.Key = (signed char *)""; SecurityParams.KeyLen = 0; SecurityParams.Type = SL_SEC_TYPE_OPEN; UART_PRINT("\n\rTrying to connect to AP: %s ...\n\r",pcSsid); // // Get the current timer tick and setup the timeout accordingly // usConnTimeout = g_usConnectIndex + 15; // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait ~10 sec to check if connection to specifed AP succeeds // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(g_usConnectIndex >= usConnTimeout) { break; } g_usConnectIndex++; } } #endif // // Put message on UART // UART_PRINT("\n\rDevice has connected to %s\n\r",pcSsid); // // Get IP address // lRetVal = Network_IF_IpConfigGet(&ulIP,&ulSubMask,&ulDefGateway,&ulDns); ASSERT_ON_ERROR(lRetVal); // // Send the information // UART_PRINT("Device IP Address is %d.%d.%d.%d \n\r\n\r", SL_IPV4_BYTE(ulIP, 3),SL_IPV4_BYTE(ulIP, 2), SL_IPV4_BYTE(ulIP, 1),SL_IPV4_BYTE(ulIP, 0)); return 0; }
int main(int argc, char** argv) { SlSockAddrIn_t Addr = {0}; _u32 cipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; _u32 googleIP = 0; _u8 method = SL_SO_SEC_METHOD_SSLV3; _i32 AddrSize = -1; _i32 g_SockID = -1; _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU These functions needs to be implemented in PAL */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) { CLI_Write(" Failed to configure the device in its default state \n\r"); } LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); /* * Assumption is that the device is configured in station mode already * and it is in its default state */ /* Initializing the CC3100 device */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device started as STATION \n\r"); /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ retVal = establishConnectionWithAP(); if(retVal < 0) { CLI_Write(" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection established w/ AP and IP is acquired \n\r"); /* Update the CC3100 time */ retVal = SetTime(); if (retVal < 0) { CLI_Write(" Failed to set the device time \n\r"); LOOP_FOREVER(); } CLI_Write(" Establishing secure connection w/ google server \n\r"); /* get the server name via a DNS request */ retVal = sl_NetAppDnsGetHostByName(g_Google, pal_Strlen(g_Google), &googleIP, SL_AF_INET); if( retVal < 0 ) { CLI_Write(" Failed to get the IP address \n\r"); LOOP_FOREVER(); } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(googleIP); AddrSize = sizeof(SlSockAddrIn_t); /* opens a secure socket */ g_SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( g_SockID < 0 ) { CLI_Write(" Failed to open socket \n\r"); LOOP_FOREVER(); } /* configure the socket as SSLV3.0 */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket as RSA with RC4 128 SHA */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &cipher, sizeof(cipher)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket with GOOGLE CA certificate-for server verification*/ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT, pal_Strlen(SL_SSL_CA_CERT)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* connect to the peer device - GMail server */ retVal = sl_Connect(g_SockID, ( SlSockAddr_t *)&Addr, AddrSize); if (retVal < 0 ) { CLI_Write(" Failed to connect w/ google server \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection w/ google server established successfully \n\r"); /* Stop the CC3100 device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) LOOP_FOREVER(); return 0; }
/*! \brief This function configure the SimpleLink device in its default state. It: - Sets the mode to STATION - Configures connection policy to Auto and AutoSmartConfig - Deletes all the stored profiles - Enables DHCP - Disables Scan policy - Sets Tx power to maximum - Sets power policy to normal - Unregisters mDNS services - Remove all filters \param[in] none \return On success, zero is returned. On error, negative is returned */ static _i32 configureSimpleLinkToDefaultState() { SlVersionFull ver = {0}; _WlanRxFilterOperationCommandBuff_t RxFilterIdMask = {0}; _u8 val = 1; _u8 configOpt = 0; _u8 configLen = 0; _u8 power = 0; _i32 retVal = -1; _i32 mode = -1; mode = sl_Start(0, 0, 0); ASSERT_ON_ERROR(mode); /* If the device is not in station-mode, try configuring it in station-mode */ if (ROLE_STA != mode) { if (ROLE_AP == mode) { /* If the device is in AP mode, we need to wait for this event before doing anything */ while(!IS_IP_ACQUIRED(g_Status)) { _SlNonOsMainLoopTask(); } } /* Switch to STA role and restart */ retVal = sl_WlanSetMode(ROLE_STA); ASSERT_ON_ERROR(retVal); retVal = sl_Stop(SL_STOP_TIMEOUT); ASSERT_ON_ERROR(retVal); retVal = sl_Start(0, 0, 0); ASSERT_ON_ERROR(retVal); /* Check if the device is in station again */ if (ROLE_STA != retVal) { /* We don't want to proceed if the device is not coming up in station-mode */ ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE); } } /* Get the device's version-information */ configOpt = SL_DEVICE_GENERAL_VERSION; configLen = sizeof(ver); retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (unsigned char *)(&ver)); ASSERT_ON_ERROR(retVal); /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */ retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0); ASSERT_ON_ERROR(retVal); /* Remove all profiles */ retVal = sl_WlanProfileDel(0xFF); ASSERT_ON_ERROR(retVal); /* * Device in station-mode. Disconnect previous connection if any * The function returns 0 if 'Disconnected done', negative number if already disconnected * Wait for 'disconnection' event if 0 is returned, Ignore other return-codes */ retVal = sl_WlanDisconnect(); if(0 == retVal) { /* Wait */ while(IS_CONNECTED(g_Status)) { _SlNonOsMainLoopTask(); } } /* Enable DHCP client*/ retVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val); ASSERT_ON_ERROR(retVal); /* Disable scan */ configOpt = SL_SCAN_POLICY(0); retVal = sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0); ASSERT_ON_ERROR(retVal); /* Set Tx power level for station mode Number between 0-15, as dB offset from max power - 0 will set maximum power */ power = 0; retVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, &power); ASSERT_ON_ERROR(retVal); /* Set PM policy to normal */ retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0); ASSERT_ON_ERROR(retVal); /* Unregister mDNS services */ retVal = sl_NetAppMDNSUnRegisterService(0, 0); ASSERT_ON_ERROR(retVal); /* Remove all 64 filters (8*8) */ pal_Memset(RxFilterIdMask.FilterIdMask, 0xFF, 8); retVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t)); ASSERT_ON_ERROR(retVal); retVal = sl_Stop(SL_STOP_TIMEOUT); ASSERT_ON_ERROR(retVal); retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); return retVal; /* Success */ }
int main(void) { /* Init board */ BoardInit(); /* Init GPIO */ InitGPIO(); /* Init UART */ MAP_PRCMPeripheralClkEnable(PRCM_UARTA0, PRCM_RUN_MODE_CLK); InitTerm(); /* Init I2C */ I2C_IF_Open(I2C_MASTER_MODE_FST); /* Init the internet! */ // http://azug.minpet.unibas.ch/~lukas/bricol/ti_simplelink/resources/swru368.pdf SECTION 10 dhcpParams.lease_time = 1000; dhcpParams.ipv4_addr_start = 0xc0a80102; dhcpParams.ipv4_addr_last = 0xc0a801fe; sl_Start(NULL,NULL,NULL); MAP_UtilsDelay(8000000); // config IP etc ipV4.ipV4 = 0xc0a80101; ipV4.ipV4Mask = 0xFFFFFF00; ipV4.ipV4Gateway = 0xc0a80101; ipV4.ipV4DnsServer = 0xc0a80101; sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, 1 ,sizeof(SlNetCfgIpV4Args_t), (unsigned char*) &ipV4); sl_WlanSetMode(ROLE_AP); // config SSID sl_WlanSet(SL_WLAN_CFG_AP_ID,WLAN_AP_OPT_SSID, strlen(myssid), (unsigned char*) myssid); sl_Stop(100); sl_Start(NULL,NULL,NULL); // start DHCP server sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID); sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, outLen,(unsigned char*) &dhcpParams); sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID); //Stop Internal HTTP Serve long lRetVal = -1; lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); /* Finished init the internet! */ setRLED(); /* Wait for operator */ while(!readDIP1()); clearRLED(); /* Init IMU (alongside timers and interrupt */ imu_setup(); /* Init odometers */ odometer_setup(); set_controller_parameters(kp, ki, kd); set__odo_controller_parameters(kp_odo, ki_odo, kd_odo); /* Init motors (alongside motor GPIO, timers and interrupt */ motorSetup(); controller_setup(); odometer_controller_setup(); // MUST be the last init called! while(1) { _SlNonOsMainLoopTask(); } }
//***************************************************************************** // //! Function to connect to server and download the requested file //! //! \param none //! //! \return Error-code or SUCCESS //! //***************************************************************************** static long ServerFileDownload() { long lRetVal = -1; struct sockaddr_in addr; HTTPCli_Struct cli; // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its desired state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) { UART_PRINT("Failed to configure the device in its default state, " "Error-code: %d\n\r", DEVICE_NOT_IN_STATION_MODE); } LOOP_FOREVER(); } UART_PRINT("Device is configured in default state \n\r"); // // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { ASSERT_ON_ERROR(DEVICE_START_FAILED); } UART_PRINT("Device started as STATION \n\r"); // Connecting to WLAN AP - Set with static parameters defined at the top // After this call we will be connected and have IP address lRetVal = WlanConnect(); UART_PRINT("Connected to the AP: %s\r\n", SSID_NAME); lRetVal = sl_NetAppDnsGetHostByName((signed char *)HOST_NAME, strlen((const char *)HOST_NAME), &g_ulDestinationIP,SL_AF_INET); if(lRetVal < 0) { ASSERT_ON_ERROR(GET_HOST_IP_FAILED); } // Set up the input parameters for HTTP Connection addr.sin_family = AF_INET; addr.sin_port = htons(HOST_PORT); addr.sin_addr.s_addr = sl_Htonl(g_ulDestinationIP); // Testing HTTPCli open call: handle, address params only HTTPCli_construct(&cli); lRetVal = HTTPCli_connect(&cli, (struct sockaddr *)&addr, 0, NULL); if (lRetVal < 0) { UART_PRINT("Connection to server failed\n\r"); ASSERT_ON_ERROR(SERVER_CONNECTION_FAILED); } else { UART_PRINT("Connection to server created successfully\r\n"); } // Download the file, verify the file and replace the exiting file lRetVal = GetData(&cli); if(lRetVal < 0) { UART_PRINT("Device couldn't download the file from the server\n\r"); } HTTPCli_destruct(&cli); return SUCCESS; }
//**************************************************************************** // //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is //! Placed, Force it to AP mode //! //! \return 0 - Success //! -1 - Failure // //**************************************************************************** long ConnectToNetwork() { long lRetVal = -1; unsigned int uiConnectTimeoutCnt =0; // staring simplelink lRetVal = sl_Start(NULL,NULL,NULL); ASSERT_ON_ERROR( lRetVal); // Device is in AP Mode and Force AP Jumper is not Connected if(ROLE_STA != lRetVal && g_uiDeviceModeConfig == ROLE_STA ) { if (ROLE_AP == lRetVal) { // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } } //Switch to STA Mode lRetVal = ConfigureMode(ROLE_STA); ASSERT_ON_ERROR( lRetVal); } //Device is in STA Mode and Force AP Jumper is Connected if(ROLE_AP != lRetVal && g_uiDeviceModeConfig == ROLE_AP ) { //Switch to AP Mode lRetVal = ConfigureMode(ROLE_AP); ASSERT_ON_ERROR( lRetVal); } //No Mode Change Required if(lRetVal == ROLE_AP) { //waiting for the AP to acquire IP address from Internal DHCP Server // If the device is in AP mode, we need to wait for this event // before doing anything while(!IS_IP_ACQUIRED(g_ulStatus)) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #endif } //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); char cCount=0; //Blink LED 3 times to Indicate AP Mode for(cCount=0;cCount<3;cCount++) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(400); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(400); } char ssid[32]; unsigned short len = 32; unsigned short config_opt = WLAN_AP_OPT_SSID; sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char* )ssid); UART_PRINT("\n\r Connect to : \'%s\'\n\r\n\r",ssid); } else { //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); ASSERT_ON_ERROR( lRetVal); //waiting for the device to Auto Connect while(uiConnectTimeoutCnt<AUTO_CONNECTION_TIMEOUT_COUNT && ((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))) { //Turn RED LED On GPIO_IF_LedOn(MCU_RED_LED_GPIO); osi_Sleep(50); //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); osi_Sleep(50); uiConnectTimeoutCnt++; } //Couldn't connect Using Auto Profile if(uiConnectTimeoutCnt == AUTO_CONNECTION_TIMEOUT_COUNT) { //Blink Red LED to Indicate Connection Error GPIO_IF_LedOn(MCU_RED_LED_GPIO); CLR_STATUS_BIT_ALL(g_ulStatus); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { MAP_UtilsDelay(500); } } //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); g_iInternetAccess = ConnectionTest(); } return SUCCESS; }
//***************************************************************************** // //! This function demonstrates how certificate can be used with SSL. //! The procedure includes the following steps: //! 1) connect to an open AP //! 2) get the server name via a DNS request //! 3) define all socket options and point to the CA certificate //! 4) connect to the server via TCP //! //! \param None //! //! \return 0 on success else error code //! \return LED1 is turned solid in case of success //! LED2 is turned solid in case of failure //! //***************************************************************************** static long ssl() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_SSLV3; unsigned int uiIP,uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; long lRetVal = -1; int iSockID; GPIO_IF_LedConfigure(LED1|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); lRetVal = InitializeAppVariables(); ASSERT_ON_ERROR(lRetVal); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state \n\r"); return lRetVal; } UART_PRINT("Device is configured in default state \n\r"); CLR_STATUS_BIT_ALL(g_ulStatus); /// // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { UART_PRINT("Failed to start the device \n\r"); return lRetVal; } UART_PRINT("Device started as STATION \n\r"); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } UART_PRINT("Connection established w/ AP and IP is aquired \n\r"); //Set time of the device for certificate verification. lRetVal = set_time(); if(lRetVal < 0) { UART_PRINT("Unable to set time in the device"); return lRetVal; } lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { UART_PRINT("Device couldn't retrive the host name \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // opens a secure socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSockID < 0 ) { UART_PRINT("Device unable to create secure socket \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // configure the socket as SSLV3.0 // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\ sizeof(ucMethod)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket as RSA with RC4 128 SHA // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\ sizeof(uiCipher)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket with GOOGLE CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CA_FILE_NAME, \ SL_SSL_CA_CERT_FILE_NAME, \ strlen(SL_SSL_CA_CERT_FILE_NAME)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SO_SECURE_DOMAIN_NAME_VERIFICATION, \ g_Host, strlen((const char *)g_Host)); if( lRetVal < 0 ) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } /* connect to the peer device - Google server */ lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { UART_PRINT("Device couldn't connect to Google server \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); return SUCCESS; }
/*! \brief This function displays the filter options and read parameters to create the filter. \param[in] none \return 0 for success, -ve otherwise \note \warning */ static _i32 FiltersMenu() { _i32 selection = -1; _i8 equalYesNo = -1; _i8 dropYesNo = -1; _u32 frameTypeLength = 0; _i32 fatherId = 0; _u32 macAddress[MAC_ADDR_LENGTH] = {'\0'}; _u32 ipAddress[IP_ADDR_LENGTH] = {'\0'}; _u8 filterData[MAC_ADDR_LENGTH] = {'\0'}; _i32 retVal = -1; _i32 idx = 0; printf("\nPlease select a filter parameter:\n"); printf("\n1. Source MAC address\n"); printf("2. Destination MAC address\n"); printf("3. BSSID\n"); printf("4. Frame type\n"); printf("5. Frame subtype\n"); printf("6. Source IP address\n"); printf("7. Destination IP address\n"); printf("8. Packet length\n"); printf("9. Remove filter and exit menu\n"); printf("10. Enable filter and exit menu\n"); printf("Selection: \n"); while(1) { fflush(stdin); scanf_s("%d",&selection, sizeof(selection)); switch(selection) { case 1: case 2: case 3: PrintFilterType(selection); printf("\nEnter the MAC address (xx:xx:xx:xx:xx:xx): \n"); fflush(stdin); scanf("%2x:%2x:%2x:%2x:%2x:%2x", &macAddress[0], &macAddress[1], &macAddress[2], &macAddress[3], &macAddress[4], &macAddress[5]); for(idx = 0 ; idx < MAC_ADDR_LENGTH ; idx++ ) { filterData[idx] = (_u8)macAddress[idx]; } break; case 4: PrintFilterType(selection); printf("Enter the frame type byte: \n"); fflush(stdin); scanf_s("%2x",&frameTypeLength, sizeof(frameTypeLength)); filterData[0] = (_u8)frameTypeLength; break; case 5: PrintFilterType(selection); printf("\nCreating a frame subtype filter requires a parent frame type filter\r\n"); printf("Enter the frame type byte: \n"); fflush(stdin); scanf_s("%2x",&frameTypeLength, sizeof(frameTypeLength)); filterData[0] = (_u8)frameTypeLength; break; case 6: case 7: PrintFilterType(selection); printf("Enter the IP address: \n"); fflush(stdin); scanf("%u.%u.%u.%u",&ipAddress[0],&ipAddress[1],&ipAddress[2], &ipAddress[3]); for(idx = 0 ; idx < IP_ADDR_LENGTH ; idx++ ) { filterData[idx] = (_u8)ipAddress[idx]; } break; case 8: PrintFilterType(selection); printf("Enter desired length in Bytes (Maximum = 1472): \n"); fflush(stdin); scanf_s("%u",&frameTypeLength, sizeof(frameTypeLength)); *(_u32 *)filterData = SWAP_UINT32(frameTypeLength); printf("Target what lengths? (h - Higher than %u | l - Lower than %u): \n", frameTypeLength,frameTypeLength); fflush(stdin); scanf_s("%c",&equalYesNo, sizeof(equalYesNo)); printf("Drop packets or not? (y/n): \n"); fflush(stdin); scanf_s("%c",&dropYesNo, sizeof(dropYesNo)); printf("Enter filter ID of parent. Otherwise 0: \n"); fflush(stdin); scanf_s("%u", &fatherId, sizeof(fatherId)); retVal= RxFiltersExample('1',selection,filterData,equalYesNo,dropYesNo, (_i8)fatherId); ASSERT_ON_ERROR(retVal); printf("\nPlease select a filter parameter:\n"); printf("\n1. Source MAC address\n"); printf("2. Destination MAC address\n"); printf("3. BSSID\n"); printf("4. Frame type\n"); printf("5. Frame subtype\n"); printf("6. Source IP address\n"); printf("7. Destination IP address\n"); printf("8. Packet length\n"); printf("9. Remove filter and exit menu\n"); printf("10. Enable filter and exit menu\n"); printf("\nSelection: \n"); continue; break; case 9: retVal = RxFiltersExample('2',0,NULL,0,0,0); ASSERT_ON_ERROR(retVal); return SUCCESS; break; case 10: retVal = RxFiltersExample('3',0,NULL,0,0,0); ASSERT_ON_ERROR(retVal); return SUCCESS; break; default: continue; } printf("Equal or not equal? (y/n): \n"); fflush(stdin); scanf_s("%c",&equalYesNo, sizeof(equalYesNo)); printf("Drop the packet? (y/n): \n"); fflush(stdin); scanf_s("%c",&dropYesNo, sizeof(dropYesNo)); printf("Enter filter ID of parent. Otherwise 0:: \n"); fflush(stdin); scanf_s("%u", &fatherId, sizeof(fatherId)); retVal = RxFiltersExample('1', selection, filterData, equalYesNo, dropYesNo, (_i8)fatherId); if((retVal < 0) && (retVal != INVALID_PARENT_FILTER_ID)) { return retVal; } printf("\nPlease select a filter parameter:\n"); printf("\n1. Source MAC address\n"); printf("2. Destination MAC address\n"); printf("3. BSSID\n"); printf("4. Frame type\n"); printf("5. Frame subtype\n"); printf("6. Source IP address\n"); printf("7. Destination IP address\n"); printf("8. Packet length\n"); printf("9. Remove and exit\n"); printf("10. Enable and exit\n"); printf("Selection:\n"); } return SUCCESS; }