//***************************************************************************** // // Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ // // // 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. // //***************************************************************************** //***************************************************************************** // // Application Name - HTTP Server // Application Overview - This is a sample application demonstrating // interaction between HTTP Client(Browser) and // SimpleLink Device.The SimpleLink device runs an // HTTP Server and user can interact using web browser. // Application Details - // http://processors.wiki.ti.com/index.php/CC32xx_HTTP_Server // or // doc\examples\CC32xx_HTTP_Server.pdf // //***************************************************************************** //**************************************************************************** // //! \addtogroup httpserver //! @{ // //**************************************************************************** // Standard includes #include #include // Simplelink includes #include "simplelink.h" #include "netcfg.h" //driverlib includes #include "hw_ints.h" #include "hw_types.h" #include "hw_memmap.h" #include "interrupt.h" #include "utils.h" #include "pin.h" #include "uart.h" #include "rom.h" #include "rom_map.h" #include "prcm.h" //Free_rtos/ti-rtos includes #include "osi.h" // common interface includes #include "gpio_if.h" #include "uart_if.h" #include "common.h" #include "smartconfig.h" #include "pinmux.h" // HTTP Client lib #include #include // // JSON Parser #include "jsmn.h" #define APPLICATION_NAME "HTTP Server" #define APPLICATION_VERSION "1.1.1" #define AP_SSID_LEN_MAX (33) #define ROLE_INVALID (-5) #define LED_STRING "LED" #define LED1_STRING "LED1_" #define LED2_STRING ",LED2_" #define LED_ON_STRING "ON" #define LED_OFF_STRING "OFF" #define OOB_TASK_PRIORITY (1) #define OSI_STACK_SIZE (2048) #define SH_GPIO_3 (3) /* P58 - Device Mode */ #define ROLE_INVALID (-5) #define AUTO_CONNECTION_TIMEOUT_COUNT (50) /* 5 Sec */ // Application specific status/error codes typedef enum{ // Choosing -0x7D0 to avoid overlap w/ host-driver's error codes LAN_CONNECTION_FAILED = -0x7D0, INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1, DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1, STATUS_CODE_MAX = -0xBB8 }e_AppStatusCodes; //***************************************************************************** // GLOBAL VARIABLES -- Start //***************************************************************************** volatile unsigned long g_ulStatus = 0;//SimpleLink Status unsigned long g_ulPingPacketsRecv = 0; //Number of Ping Packets received unsigned long g_ulGatewayIP = 0; //Network Gateway IP address unsigned char g_ucConnectionSSID[SSID_LEN_MAX+1]; //Connection SSID unsigned char g_ucConnectionBSSID[BSSID_LEN_MAX]; //Connection BSSID unsigned char POST_token[] = "__SL_P_ULD"; unsigned char GET_token[] = "__SL_G_ULD"; int g_iSimplelinkRole = ROLE_INVALID; signed int g_uiIpAddress = 0; unsigned char g_ucSSID[AP_SSID_LEN_MAX]; #if defined(ccs) extern void (* const g_pfnVectors[])(void); #endif #if defined(ewarm) extern uVectorEntry __vector_table; #endif //***************************************************************************** // const char str1[]={"AP"}; const char str2[]={"STA"}; // GLOBAL VARIABLES -- End //***************************************************************************** volatile unsigned char ucChar[600]="\0"; volatile char ucBuffer[30]="\0"; volatile int flag=-1; volatile int status=-1; int sMode=-1; unsigned int uiCounter=0; struct Wifi_param { unsigned char mode[5]; unsigned char ssid[32]; unsigned char pass[25]; char host[70]; char json[600]; char posturi[40]; char geturi[40]; } w1; // typedef enum //check { STA_MODE=0, AP_MODE=1, NOT_SELECTED }mode; typedef enum { CONNECT_AP=0, CONNECT_HTTP, HTTPPOST, HTTPGET, DISCONNECT, RECONNECT }WifiStation; typedef enum {Mode=0,Ssid,Pass,ConnectAP,ConnectHttp,HostName,PostUri,GetUri,Json,Httppost,Httpget,Disconnect,Reconnect}hClient ; //typedef enum {}hServer; const char checkBuffer[13][13]={"mode","ssid","pass","connectAP","connecthttp","host","posturi","geturi","json","httppost","httpget","disconnect","reconnect"}; int matchBuffer(const char *str) { int i=0; for(i=0;i<13;i++) { if(!strncmp(str,checkBuffer[i],strlen(checkBuffer[i]))) return i; } return -1; } //***************************************************************************** // Variable related to Connection status //***************************************************************************** volatile unsigned short g_usMCNetworkUstate = 0; int g_uiSimplelinkRole = ROLE_INVALID; unsigned int g_uiDeviceModeConfig = ROLE_STA; //default is STA mode volatile unsigned char g_ucConnectTimeout =0; #ifdef USE_FREERTOS //***************************************************************************** // FreeRTOS User Hook Functions enabled in FreeRTOSConfig.h //***************************************************************************** //***************************************************************************** // //! \brief Application defined hook (or callback) function - assert //! //! \param[in] pcFile - Pointer to the File Name //! \param[in] ulLine - Line Number //! //! \return none //! //***************************************************************************** void vAssertCalled( const char *pcFile, unsigned long ulLine ) { //Handle Assert here while(1) { } } //***************************************************************************** // //! \brief Application defined idle task hook //! //! \param none //! //! \return none //! //***************************************************************************** void vApplicationIdleHook( void) { //Handle Idle Hook for Profiling, Power Management etc } //***************************************************************************** // //! \brief Application defined malloc failed hook //! //! \param none //! //! \return none //! //***************************************************************************** void vApplicationMallocFailedHook() { //Handle Memory Allocation Errors while(1) { } } //***************************************************************************** // //! \brief Application defined stack overflow hook //! //! \param none //! //! \return none //! //***************************************************************************** void vApplicationStackOverflowHook( OsiTaskHandle *pxTask, signed char *pcTaskName) { //Handle FreeRTOS Stack Overflow while(1) { } } #endif //USE_FREERTOS //***************************************************************************** // SimpleLink Asynchronous Event Handlers -- Start //***************************************************************************** //***************************************************************************** // //! \brief The Function Handles WLAN Events //! //! \param[in] pWlanEvent - Pointer to WLAN Event Info //! //! \return None //! //***************************************************************************** void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent) { if(!pWlanEvent) { return; } switch(pWlanEvent->Event) { case SL_WLAN_CONNECT_EVENT: { SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); // // Information about the connected AP (like name, MAC etc) will be // available in 'slWlanConnectAsyncResponse_t'-Applications // can use it if required // // slWlanConnectAsyncResponse_t *pEventData = NULL; // pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected; // // Copy new connection SSID and BSSID to global parameters memcpy(g_ucConnectionSSID,pWlanEvent->EventData. STAandP2PModeWlanConnected.ssid_name, pWlanEvent->EventData.STAandP2PModeWlanConnected.ssid_len); memcpy(g_ucConnectionBSSID, pWlanEvent->EventData.STAandP2PModeWlanConnected.bssid, SL_BSSID_LENGTH); UART_PRINT("[WLAN EVENT] STA Connected to the AP: %s ," "BSSID: %x:%x:%x:%x:%x:%x\n\r", g_ucConnectionSSID,g_ucConnectionBSSID[0], g_ucConnectionBSSID[1],g_ucConnectionBSSID[2], g_ucConnectionBSSID[3],g_ucConnectionBSSID[4], g_ucConnectionBSSID[5]); } break; case SL_WLAN_DISCONNECT_EVENT: { slWlanConnectAsyncResponse_t* pEventData = NULL; CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected; // If the user has initiated 'Disconnect' request, //'reason_code' is SL_WLAN_DISCONNECT_USER_INITIATED_DISCONNECTION if(SL_WLAN_DISCONNECT_USER_INITIATED_DISCONNECTION == pEventData->reason_code) { UART_PRINT("[WLAN EVENT]Device disconnected from the AP: %s," "BSSID: %x:%x:%x:%x:%x:%x on application's request \n\r", g_ucConnectionSSID,g_ucConnectionBSSID[0], g_ucConnectionBSSID[1],g_ucConnectionBSSID[2], g_ucConnectionBSSID[3],g_ucConnectionBSSID[4], g_ucConnectionBSSID[5]); } else { UART_PRINT("[WLAN ERROR]Device disconnected from the AP AP: %s," "BSSID: %x:%x:%x:%x:%x:%x on an ERROR..!! \n\r", g_ucConnectionSSID,g_ucConnectionBSSID[0], g_ucConnectionBSSID[1],g_ucConnectionBSSID[2], g_ucConnectionBSSID[3],g_ucConnectionBSSID[4], g_ucConnectionBSSID[5]); } memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID)); memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID)); } break; case SL_WLAN_STA_CONNECTED_EVENT: { // when device is in AP mode and any client connects to device cc3xxx SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED); // // Information about the connected client (like SSID, MAC etc) will // be available in 'slPeerInfoAsyncResponse_t' - Applications // can use it if required // // slPeerInfoAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.APModeStaConnected; // } break; case SL_WLAN_STA_DISCONNECTED_EVENT: { // when client disconnects from device (AP) CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED); // // Information about the connected client (like SSID, MAC etc) will // be available in 'slPeerInfoAsyncResponse_t' - Applications // can use it if required // // slPeerInfoAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.APModestaDisconnected; // } break; case SL_WLAN_SMART_CONFIG_COMPLETE_EVENT: { SET_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START); // // Information about the SmartConfig details (like Status, SSID, // Token etc) will be available in 'slSmartConfigStartAsyncResponse_t' // - Applications can use it if required // // slSmartConfigStartAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.smartConfigStartResponse; // } break; case SL_WLAN_SMART_CONFIG_STOP_EVENT: { // SmartConfig operation finished CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START); // // Information about the SmartConfig details (like Status, padding // etc) will be available in 'slSmartConfigStopAsyncResponse_t' - // Applications can use it if required // // slSmartConfigStopAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.smartConfigStopResponse; // } break; case SL_WLAN_P2P_DEV_FOUND_EVENT: { SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_DEV_FOUND); // // Information about P2P config details (like Peer device name, own // SSID etc) will be available in 'slPeerInfoAsyncResponse_t' - // Applications can use it if required // // slPeerInfoAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.P2PModeDevFound; // } break; case SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT: { SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_REQ_RECEIVED); // // Information about P2P Negotiation req details (like Peer device // name, own SSID etc) will be available in 'slPeerInfoAsyncResponse_t' // - Applications can use it if required // // slPeerInfoAsyncResponse_t *pEventData = NULL; // pEventData = &pSlWlanEvent->EventData.P2PModeNegReqReceived; // } break; case SL_WLAN_CONNECTION_FAILED_EVENT: { // If device gets any connection failed event SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED); } break; default: { UART_PRINT("[WLAN EVENT] Unexpected event [0x%x]\n\r", pWlanEvent->Event); } break; } } //***************************************************************************** // //! \brief This function handles network events such as IP acquisition, IP //! leased, IP released etc. //! //! \param[in] pNetAppEvent - Pointer to NetApp Event Info //! //! \return None //! //***************************************************************************** void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent) { if(!pNetAppEvent) { return; } switch(pNetAppEvent->Event) { case SL_NETAPP_IPV4_IPACQUIRED_EVENT: { SlIpV4AcquiredAsync_t *pEventData = NULL; SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); //Ip Acquired Event Data pEventData = &pNetAppEvent->EventData.ipAcquiredV4; g_uiIpAddress = pEventData->ip; //Gateway IP address g_ulGatewayIP = pEventData->gateway; /*UART_PRINT("[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , " "Gateway=%d.%d.%d.%d\n\r", SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1), SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0)); */ } break; case SL_NETAPP_IP_LEASED_EVENT: { SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED); // // Information about the IP-Leased details(like IP-Leased,lease-time, // mac etc) will be available in 'SlIpLeasedAsync_t' - Applications // can use it if required // // SlIpLeasedAsync_t *pEventData = NULL; // pEventData = &pNetAppEvent->EventData.ipLeased; // } break; case SL_NETAPP_IP_RELEASED_EVENT: { CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED); // // Information about the IP-Released details (like IP-address, mac // etc) will be available in 'SlIpReleasedAsync_t' - Applications // can use it if required // // SlIpReleasedAsync_t *pEventData = NULL; // pEventData = &pNetAppEvent->EventData.ipReleased; // } break; default: { UART_PRINT("[NETAPP EVENT] Unexpected event [0x%x] \n\r", pNetAppEvent->Event); } break; } } //***************************************************************************** // //! \brief This function handles General Events //! //! \param[in] pDevEvent - Pointer to General Event Info //! //! \return None //! //***************************************************************************** void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent) { if(!pDevEvent) { return; } // // Most of the general errors are not FATAL are are to be handled // appropriately by the application // UART_PRINT("[GENERAL EVENT] - ID=[%d] Sender=[%d]\n\n", pDevEvent->EventData.deviceEvent.status, pDevEvent->EventData.deviceEvent.sender); } //***************************************************************************** // //! This function handles socket events indication //! //! \param[in] pSock - Pointer to Socket Event Info //! //! \return None //! //***************************************************************************** void SimpleLinkSockEventHandler(SlSockEvent_t *pSock) { // // This application doesn't work w/ socket - Events are not expected // } //***************************************************************************** // //! This function gets triggered when HTTP Server receives Application //! defined GET and POST HTTP Tokens. //! //! \param pHttpServerEvent Pointer indicating http server event //! \param pHttpServerResponse Pointer indicating http server response //! //! \return None //! //***************************************************************************** void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse) { unsigned char strLenVal = 0; if(!pSlHttpServerEvent || !pSlHttpServerResponse) { return; } switch (pSlHttpServerEvent->Event) { case SL_NETAPP_HTTPGETTOKENVALUE_EVENT: { unsigned char status, *ptr; ptr = pSlHttpServerResponse->ResponseData.token_value.data; pSlHttpServerResponse->ResponseData.token_value.len = 0; if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, GET_token, strlen((const char *)GET_token)) == 0) { status = GPIO_IF_LedStatus(MCU_RED_LED_GPIO); strLenVal = strlen(LED1_STRING); memcpy(ptr, LED1_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; if(status & 0x01) { strLenVal = strlen(LED_ON_STRING); memcpy(ptr, LED_ON_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; } else { strLenVal = strlen(LED_OFF_STRING); memcpy(ptr, LED_OFF_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; } status = GPIO_IF_LedStatus(MCU_GREEN_LED_GPIO); strLenVal = strlen(LED2_STRING); memcpy(ptr, LED2_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; if(status & 0x01) { strLenVal = strlen(LED_ON_STRING); memcpy(ptr, LED_ON_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; } else { strLenVal = strlen(LED_OFF_STRING); memcpy(ptr, LED_OFF_STRING, strLenVal); ptr += strLenVal; pSlHttpServerResponse->ResponseData.token_value.len += strLenVal; } *ptr = '\0'; } } break; case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT: { unsigned char led; unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data; if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0) { ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data; strLenVal = strlen(LED_STRING); if(memcmp(ptr, LED_STRING, strLenVal) != 0) break; ptr += strLenVal; led = *ptr; strLenVal = strlen(LED_ON_STRING); ptr += strLenVal; if(led == '1') { if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0) { GPIO_IF_LedOn(MCU_RED_LED_GPIO); } else { GPIO_IF_LedOff(MCU_RED_LED_GPIO); } } else if(led == '2') { if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0) { GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); } else { GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); } } } } break; default: break; } } //***************************************************************************** // //! \brief This function initializes the application variables //! //! \param None //! //! \return None //! //***************************************************************************** static void InitializeAppVariables() { g_ulStatus = 0; g_uiIpAddress = 0; g_ulGatewayIP = 0; //Added memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID)); memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID)); } //***************************************************************************** //! \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 } // /* Connecting to WLAN AccessPoint */ // This function connects the device to an accesspoint. // static long WlanConnect() { SlSecParams_t secParams = {0}; long lRetVal = 0; secParams.Key = (signed char*)w1.pass; secParams.KeyLen = strlen(w1.pass); secParams.Type = SECURITY_TYPE; lRetVal = sl_WlanConnect((signed char*)w1.ssid, strlen(w1.ssid), 0, &secParams, 0); ASSERT_ON_ERROR(lRetVal); // Wait for WLAN Event while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))) { // Toggle LEDs to Indicate Connection Progress GPIO_IF_LedOff(MCU_IP_ALLOC_IND); MAP_UtilsDelay(800000); GPIO_IF_LedOn(MCU_IP_ALLOC_IND); MAP_UtilsDelay(800000); } return SUCCESS; } //**************************************************************************** // //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is //! Placed, Force it to AP mode //! //! \return 0 on success else error code // //**************************************************************************** long ConnectToNetwork() { char ucAPSSID[32]; unsigned short len, config_opt; long lRetVal = -1; // starting simplelink g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); // Device is not in STA mode and Force AP Jumper is not Connected //- Switch to STA mode if(g_uiSimplelinkRole != ROLE_STA && g_uiDeviceModeConfig == ROLE_STA ) { //Switch to STA Mode lRetVal = sl_WlanSetMode(ROLE_STA); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); g_usMCNetworkUstate = 0; g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); } //Device is not in AP mode and Force AP Jumper is Connected - //Switch to AP mode if(g_uiSimplelinkRole != ROLE_AP && g_uiDeviceModeConfig == ROLE_AP ) { //Switch to AP Mode lRetVal = sl_WlanSetMode(ROLE_AP); ASSERT_ON_ERROR(lRetVal); lRetVal = sl_Stop(SL_STOP_TIMEOUT); g_usMCNetworkUstate = 0; g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL); } //No Mode Change Required if(g_uiSimplelinkRole == ROLE_AP) { //waiting for the AP to acquire IP address from Internal DHCP Server while(!IS_IP_ACQUIRED(g_ulStatus)) { } //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 iCount=0; //Read the AP SSID memset(ucAPSSID,'\0',AP_SSID_LEN_MAX); len = AP_SSID_LEN_MAX; config_opt = WLAN_AP_OPT_SSID; lRetVal = sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (unsigned char*) ucAPSSID); ASSERT_ON_ERROR(lRetVal); Report("\n\rDevice is in AP Mode, Please Connect to AP [%s] and" "type [mysimplelink.net] in the browser \n\r",ucAPSSID); //Blink LED 3 times to Indicate AP Mode for(iCount=0;iCount<3;iCount++) { //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); } } 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 ( (!IS_IP_ACQUIRED(g_ulStatus))&& g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT) { //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); g_ucConnectTimeout++; } */ //Couldn't connect Using Auto Profile /* if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT) { //Blink Red LED to Indicate Connection Error GPIO_IF_LedOn(MCU_RED_LED_GPIO); CLR_STATUS_BIT_ALL(g_ulStatus); Report("Use Smart Config Application to configure the device.\n\r"); //Connect Using Smart Config lRetVal = SmartConfigConnect(); ASSERT_ON_ERROR(lRetVal); //Waiting for the device to Auto Connect while(!IS_IP_ACQUIRED(g_ulStatus)) { MAP_UtilsDelay(500); } } */ WlanConnect(); //check //Turn RED LED Off GPIO_IF_LedOff(MCU_RED_LED_GPIO); UART_PRINT("\n\rDevice is in STA Mode, Connect to the AP[%s] and type" "IP address [%d.%d.%d.%d] in the browser \n\r",g_ucConnectionSSID, SL_IPV4_BYTE(g_uiIpAddress,3),SL_IPV4_BYTE(g_uiIpAddress,2), SL_IPV4_BYTE(g_uiIpAddress,1),SL_IPV4_BYTE(g_uiIpAddress,0)); } return SUCCESS; } //***************************************************************************** // //! \brief Flush response body. //! //! \param[in] httpClient - Pointer to HTTP Client instance //! //! \return 0 on success else error code on failure //! //***************************************************************************** static int FlushHTTPResponse(HTTPCli_Handle httpClient) { const char *ids[2] = { HTTPCli_FIELD_NAME_CONNECTION, /* App will get connection header value. all others will skip by lib */ NULL }; char buf[128]; int id; int len = 1; bool moreFlag = 0; char ** prevRespFilelds = NULL; /* Store previosly store array if any */ prevRespFilelds = HTTPCli_setResponseFields(httpClient, ids); /* Read response headers */ while ((id = HTTPCli_getResponseField(httpClient, buf, sizeof(buf), &moreFlag)) != HTTPCli_FIELD_ID_END) { if(id == 0) { if(!strncmp(buf, "close", sizeof("close"))) { UART_PRINT("\r\nConnection terminated by server\r\n"); } } } /* Restore previosuly store array if any */ HTTPCli_setResponseFields(httpClient, (const char **)prevRespFilelds); while(1) { /* Read response data/body */ /* Note: moreFlag will be set to 1 by HTTPCli_readResponseBody() call, if more data is available Or in other words content length > length of buffer. The remaining data will be read in subsequent call to HTTPCli_readResponseBody(). Please refer HTTP Client Libary API documenation @ref HTTPCli_readResponseBody for more information. */ HTTPCli_readResponseBody(httpClient, buf, sizeof(buf) - 1, &moreFlag); ASSERT_ON_ERROR(len); if ((len - 2) >= 0 && buf[len - 2] == '\r' && buf [len - 1] == '\n'){ break; } if(!moreFlag) { /* There no more data. break the loop. */ break; } } return 0; } //***************************************************************************** // //! \brief Handler for parsing JSON data //! //! \param[in] ptr - Pointer to http response body data //! //! \return 0 on success else error code on failure //! //***************************************************************************** int ParseJSONData(char *ptr) { long lRetVal = 0; int noOfToken; jsmn_parser parser; jsmntok_t *tokenList; /* Initialize JSON PArser */ jsmn_init(&parser); /* Get number of JSON token in stream as we we dont know how many tokens need to pass */ noOfToken = jsmn_parse(&parser, (const char *)ptr, strlen((const char *)ptr), NULL, 10); if(noOfToken <= 0) { UART_PRINT("\r\nFailed to initialize JSON parser\r\n"); return -1; } /* Allocate memory to store token */ tokenList = (jsmntok_t *) malloc(noOfToken*sizeof(jsmntok_t)); if(tokenList == NULL) { UART_PRINT("\r\nFailed to allocate memory\r\n"); return -1; } /* Initialize JSON Parser again */ jsmn_init(&parser); noOfToken = jsmn_parse(&parser, (const char *)ptr, strlen((const char *)ptr), tokenList, noOfToken); if(noOfToken < 0) { UART_PRINT("Failed to parse JSON tokens\n\r"); lRetVal = noOfToken; } else { // UART_PRINT("Successfully parsed %ld JSON tokens\n\r", noOfToken); } free(tokenList); return lRetVal; } /*! \brief This function read respose from server and dump on console \param[in] httpClient - HTTP Client object \return 0 on success else -ve \note \warning */ static int readResponse(HTTPCli_Handle httpClient) { long lRetVal = 0; int bytesRead = 0; int id = 0; unsigned long len = 0; int json = 0; char *dataBuffer=NULL; bool moreFlags = 1; const char *ids[4] = { HTTPCli_FIELD_NAME_CONTENT_LENGTH, HTTPCli_FIELD_NAME_CONNECTION, HTTPCli_FIELD_NAME_CONTENT_TYPE, NULL }; /* Read HTTP POST request status code */ lRetVal = HTTPCli_getResponseStatus(httpClient); if(lRetVal > 0) { switch(lRetVal) { case 200: { UART_PRINT("\r\n200 OK\r\n"); /* Set response header fields to filter response headers. All other than set by this call we be skipped by library. */ HTTPCli_setResponseFields(httpClient, (const char **)ids); /* Read filter response header and take appropriate action. */ /* Note: 1. id will be same as index of fileds in filter array setted in previous HTTPCli_setResponseFields() call. 2. moreFlags will be set to 1 by HTTPCli_getResponseField(), if field value could not be completely read. A subsequent call to HTTPCli_getResponseField() will read remaining field value and will return HTTPCli_FIELD_ID_DUMMY. Please refer HTTP Client Libary API documenation @ref HTTPCli_getResponseField for more information. */ while((id = HTTPCli_getResponseField(httpClient, (char *)g_buff, sizeof(g_buff), &moreFlags)) != HTTPCli_FIELD_ID_END) { switch(id) { case 0: /* HTTPCli_FIELD_NAME_CONTENT_LENGTH */ { len = strtoul((char *)g_buff, NULL, 0); } break; case 1: /* HTTPCli_FIELD_NAME_CONNECTION */ { } break; case 2: /* HTTPCli_FIELD_NAME_CONTENT_TYPE */ { if(!strncmp((const char *)g_buff, "application/json; charset=utf-8", sizeof("application/json"))) { json = 1; } else { /* Note: Developers are advised to use appropriate content handler. In this example all content type other than json are treated as plain text. */ json = 0; } // UART_PRINT(HTTPCli_FIELD_NAME_CONTENT_TYPE); // UART_PRINT(" : "); // UART_PRINT("\r\napplication/json\n\r"); } break; default: { UART_PRINT("\r\nWrong filter id\r\n"); lRetVal = -1; goto end; } } } bytesRead = 0; if(len > sizeof(g_buff)) { dataBuffer = (char *) malloc(len); if(dataBuffer) { UART_PRINT("\r\nFailed to allocate memory\r\n"); lRetVal = -1; goto end; } } else { dataBuffer = (char *)g_buff; } /* Read response data/body */ /* Note: moreFlag will be set to 1 by HTTPCli_readResponseBody() call, if more data is available Or in other words content length > length of buffer. The remaining data will be read in subsequent call to HTTPCli_readResponseBody(). Please refer HTTP Client Libary API documenation @ref HTTPCli_readResponseBody for more information */ bytesRead = HTTPCli_readResponseBody(httpClient, (char *)dataBuffer, len, &moreFlags); if(bytesRead < 0) { UART_PRINT("\r\nFailed to received response body\r\n"); lRetVal = bytesRead; goto end; } else if( bytesRead < len || moreFlags) { UART_PRINT("\r\nMismatch in content length and received data length\r\n"); goto end; } dataBuffer[bytesRead] = '\0'; if(json) { /* Parse JSON data */ lRetVal = ParseJSONData(dataBuffer); if(lRetVal < 0) { goto end; } } else { /* treating data as a plain text */ } UART_PRINT("\r\n%s\r\n",g_buff); //GET response string } break; case 201: { UART_PRINT("\r\n201 created\r\n"); FlushHTTPResponse(httpClient); break; } case 400: UART_PRINT("\r\n400 Bad Request\r\n"); FlushHTTPResponse(httpClient); break; case 404: UART_PRINT("\r\n404 File not found\r\n"); //break; /* Handle response body as per requirement. Note: Developers are advised to take appopriate action for HTTP return status code else flush the response body. In this example we are flushing response body in default case for all other than 200 HTTP Status code. */ default: /* Note: Need to flush received buffer explicitly as library will not do for next request.Application is responsible for reading all the data. */ FlushHTTPResponse(httpClient); break; } } else { UART_PRINT("\r\nFailed to receive data from server\r\n"); goto end; } lRetVal = 0; end: if(len > sizeof(g_buff) && (dataBuffer != NULL)) { free(dataBuffer); } return lRetVal; } //***************************************************************************** // //! \brief HTTP POST Demonstration //! //! \param[in] httpClient - Pointer to http client //! //! \return 0 on success else error code on failure //! //***************************************************************************** static int HTTPPostMethod(HTTPCli_Handle httpClient) { bool moreFlags = 1; bool lastFlag = 1; char tmpBuf[4]; long lRetVal = 0; HTTPCli_Field fields[4] = { {HTTPCli_FIELD_NAME_HOST, w1.host}, {HTTPCli_FIELD_NAME_ACCEPT, "*/*"}, {HTTPCli_FIELD_NAME_CONTENT_TYPE, "application/json"}, {NULL, NULL} }; // json_t json_data={"{\n\"StationNum\": ","1000",}; //testing // char *j=&json_data; //testing // strcpy(json_data.last,",\n\"Epoch\": 1522231953,\n\"RMY8600WindSpeed\": 29.10,\n\"RMY8600WindDirection\": 57.23,\n\"RMY61302Pressure\": 87.235,\n\"WXT520Humidity\": 49.00,\n\"WXT520Temperature\": 26.30,\n\"WXT520Pressure\": 56.880700,\n\"WindSonicSpeed\": 64.50,\n\"WindSonicDirection\": 84.30,\n\"Pyrano_SR20\": 645.756,\n\"RainGauge\": 48.664,\n\"RMY05103WindSpeed\": 65.464,\n\"RMY05103WindDirection\": 57.780,\n\"RMYRTDTemperature\": 56.70,\n\"PT1000Temperature\": 55.175,\n\"VegapulsLevel_water_\": 35.40\n}"); /* Set request header fields to be send for HTTP request. */ HTTPCli_setRequestFields(httpClient, fields); /* Send POST method request. */ /* Here we are setting moreFlags = 1 as there are some more header fields need to send other than setted in previous call HTTPCli_setRequestFields() at later stage. Please refer HTTP Library API documentaion @ref HTTPCli_sendRequest for more information. */ moreFlags = 1; lRetVal = HTTPCli_sendRequest(httpClient, HTTPCli_METHOD_POST, w1.posturi, moreFlags); if(lRetVal < 0) { UART_PRINT("\r\nFailed to send POST request header\r\n"); return lRetVal; } // p++; // sprintf(json.sno,"%d",p); //testing // p = strlen((const char *)&json_data); //p = strlen(POST_DATA); //p = strncmp(POST_DATA,(const char)j, strlen(POST_DATA)); //Report("%s",j); // Report("%s",POST_DATA); //sprintf((char *)tmpBuf, "%d", strlen((const char *)&json_data)); sprintf((char *)tmpBuf, "%d", (sizeof(w1.json)-1)); /* Here we are setting lastFlag = 1 as it is last header field. Please refer HTTP Library API documentaion @ref HTTPCli_sendField for more information. */ lastFlag = 1; lRetVal = HTTPCli_sendField(httpClient, HTTPCli_FIELD_NAME_CONTENT_LENGTH, (const char *)tmpBuf, lastFlag); if(lRetVal < 0) { UART_PRINT("\r\nFailed to send POST request header\r\n"); return lRetVal; } /* Send POST data/body */ // lRetVal = HTTPCli_sendRequestBody(httpClient,(const char) j, (strlen((const char) j))); lRetVal = HTTPCli_sendRequestBody(httpClient,w1.json, (sizeof(w1.json)-1)); if(lRetVal < 0) { UART_PRINT("\r\nFailed to send POST request body.\n\r"); return lRetVal; } lRetVal = readResponse(httpClient); return lRetVal; } // // http get method // static int HTTPGetMethod(HTTPCli_Handle httpClient) { long lRetVal = 0; HTTPCli_Field fields[4] = { {HTTPCli_FIELD_NAME_HOST, w1.host}, {HTTPCli_FIELD_NAME_ACCEPT, "*/*"}, {HTTPCli_FIELD_NAME_CONTENT_LENGTH, "0"}, {NULL, NULL} }; bool moreFlags; /* Set request header fields to be send for HTTP request. */ HTTPCli_setRequestFields(httpClient, fields); /* Send GET method request. */ /* Here we are setting moreFlags = 0 as there are no more header fields need to send at later stage. Please refer HTTP Library API documentaion @ HTTPCli_sendRequest for more information. */ moreFlags = 0; lRetVal = HTTPCli_sendRequest(httpClient, HTTPCli_METHOD_GET, w1.geturi, moreFlags); if(lRetVal < 0) { UART_PRINT("\r\nFailed to send GET request\r\n"); return lRetVal; } lRetVal = readResponse(httpClient); return lRetVal; } //***************************************************************************** // //! Function to connect to HTTP server //! //! \param httpClient - Pointer to HTTP Client instance //! //! \return Error-code or SUCCESS //! //***************************************************************************** static int ConnectToHTTPServer(HTTPCli_Handle httpClient) { long lRetVal = -1; struct sockaddr_in addr; #ifdef USE_PROXY struct sockaddr_in paddr; paddr.sin_family = AF_INET; paddr.sin_port = htons(PROXY_PORT); paddr.sin_addr.s_addr = sl_Htonl(PROXY_IP); HTTPCli_setProxy((struct sockaddr *)&paddr); #endif /* Resolve HOST NAME/IP */ lRetVal = sl_NetAppDnsGetHostByName((signed char *)w1.host, strlen((const char *)w1.host), &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(httpClient); lRetVal = HTTPCli_connect(httpClient, (struct sockaddr *)&addr, 0, NULL); if (lRetVal < 0) { UART_PRINT("\r\nConnection to server failed. error(%d)\r\n", lRetVal); ASSERT_ON_ERROR(SERVER_CONNECTION_FAILED); } else { UART_PRINT("\r\nServerConnected\r\n"); } return 0; } //**************************************************************************** // //! \brief Read Force AP GPIO and Configure Mode - 1(Access Point Mode) //! - 0 (Station Mode) //! //! \return None // //**************************************************************************** static void ReadDeviceConfiguration() { //unsigned int uiGPIOPort; //unsigned char pucGPIOPin; unsigned char ucPinValue; //Read GPIO // GPIO_IF_GetPortNPin(SH_GPIO_3,&uiGPIOPort,&pucGPIOPin); // ucPinValue = GPIO_IF_Get(SH_GPIO_3,uiGPIOPort,pucGPIOPin); //If Connected to VCC, Mode is AP ucPinValue=sMode; if(ucPinValue == 1) { //AP Mode g_uiDeviceModeConfig = ROLE_AP; } else { //STA Mode g_uiDeviceModeConfig = ROLE_STA; } } //**************************************************************************** // //! \brief Handles HTTP Server Task //! //! \param[in] pvParameters is the data passed to the Task //! //! \return None // //**************************************************************************** static void HTTPServerTask(void *pvParameters) { long lRetVal = -1; 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 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"); LOOP_FOREVER(); } UART_PRINT("Device is configured in default state \n\r"); memset(g_ucSSID,'\0',AP_SSID_LEN_MAX); //Read Device Mode Configuration ReadDeviceConfiguration(); //Connect to Network lRetVal = ConnectToNetwork(); //Stop Internal HTTP Server lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Start Internal HTTP Server lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } //Handle Async Events // while(1) //commented //{ //} } //***************************************************************************** // //! Application startup display on UART //! //! \param none //! //! \return none //! //***************************************************************************** /*static void //comment DisplayBanner(char * AppName) { Report("\n\n\n\r"); Report("\t\t *************************************************\n\r"); Report("\t\t CC3200 %s Application \n\r", AppName); Report("\t\t *************************************************\n\r"); Report("\n\n\n\r"); } */ //***************************************************************************** // //! Board Initialization & Configuration //! //! \param None //! //! \return None // //***************************************************************************** static void BoardInit(void) { /* In case of TI-RTOS vector table is initialize by OS itself */ #ifndef USE_TIRTOS // // Set vector table base // #if defined(ccs) MAP_IntVTableBaseSet((unsigned long)&g_pfnVectors[0]); #endif #if defined(ewarm) MAP_IntVTableBaseSet((unsigned long)&__vector_table); #endif #endif // // Enable Processor // MAP_IntMasterEnable(); MAP_IntEnable(FAULT_SYSTICK); PRCMCC3200MCUInit(); } // // extract function // void extract() { int k=0; int j; int i=0; while(ucChar[i]!='<') { ucBuffer[i]=ucChar[i]; i++; } ucBuffer[i]='\0'; i++; // Report("\nEntered parameter = %s",ucBuffer); j=matchBuffer(ucBuffer); switch(j) { case Mode: { while(ucChar[i]!='>') { w1.mode[k]=ucChar[i]; i++; k++; } w1.mode[k]='\0'; Report("\n%s\n",w1.mode); if(!strcmp(w1.mode,str1)) { sMode=AP_MODE; Report("\nAp mode\n"); } else if(!strcmp(w1.mode,str2)) sMode=STA_MODE; else Report("\r\nMODE UNKNOWN\r\n"); break; } case Ssid: { while(ucChar[i]!='>') { w1.ssid[k]=ucChar[i]; i++; k++; } w1.ssid[k]='\0'; //Report("\nSsid is \"%s\"",w1.ssid); Report("\r\nOK\r\n"); break; } case Pass: { while(ucChar[i]!='>') { w1.pass[k]=ucChar[i]; i++; k++; } w1.pass[k]='\0'; //Report("\nPassword is \"%s\"",w1.pass); Report("\r\nOK\r\n"); break; } case ConnectAP: { flag=0; break; } case ConnectHttp: { flag=1; break; } case HostName: { while(ucChar[i]!='>') { w1.host[k]=ucChar[i]; i++; k++; } w1.host[k]='\0'; //Report("\nHostName is \"%s\"",w1.host); Report("\r\nOK\r\n"); break; } case PostUri: { while(ucChar[i]!='>') { w1.posturi[k]=ucChar[i]; i++; k++; } w1.posturi[k]='\0'; //Report("uripost is %s",w1.posturi); Report("\r\nOK\r\n"); break; } case GetUri: { while(ucChar[i]!='>') { w1.geturi[k]=ucChar[i]; i++; k++; } w1.geturi[k]='\0'; //Report("\nGetUri is \"%s\"",w1.geturi); Report("\r\nOK\r\n"); break; } case Json: { while(ucChar[i]!='>') { w1.json[k]=ucChar[i]; i++; k++; } w1.json[k]='\0'; //Report("\nJson data is \"%s\"",w1.json); Report("\r\nOK\r\n"); break; } case Httppost: { flag=2; break; } case Httpget: { flag=3; break; } case Disconnect: { flag=4; break; } case Reconnect: { flag=5; break; } default: Report("\r\nData Incorrect\r\n"); break; } } // // Interrupt handler // void UARTIntHandler() { unsigned long ulStatus; char rChar; //int i=0; //int j; //int k=0; // Read the interrupt status of the UART. ulStatus = MAP_UARTIntStatus(UARTA0_BASE, 1); if((ulStatus&UART_INT_RX)&&MAP_UARTCharsAvail(UARTA0_BASE)) { rChar=UARTCharGetNonBlocking(UARTA0_BASE); if((rChar=='\n')&&(ucChar[uiCounter-1]=='\r')) { ucChar[uiCounter]='\0'; uiCounter=0; // Report("Entered String is | %s |",ucChar); extract(); // Extract string and save } else { //UartPutChar(rChar); ucChar[uiCounter]=rChar; uiCounter++; } } MAP_UARTIntClear(UARTA0_BASE, ulStatus); } //**************************************************************************** // MAIN FUNCTION //**************************************************************************** void main() { long lRetVal = -1; //HTTPCli_Struct httpClient; //Board Initialization BoardInit(); //Pin Configuration PinMuxConfig(); InitTerm(); // MAP_UARTConfigSetExpClk(CONSOLE,MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH), // UART_BAUD_RATE,(UART_CONFIG_WLEN_8 | // UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); MAP_UARTFlowControlSet(UARTA0_BASE, UART_FLOWCONTROL_NONE); MAP_UARTFIFODisable(UARTA0_BASE); MAP_UARTIntRegister(UARTA0_BASE,UARTIntHandler); MAP_UARTIntEnable(UARTA0_BASE, UART_INT_RX|UART_INT_RT); //Change Pin 58 Configuration from Default to Pull Down // MAP_PinConfigSet(PIN_58,PIN_STRENGTH_2MA|PIN_STRENGTH_4MA,PIN_TYPE_STD_PD); // // Initialize GREEN and ORANGE LED // GPIO_IF_LedConfigure(LED1|LED2|LED3); //Turn Off the LEDs GPIO_IF_LedOff(MCU_ALL_LED_IND); //Display Application Banner on UART Terminal //DisplayBanner(APPLICATION_NAME); UART_PRINT("\r\nEnter Mode\r\n"); //wait until mode is seleceted while(sMode!=AP_MODE&&sMode!=STA_MODE) { } // // Simplelinkspawntask // lRetVal = VStartSimpleLinkSpawnTask (SPAWN_TASK_PRIORITY); if(lRetVal < 0) { UART_PRINT("Unable to start simpelink spawn task\n\r"); LOOP_FOREVER(); } // // Create HTTP Server Task // lRetVal = osi_TaskCreate(HTTPServerTask, (signed char*)"HTTPServerTask", OSI_STACK_SIZE, NULL, OOB_TASK_PRIORITY, NULL ); if(lRetVal < 0) { UART_PRINT("Unable to create task\n\r"); LOOP_FOREVER(); } // // Start OS Scheduler // osi_start(); while (1) { if(status==2) { WlanConnect(); status=1; } if(flag==CONNECT_AP) { Report("\nStatus = %d\n",status); // if(status==1) //{ //Report("Already connected"); //} lRetVal= ConnectToAP(); flag=-1; } if(flag==CONNECT_HTTP) { lRetVal = ConnectToHTTPServer(&httpClient); if(lRetVal < 0) { Report("\r\nTry again\r\n"); } flag= -1; } if(flag==HTTPPOST) { flag= -1; //UART_PRINT("\n\r"); // UART_PRINT("HTTP Post Begin:\n\r"); lRetVal = HTTPPostMethod(&httpClient); if(lRetVal < 0) { UART_PRINT("\r\nHTTP POST FAILED\r\n"); ConnectToHTTPServer(&httpClient); } // UART_PRINT("\r\nPOST END\r\n"); } if(flag==HTTPGET) { //UART_PRINT("\n\r"); //UART_PRINT("HTTP Get Begin:\n\r"); lRetVal = HTTPGetMethod(&httpClient); if(lRetVal < 0) { UART_PRINT("\r\nHTTP GET FAILED\r\n"); } // UART_PRINT("\r\nHTTP GET END\r\n"); flag = -1; } if(flag==DISCONNECT) { Report("\nStatus = %d\n",status); //Report("\r\nDisconnecting...."); lRetVal=sl_WlanDisconnect(); //if(lRetVal==0) //{ // Report("Disconnected from AP: %s",w1.ssid); // status=0; // Report("\nStatus = %d\n",status); // } flag=-1; } /* if(flag==RECONNECT) { lRetVal=WlanConnect(); //if(lRetVal==0) // { // Report("\nConnected\n"); // } flag=-1; } } }