int main(void){ UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; SlSockAddrIn_t LocalAddr; UINT16 AddrSize = 0; INT16 SockID = 0; INT16 Status = 1; // ok UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); stopWDT(); // Stop WDT initClk(); // PLL 50 MHz, ADC needs PPL active Board_Init(); // initialize LaunchPad I/O ConfigureUART(); // Initialize the UART. UARTprintf("Section 11.4 IoT example, Volume 2 Real-time interfacing\n"); UARTprintf("This node is configured to receive UDP packets\n"); UARTprintf("This node should be at IP: %d.%d.%d.%d Port: %d\n\n", SL_IPV4_BYTE(IP_ADDR,3), SL_IPV4_BYTE(IP_ADDR,2), SL_IPV4_BYTE(IP_ADDR,1), SL_IPV4_BYTE(IP_ADDR,0),PORT_NUM); ST7735_InitR(INITR_REDTAB); ST7735_OutString("Internet of Things\n"); ST7735_OutString("Embedded Systems\n"); ST7735_OutString("Vol. 2, Valvano"); ST7735_PlotClear(0,4095); // range from 0 to 4095 while(1){ sl_Start(0, 0, 0); /* Initializing the CC3100 device */ /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ WlanConnect(); // connect to AP /* Read the IP parameter */ sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,(unsigned char *)&ipV4); UARTprintf("This node is at IP: %d.%d.%d.%d\n", SL_IPV4_BYTE(ipV4.ipV4,3), SL_IPV4_BYTE(ipV4.ipV4,2), SL_IPV4_BYTE(ipV4.ipV4,1), SL_IPV4_BYTE(ipV4.ipV4,0)); while(Status > 0){ UARTprintf("\nReceiving a UDP packet ..."); LocalAddr.sin_family = SL_AF_INET; LocalAddr.sin_port = sl_Htons((UINT16)PORT_NUM); LocalAddr.sin_addr.s_addr = 0; AddrSize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( SockID < 0 ){ UARTprintf("SockIDerror\n"); Status = -1; // error }else{ Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize); if( Status < 0 ){ sl_Close(SockID); UARTprintf("Sock Bind error\n"); }else{ Status = sl_RecvFrom(SockID, uBuf, BUF_SIZE, 0, (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize ); if( Status <= 0 ){ sl_Close(SockID); UARTprintf("Receive error %d ",Status); }else{ LED_Toggle(); sl_Close(SockID); UARTprintf("ok %s ",uBuf); if((uBuf[0]==ATYPE)&&(uBuf[1]== '=')){ int i,bOk; uint32_t place; data = 0; bOk = 1; i=4; // ignore possible negative sign for(place = 1000; place; place = place/10){ if((uBuf[i]&0xF0)==0x30){ // ignore spaces data += place*(uBuf[i]-0x30); }else{ if((uBuf[i]&0xF0)!= ' '){ bOk = 0; } } i++; } if(bOk){ ST7735_PlotLine(data); ST7735_PlotNextErase(); } } } } } ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 120ms } } }
//**************************************************************************** // MAIN FUNCTION //**************************************************************************** int main(void) { long lRetVal; char cCmdBuff[20]; signed char cCmd = APP_SLEEP; SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; SlSockAddrIn_t sBrdAddr; int iCounter; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; short sTestBufLen; struct SlTimeval_t timeVal; // // Board Initialization // BoardInit(); // // uDMA Initialization // UDMAInit(); // // Configure the pinmux settings for the peripherals exercised // Note: pinmux has been modified after the output from pin mux tools // to enable sleep clk for the peripherals exercised // PinMuxConfig(); // // Initialize the platform // platform_init(); // // Initialise the UART terminal // InitTerm(); // // Display banner // DisplayBanner(); // // starting the simplelink // lRetVal = sl_Start(NULL, NULL, NULL); if (lRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } // // Swtich to STA mode if device is not // SwitchToStaMode(lRetVal); // // set connection policy // sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(0, 0, 0, 0, 0), NULL, 0); // // Set the power management policy of NWP // lRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0); UART_PRINT("Trying to Connect to AP: %s ...\r\n",SSID_NAME); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } // 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)PORT_NUM); sLocalAddr.sin_addr.s_addr = 0; //filling the UDP server socket address sBrdAddr.sin_family = SL_AF_INET; sBrdAddr.sin_port = sl_Htons((unsigned short)PORT_NUM); sBrdAddr.sin_addr.s_addr = sl_Htonl((unsigned int)g_ulDestinationIp); iAddrSize = sizeof(SlSockAddrIn_t); // creating a UDP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); /* setting time out for socket recv */ timeVal.tv_sec = 5; // Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution sl_SetSockOpt(iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (_u8 *)&timeVal, sizeof(timeVal)); // 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(iStatus); } // // setting Apps power policy // lp3p0_setup_power_policy(POWER_POLICY_STANDBY); UART_PRINT("enter one of the following command:\n\r"); UART_PRINT("sleep - for putting the system into LPDS mode\n\r"); UART_PRINT(" GPIO 13 and timer(5 sec) are the wk source configured\n\r"); UART_PRINT("recv - for receiving 1000 UDP packets\n\r"); UART_PRINT("send - for broadcasting 1000 UDP packets\n\r"); do{ UART_PRINT("cmd#"); // // get cmd over UART // GetCmd(cCmdBuff, 20); // // parse the command // ParseCmd(cCmdBuff, &cCmd); if(cCmd == APP_SLEEP) { // // set timer and gpio as wake src // set_rtc_as_wk_src(WK_LPDS, LPDS_DUR_SEC, false); set_gpio_as_wk_src(WK_LPDS, GPIO_SRC_WKUP, PRCM_LPDS_FALL_EDGE); cc_idle_task_pm(); } else if(cCmd == APP_RECV) { lLoopCount = 0; /// 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 break; } lLoopCount++; } UART_PRINT("Recieved %u packets successfully \n\r",lLoopCount); if(lLoopCount != g_ulPacketCount) { if(iStatus == SL_EAGAIN) { UART_PRINT("timed out\n\r"); } else { UART_PRINT("recv error: %d\n\r", iStatus); } } } else if(cCmd == APP_SEND) { lLoopCount = 0; // sending 1000 packets to the UDP server while (lLoopCount < g_ulPacketCount) { // sending packet iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, (SlSockAddr_t *)&sBrdAddr, iAddrSize); if( iStatus <= 0 ) { // error UART_PRINT("send error\n\r"); break; } lLoopCount++; } UART_PRINT("Sent %u packets successfully\n\r",lLoopCount); } }while(FOREVER); }
int main1(void){ UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; UINT16 AddrSize = 0; INT16 SockID = 0; INT16 Status = 1; // ok UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); stopWDT(); // Stop WDT initClk(); // PLL 50 MHz, ADC needs PPL active Board_Init(); // initialize LaunchPad I/O ConfigureUART(); // Initialize the UART. UARTprintf("Section 11.4 IoT example, Volume 2 Real-time interfacing\n"); #if ADC ADC0_InitSWTriggerSeq3(7); // Ain7 is on PD0 UARTprintf("This node is configured to measure signals from Ain7=PD0\n"); #endif #if EKG UARTprintf("This node is configured to generate simulated EKG data\n"); #endif UARTprintf(" and send UDP packets to IP: %d.%d.%d.%d Port: %d\n\n", SL_IPV4_BYTE(IP_ADDR,3), SL_IPV4_BYTE(IP_ADDR,2), SL_IPV4_BYTE(IP_ADDR,1), SL_IPV4_BYTE(IP_ADDR,0),PORT_NUM); while(1){ sl_Start(0, 0, 0);/* Initializing the CC3100 device */ /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ WlanConnect(); // connect to AP /* Read the IP parameter */ sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len,(unsigned char *)&ipV4); UARTprintf("This node is at IP: %d.%d.%d.%d\n", SL_IPV4_BYTE(ipV4.ipV4,3), SL_IPV4_BYTE(ipV4.ipV4,2), SL_IPV4_BYTE(ipV4.ipV4,1), SL_IPV4_BYTE(ipV4.ipV4,0)); while(Status > 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons((UINT16)PORT_NUM); Addr.sin_addr.s_addr = sl_Htonl((UINT32)IP_ADDR); AddrSize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( SockID < 0 ){ UARTprintf("SockIDerror "); Status = -1; // error }else{ while(Status>0){ UARTprintf("\nSending a UDP packet ..."); uBuf[0] = ATYPE; // defines this as an analog data type uBuf[1] = '='; #if ADC data = ADC0_InSeq3(); // 0 to 4095, Ain7 is on PD0 #endif #if EKG data = EKGbuf[EKGindex]; EKGindex = (EKGindex+1)%EKGSIZE; // 100 Hz #endif Int2Str(data,(char*)&uBuf[2]); // [2] to [7] is 6 digit number UARTprintf(" %s ",uBuf); LED_Toggle(); Status = sl_SendTo(SockID, uBuf, BUF_SIZE, 0, (SlSockAddr_t *)&Addr, AddrSize); ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 80ms if( Status <= 0 ){ UARTprintf("SockIDerror %d ",Status); }else{ UARTprintf("ok"); } } sl_Close(SockID); } } } }
//***************************************************************************** // //! This function obtains the current time from a SNTP server if required due //! to not having current time (when booting up) or periodically to update //! the time //! //! \param None //! //! \return 0 on success else error code //! \return Error Number of failure // //***************************************************************************** long GetCurrentTime() { int iSocketDesc; long lRetVal = -1; // // Get the time and date currently stored in the RTC // getDeviceTimeDate(); // // Calculate time difference between the last time we obtained time from a NTP server // timeDifference = dateTime.sl_tm_hour - hourSet; // This roughly works, it does however reset after midnight. // // Get the NTP time to use with the SSL process. Only call this every 6 hours to update the RTC // As we do not want to be calling the NTP server too often // if (timeDifference > 6 || timeDifference < 0) { // // Create UDP socket // iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(iSocketDesc < 0) { CLI_Write("Could not create UDP socket.\n\r"); close(iSocketDesc); return iSocketDesc; } else { CLI_Write("Socket successfully created\n\r"); } g_sAppData.iSockID = iSocketDesc; // // Get the NTP server host IP address using the DNS lookup // lRetVal = getHostIP((char*)g_acSNTPserver, &g_sAppData.ulDestinationIP); if( lRetVal >= 0) { // // Configure the recieve timeout // struct SlTimeval_t timeVal; timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT; // Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution lRetVal = sl_SetSockOpt(g_sAppData.iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal)); if(lRetVal < 0) { CLI_Write("Could not configure socket option (receive timeout).\n\r"); close(iSocketDesc); return lRetVal; } } else { CLI_Write("DNS lookup failed."); } // // Get current time from the SNTP server // CLI_Write("Fetching Time From SNTP Server\n\r"); lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS); if(lRetVal < 0) { CLI_Write("Server Get Time failed.\n\r"); close(iSocketDesc); return lRetVal; } else { hourSet = dateTime.sl_tm_hour; // Set to current hour as we did get the time successfully CLI_Write("Server Get Time Successful\n\n\r"); } // // Close the socket // close(iSocketDesc); } return 0; }
//***************************************************************************** // //! This function POST to Event Hub REST API using TLS //! //! \param None //! //! \return 0 on success else error code //! \return Error number on Failure // //***************************************************************************** long PostEventHubSSL() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1; //SL_SO_SEC_METHOD_SSLv3_TLSV1_2; //SL_SO_SEC_METHOD_TLSV1_2; //SL_SO_SEC_METHOD_SSLV3; unsigned int uiIP; unsigned int uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; long lRetVal = -1; int iSSLSockID; char acSendBuff[512]; char acRecvbuff[1460]; //char* pcBufData; char* pcBufHeaders; // // Retrieve IP from Hostname // lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { CLI_Write("Could not retrive the IP Address for Azure Server.\n\r"); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(SSL_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // Opens a secure socket // iSSLSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSSLSockID < 0 ) { CLI_Write("Unable to create secure socket.\n\r"); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Configure the socket as TLS (SSLV3.0 does not work because of POODLE - http://en.wikipedia.org/wiki/POODLE) // lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod, sizeof(ucMethod)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (TLS).\n\r"); sl_Close(iSSLSockID); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Configure the socket as RSA with RC4 128 SHA // lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher, sizeof(uiCipher)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (RSA).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Configure the socket with Azure CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSSLSockID, 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) { CLI_Write("Couldn't set socket option (CA Certificate).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Configure the recieve timeout // struct SlTimeval_t timeVal; timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT; // In Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal)); if(lRetVal < 0) { CLI_Write("Couldn't set socket option (Receive Timeout).\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Connect to the peer device - Azure server */ // lRetVal = sl_Connect(iSSLSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { CLI_Write("Couldn't connect to Azure server.\n\r"); sl_Close(iSSLSockID); //GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // Generate a random number for the temperture // srand((unsigned int)time(NULL)); float a = 5.0; float fRandTemp = 25 - (((float)rand()/(float)(RAND_MAX)) * a); char cTempChar[5]; sprintf(cTempChar, "%.2f", fRandTemp); // // Creates the HTTP POST string. // int dataLength = strlen(DATA1) + 5 + strlen(DATA2); char cCLLength[4]; pcBufHeaders = acSendBuff; strcpy(pcBufHeaders, POSTHEADER); pcBufHeaders += strlen(POSTHEADER); strcpy(pcBufHeaders, HOSTHEADER); pcBufHeaders += strlen(HOSTHEADER); strcpy(pcBufHeaders, AUTHHEADER); pcBufHeaders += strlen(AUTHHEADER); strcpy(pcBufHeaders, CHEADER); pcBufHeaders += strlen(CHEADER); strcpy(pcBufHeaders, CTHEADER); pcBufHeaders += strlen(CTHEADER); strcpy(pcBufHeaders, CLHEADER1); pcBufHeaders += strlen(CLHEADER1); sprintf(cCLLength, "%d", dataLength); strcpy(pcBufHeaders, cCLLength); pcBufHeaders += strlen(cCLLength); strcpy(pcBufHeaders, CLHEADER2); pcBufHeaders += strlen(CLHEADER2); strcpy(pcBufHeaders, DATA1); pcBufHeaders += strlen(DATA1); strcpy(pcBufHeaders , cTempChar); pcBufHeaders += strlen(cTempChar); strcpy(pcBufHeaders, DATA2); int testDataLength = strlen(pcBufHeaders); // // Send the packet to the server */ // lRetVal = sl_Send(iSSLSockID, acSendBuff, strlen(acSendBuff), 0); if(lRetVal < 0) { CLI_Write("POST failed.\n\r"); sl_Close(iSSLSockID); return lRetVal; } // // Receive response packet from the server */ // lRetVal = sl_Recv(iSSLSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0); if(lRetVal < 0) { CLI_Write("Received failed.\n\r"); sl_Close(iSSLSockID); return lRetVal; } else { CLI_Write("HTTP POST Successful. Telemetry successfully logged\n\r"); } sl_Close(iSSLSockID); return SUCCESS; }
//***************************************************************************** // //! \brief Task Created by main fucntion. This task prints the wake up reason //! (from hibernate or from restart). start simplelink, set NWP power //! policy and connects to an AP. Creates UDP client and send UDP //! packets at around 1Mbit/sec for certain time. Disconnect form AP //! and stops the simplelink.Setup GPIO and Timer as wakeup source from //! low power modes. Go into HIBernate. //! //! \param pvParameters is a general void pointer (not used here). //! //! \return none // //***************************************************************************** void TimerGPIOTask(void *pvParameters) { cc_hndl tTimerHndl; cc_hndl tGPIOHndl; int iSockDesc = 0; int iRetVal = 0; int iCounter = 0; sockaddr_in sServerAddr; unsigned char *pcSendBuff; unsigned char cSyncMsg; // // creating the queue for signalling about connection events // iRetVal = osi_MsgQCreate(&g_tConnection, NULL, sizeof( unsigned char ), 3); if (iRetVal < 0) { UART_PRINT("unable to create the msg queue\n\r"); LOOP_FOREVER(); } // filling the buffer for (iCounter=0 ; iCounter<BUFF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } pcSendBuff = g_cBsdBuf; if(MAP_PRCMSysResetCauseGet() == PRCM_POWER_ON) { // // Displays the Application Banner // DisplayBanner(); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } // // Switch to STA mode if device is not in this mode // SwitchToStaMode(iRetVal); // // Set the power management policy of NWP // iRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0); if (iRetVal < 0) { UART_PRINT("unable to configure network power policy\n\r"); LOOP_FOREVER(); } } else if(MAP_PRCMSysResetCauseGet() == PRCM_HIB_EXIT) { UART_PRINT("woken from hib\n\r"); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } } else if(MAP_PRCMSysResetCauseGet() == PRCM_WDT_RESET) { UART_PRINT("woken from WDT Reset\n\r"); // // starting the simplelink // iRetVal = sl_Start(NULL, NULL, NULL); if (iRetVal < 0) { UART_PRINT("Failed to start the device \n\r"); LOOP_FOREVER(); } } else { UART_PRINT("woken cause unknown\n\r"); } // // connecting to the Access Point // if(-1 == WlanConnect()) { UART_PRINT("Connection to AP failed\n\r"); goto no_network_connection; }else{ UART_PRINT("Connected to AP\n\r"); } // // creating a UDP socket // iSockDesc = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if(iSockDesc < 0) { UART_PRINT("sock error\n\r"); LOOP_FOREVER(); } // // configure the UDP Server address // sServerAddr.sin_family = SL_AF_INET; sServerAddr.sin_port = sl_Htons(APP_UDP_PORT); sServerAddr.sin_addr.s_addr = sl_Htonl(SERVER_IP_ADDRESS); // // Set 5 sec timer allowing 5 sec of UDP Tx. // tTimerHndl = SetTimer(); g_ucTrafficEnable = 1; while(g_ucTrafficEnable == 1) { // // sending message // iRetVal = sendto(iSockDesc, pcSendBuff,BUFF_SIZE, 0, (struct sockaddr *)&sServerAddr,sizeof(sServerAddr)); if(iRetVal < 0) { UART_PRINT("send error\n\r"); LOOP_FOREVER(); } ManageDelay(128,BUFF_SIZE); } UART_PRINT("sent\n\r"); // // stop and delete the timer // cc_timer_stop(tTimerHndl); cc_timer_delete(tTimerHndl); // //close the socket // close(iSockDesc); if(iRetVal < 0) { UART_PRINT("could not close the socket\n\r"); } // // disconnect from the Access Point // WlanDisconnect(); no_network_connection: // // stop the simplelink with reqd. timeout value (30 ms) // sl_Stop(SL_STOP_TIMEOUT); // // setting Timer as one of the wakeup source // tTimerHndl = SetTimerAsWkUp(); // // setting some GPIO as one of the wakeup source // tGPIOHndl = SetGPIOAsWkUp(); /* handles, if required, can be used to stop the timer, but not used here*/ UNUSED(tTimerHndl); UNUSED(tGPIOHndl); // // Setting up HIBERNATE as the lowest power mode for the system. // lp3p0_setup_power_policy(POWER_POLICY_HIBERNATE); // // idle wait will push the system into the lowest power mode(HIBERNATE). // iRetVal = osi_MsgQCreate(&g_tWaitForHib, NULL, sizeof( unsigned char ), 1); if (iRetVal < 0) { UART_PRINT("unable to create the msg queue\n\r"); LOOP_FOREVER(); } osi_MsgQRead(&g_tWaitForHib, &cSyncMsg, OSI_WAIT_FOREVER); // // infinite loop (must not reach here) // LOOP_FOREVER(); }
//**************************************************************************** // //! \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; }
//**************************************************************************** // //! Task function implementing the UDP client and showcasing the hibernate //! functionality //! //! \param none //! //! This function //! 1. Creates a UDP socket //! 2. Broadcasts a packet on the socket //! 3. Closes the socket //! 4. Enters the HIBernate mode //! //! \return None. // //**************************************************************************** void HIBUDPBroadcastTask(void *pvParameters) { int iSocketDesc; long lRetVal; struct sockaddr_in sBroadcastAddr; char pcBroadcastMessage[]="32xx HIB example application"; // // Check the wakeup source. If first itme entry or wakeup from HIB // if(MAP_PRCMSysResetCauseGet() == 0) { DisplayBanner(APPNAME); DBG_PRINT("HIB: Wake up on Power ON\n\r"); } else if(MAP_PRCMSysResetCauseGet() == PRCM_HIB_EXIT) { DBG_PRINT("HIB: Woken up from Hibernate\n\r"); } else { } GPIO_IF_LedConfigure(LED1); GPIO_IF_LedOff(MCU_RED_LED_GPIO); // // Configure Timer for blinking the LED for IP acquisition // LedTimerConfigNStart(); // // // Reset The state of the machine // Network_IF_ResetMCUStateMachine(); // // Start the driver // lRetVal = Network_IF_InitDriver(ROLE_STA); if(lRetVal < 0) { UART_PRINT("Failed to start SimpleLink Device\n\r"); LOOP_FOREVER(); } // Initialize AP security params SecurityParams.Key = (signed char*)SECURITY_KEY; SecurityParams.KeyLen = strlen(SECURITY_KEY); SecurityParams.Type = SECURITY_TYPE; // // Connect to the Access Point // lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams); if(lRetVal < 0) { UART_PRINT("Connection to AP failed\n\r",lRetVal); LOOP_FOREVER(); } // // 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); // // Create UDP socket // iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, 0); if(iSocketDesc < 0) { DBG_PRINT("HIB: Socket create failed\n\r"); goto end; } DBG_PRINT("HIB: Socket created\n\r"); // // Assign socket structure values for a braodcast message // sBroadcastAddr.sin_family = AF_INET; sBroadcastAddr.sin_addr.s_addr= sl_Htonl(0xFFFFFFFF); sBroadcastAddr.sin_port= sl_Htons(APP_UDP_PORT); // // Broadcast message // lRetVal = sendto(iSocketDesc, (char *)&pcBroadcastMessage[0], sizeof(pcBroadcastMessage), 0, (struct sockaddr *)&sBroadcastAddr,sizeof(sBroadcastAddr)); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } UNUSED(lRetVal); DBG_PRINT("HIB: sent message\n\r"); // // Close the socket // close(iSocketDesc); DBG_PRINT("HIB: Socket closed\n\r"); // // Stop the driver // lRetVal = Network_IF_DeInitDriver(); if(lRetVal < 0) { UART_PRINT("Failed to stop SimpleLink Device\n\r"); LOOP_FOREVER(); } // // Switch Off RED & Green LEDs to indicate that Device is // disconnected from AP and Simplelink is shutdown // GPIO_IF_LedOff(MCU_IP_ALLOC_IND); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); // // Enter HIB here configuring the wakeup-timer // EnterHIBernate(); end: DBG_PRINT("HIB: Test Complete\n\r"); // // Loop here // LOOP_FOREVER(); }
//**************************************************************************** // //! Task function implementing the gettime functionality using an NTP server //! //! \param none //! //! This function //! 1. Initializes the required peripherals //! 2. Initializes network driver and connects to the default AP //! 3. Creates a UDP socket, gets the NTP server IP address using DNS //! 4. Periodically gets the NTP time and displays the time //! //! \return None. // //**************************************************************************** void GetNTPTimeTask(void *pvParameters) { int iSocketDesc; long lRetVal = -1; UART_PRINT("GET_TIME: Test Begin\n\r"); // // Configure LED // GPIO_IF_LedConfigure(LED1|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); // // Reset The state of the machine // Network_IF_ResetMCUStateMachine(); // // Start the driver // lRetVal = Network_IF_InitDriver(ROLE_STA); if(lRetVal < 0) { UART_PRINT("Failed to start SimpleLink Device\n\r",lRetVal); LOOP_FOREVER(); } // switch on Green LED to indicate Simplelink is properly up GPIO_IF_LedOn(MCU_ON_IND); // Start Timer to blink Red LED till AP connection LedTimerConfigNStart(); // Initialize AP security params SecurityParams.Key = (signed char *)SECURITY_KEY; SecurityParams.KeyLen = strlen(SECURITY_KEY); SecurityParams.Type = SECURITY_TYPE; // // Connect to the Access Point // lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams); if(lRetVal < 0) { UART_PRINT("Connection to an AP failed\n\r"); LOOP_FOREVER(); } // // 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); // // Create UDP socket // iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(iSocketDesc < 0) { ERR_PRINT(iSocketDesc); goto end; } g_sAppData.iSockID = iSocketDesc; UART_PRINT("Socket created\n\r"); // // Get the NTP server host IP address using the DNS lookup // lRetVal = Network_IF_GetHostIP((char*)g_acSNTPserver, \ &g_sAppData.ulDestinationIP); if( lRetVal >= 0) { struct SlTimeval_t timeVal; timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT; // Seconds timeVal.tv_usec = 0; // Microseconds. 10000 microseconds resolution lRetVal = sl_SetSockOpt(g_sAppData.iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO,\ (unsigned char*)&timeVal, sizeof(timeVal)); if(lRetVal < 0) { ERR_PRINT(lRetVal); LOOP_FOREVER(); } while(1) { // // Get the NTP time and display the time // lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS); if(lRetVal < 0) { UART_PRINT("Server Get Time failed\n\r"); break; } // // Wait a while before resuming // MAP_UtilsDelay(SLEEP_TIME); } } else { UART_PRINT("DNS lookup failed. \n\r"); } // // Close the socket // close(iSocketDesc); UART_PRINT("Socket closed\n\r"); end: // // Stop the driver // lRetVal = Network_IF_DeInitDriver(); if(lRetVal < 0) { UART_PRINT("Failed to stop SimpleLink Device\n\r"); LOOP_FOREVER(); } // // Switch Off RED & Green LEDs to indicate that Device is // disconnected from AP and Simplelink is shutdown // GPIO_IF_LedOff(MCU_IP_ALLOC_IND); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); UART_PRINT("GET_TIME: Test Complete\n\r"); // // Loop here // LOOP_FOREVER(); }
/* * ::socket() */ int socket(int domain, int type, int protocol) { switch (domain) { case AF_INET: domain = SL_AF_INET; break; case AF_INET6: domain = SL_AF_INET6; break; case AF_PACKET: domain = SL_AF_PACKET; break; default: errno = EAFNOSUPPORT; return -1; } switch (type) { case SOCK_STREAM: type = SL_SOCK_STREAM; break; case SOCK_DGRAM: type = SL_SOCK_DGRAM; break; case SOCK_RAW: type = SL_SOCK_RAW; break; default: errno = EINVAL; return -1; } switch (protocol) { case 0: break; case IPPROTO_TCP: protocol = SL_IPPROTO_TCP; break; case IPPROTO_UDP: protocol = SL_IPPROTO_UDP; break; case IPPROTO_RAW: protocol = SL_IPPROTO_RAW; break; default: errno = EINVAL; return -1; } int result = sl_Socket(domain, type, protocol); if (result < 0) { switch (result) { default: errno = EINVAL; break; case SL_EAFNOSUPPORT: errno = EAFNOSUPPORT; break; case SL_EPROTOTYPE: errno = EPROTOTYPE; break; case SL_EACCES: errno = EACCES; break; case SL_ENSOCK: errno = EMFILE; break; case SL_POOL_IS_EMPTY: case SL_ENOMEM: errno = ENOMEM; break; case SL_EINVAL: errno = EINVAL; break; case SL_EPROTONOSUPPORT: errno = EPROTONOSUPPORT; break; case SL_EOPNOTSUPP: errno = EOPNOTSUPP; break; } return -1; } return result; }
//**************************************************************************** // //! \brief Opening a TCP 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 // //**************************************************************************** int BsdTcpServer(unsigned short usPort) { SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; int iCounter; int iAddrSize; int iSockID; int iStatus; int iNewSockID; unsigned long lLoopCount = 0; long lBytesSent = 0; long lNonBlocking = 1; int iTestBufLen; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10) + '0'; } iTestBufLen = BUF_SIZE; //filling the TCP server socket address sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short)usPort); sLocalAddr.sin_addr.s_addr = 0; // sLocalAddr.sin_port = usPort; // sLocalAddr.sin_addr.s_addr = SL_IPV4_VAL(192,168,1,101); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { UART_PRINT("error at creating a TCP socket ! \n\r"); // error return -1; } UART_PRINT("iSockID :"); Z_NumDispaly(iSockID, 2); iAddrSize = sizeof(SlSockAddrIn_t); // binding the TCP socket to the TCP server address iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize); if( iStatus < 0 ) { UART_PRINT("error at binding the TCP socket to the TCP server address ! \n\r"); // error return -1; } UART_PRINT("binding the TCP socket to the TCP server address ok! \n\r"); // putting the socket for listening to the incoming TCP connection iStatus = sl_Listen(iSockID, 0); if( iStatus < 0 ) { UART_PRINT("error at putting the socket for listening to the incoming TCP connection ! \n\r"); return -1; } UART_PRINT("listen end! \n\r"); // setting socket option to make the socket as non blocking iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); iNewSockID = SL_EAGAIN; UART_PRINT(" waiting for an incoming TCP connection! \n\r"); // waiting for an incoming TCP connection while( iNewSockID < 0 ) { // accepts a connection form a TCP client, if there is any // otherwise returns SL_EAGAIN iNewSockID = sl_Accept(iSockID, ( struct SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize); if( iNewSockID == SL_EAGAIN ) { UtilsDelay(10000); // UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); } else if( iNewSockID < 0 ) { // error UART_PRINT(" iNewSockID < 0! \n\r"); return -1; } } UART_PRINT("connect succeed the new iSockID :"); Z_NumDispaly(iSockID, 5); unsigned long the_client_ip = sl_BIGtoLITTLE_l( (unsigned long)sAddr.sin_addr.s_addr ); UART_PRINT("the client ip is :"); Z_IPDispaly(&the_client_ip); unsigned short the_client_port = sl_BIGtoLITTLE_S( (unsigned short)sAddr.sin_port ); UART_PRINT("the client port is :"); Z_NumDispaly( (unsigned long)the_client_port,5); /* UART_PRINT(" waits for 1000 packets from the connected TCP client! \n\r"); // waits for 1000 packets from the connected TCP client while (lLoopCount < 1000) { iStatus = sl_Recv(iNewSockID, g_cBsdBuf, iTestBufLen, 0); if( iStatus <= 0 ) { // error return -1; } lLoopCount++; lBytesSent += iStatus; } */ // sending 3 packets to the TCP server while (lLoopCount < 3) { // sending packet // iStatus = sl_Send(iNewSockID, g_cBsdBuf, iTestBufLen, 0 ); char *send_buffer = "hellow i am cc3200 , welcome to wifi world !\n\r"; iStatus = sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 ); if( iStatus <= 0 ) { UART_PRINT("error at sending packet\n\r"); Z_NumDispaly(lLoopCount,5); // error return -1; } lLoopCount++; lBytesSent += iStatus; } Sl_WlanNetworkEntry_t netEntries[20]; char message[80]; unsigned long intervalInSeconds = 10; sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds)); while(1){ //Get Scan Result UINT8 Index = sl_WlanGetNetworkList(0,20,&netEntries[0]); for(UINT8 i=0; i< Index; i++) { snprintf(message, 60, "%d) SSID %s RSSI %d \n\r",i,netEntries[i].ssid,netEntries[i].rssi); UART_PRINT(message); sl_Send(iNewSockID, message, strlen(message), 0 ); } Z_DelayS(3); } // close the connected socket after receiving from connected TCP client sl_Close(iNewSockID); // close the listening socket sl_Close(iSockID); return 0; }
/**************************************************************************** // //! \brief Opening a TCP client side socket and sending data //! //! This function opens a TCP socket and tries to connect to a Server IP_ADDR //! waiting on port PORT_NUM. //! If the socket connection is successful then the function will send 1000 //! TCP packets to the server. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. // ****************************************************************************/ int BsdTcpClient(unsigned short usPort) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; unsigned long lLoopCount = 0; long lBytesSent = 0; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; // sAddr.sin_port = usPort; // sAddr.sin_addr.s_addr = IP_ADDR ; sAddr.sin_port = sl_Htons((unsigned short)usPort); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)IP_ADDR); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { UART_PRINT("error at creating a TCP socket ! \n\r"); // error return -1; } UART_PRINT("iSockID :"); Z_NumDispaly(iSockID, 2); // connecting to TCP server iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { UART_PRINT("error at connecting to TCP server ! \n\r"); // error return -1; } UART_PRINT(" connected to TCP server ok! \n\r"); // sending 1000 packets to the TCP server while (lLoopCount < 1000) { // sending packet iStatus = sl_Send(iSockID, g_cBsdBuf, sTestBufLen, 0 ); if( iStatus <= 0 ) { UART_PRINT("error at sending packet"); Z_NumDispaly(lLoopCount,2); // error return -1; } lLoopCount++; lBytesSent += iStatus; } //closing the socket after sending 1000 packets sl_Close(iSockID); return 0; }