static int32_t Lab16(void){uint32_t i; char *pt = NULL; memcpy(appData.HostName,SERVER,strlen(SERVER)); if(GetHostIP() == 0){ if( (appData.SockID = CreateConnection()) < 0 ) return -1; /* HTTP GET string. */ strcpy(appData.SendBuff,REQUEST); // 1) change Austin Texas to your city // 2) you can change metric to imperial if you want temperature in F /* Send the HTTP GET string to the open TCP/IP socket. */ sl_Send(appData.SockID, appData.SendBuff, strlen(appData.SendBuff), 0); /* Receive response */ sl_Recv(appData.SockID, &appData.Recvbuff[0], MAX_RECV_BUFF_SIZE, 0); appData.Recvbuff[strlen(appData.Recvbuff)] = '\0'; /* find ticker name in response*/ pt = strstr(appData.Recvbuff, "id"); i = 0; if( NULL != pt ){ pt = pt + 5; // skip over id":" while((i<MAXLEN)&&(*pt)&&(*pt!='\"')){ Id[i] = *pt; // copy into Id string pt++; i++; } } Id[i] = 0; /* find score Value in response */ pt = strstr(appData.Recvbuff, "\"score\""); i = 0; if( NULL != pt ){ pt = pt + 8; // skip over "score": while((i<MAXLEN)&&(*pt)&&(*pt!=',')){ Score[i] = *pt; // copy into Score string pt++; i++; } } Score[i] = 0; /* find edxpost in response */ pt = strstr(appData.Recvbuff, "edxpost"); i = 0; if( NULL != pt ){ pt = pt + 9; // skip over edxpost": for(i=0; i<8; i++){ Edxpost[i] = *pt; // copy into Edxpost string pt++; } } Edxpost[i] = 0; sl_Close(appData.SockID); } return 0; }
void WeatherForecastGet(int iSockID, cInt8 * acSendBuff,cInt8 * acRecvbuff) { int iTXStatus; int iRXDataStatus; char* pcBufLocation; const char prefixBuffer[] = "GET /data/2.5/forecast?"; const char postBuffer[] = "&mode=xml&units=metric HTTP/1.1\r\nHost: api.openweathermap.org\r\nAccept: */"; const char postBuffer2[] = "*\r\n\r\n"; memset(acRecvbuff, 0, RX_BUFF_SIZE); // Puts together the HTTP GET string. // pcBufLocation = acSendBuff; strcpy(pcBufLocation, prefixBuffer); pcBufLocation += strlen(prefixBuffer); #ifdef LOCATION_GPS int l_size; l_size = sprintf(pcBufLocation,"lat=%.6f&lon=%.6f",LOCATION_GPS_LAT,LOCATION_GPS_LON); pcBufLocation += l_size; #else strcpy(pcBufLocation,"q="); pcBufLocation += strlen("q="); strcpy(pcBufLocation,LOCATION_CITY_NAME); pcBufLocation += strlen(LOCATION_CITY_NAME); #endif strcpy(pcBufLocation, postBuffer); pcBufLocation += strlen(postBuffer); strcpy(pcBufLocation, postBuffer2); // // Send the HTTP GET string to the open TCP/IP socket. // DBG_PRINT("Sent HTTP GET request. \n\r"); iTXStatus = sl_Send(iSockID, acSendBuff, strlen(acSendBuff), 0); MAP_UtilsDelay(DELAY_CLK_1_SEK *3); DBG_PRINT("Return value: %d \n\r", iTXStatus); // // Store the reply from the server in buffer. // DBG_PRINT("Received HTTP GET response data. \n\r"); iRXDataStatus = sl_Recv(iSockID, &acRecvbuff[0], RX_BUFF_SIZE, 0); DBG_PRINT("Return value: %d \n\r", iRXDataStatus); acRecvbuff[RX_BUFF_SIZE - 1] = 0; DBG_PRINT(acRecvbuff); }
/*! \brief This function opens a raw socket, receives the frames and display them. \param[in] channel : channel for the raw socket \param[in] numpackets : number of packets to be received \return 0 for success, -ve otherwise \note \warning */ static _i32 Sniffer(_i32 channel,_i32 numpackets) { TransceiverRxOverHead_t *frameRadioHeader = 0; _u8 MAC[MAX_RECV_BUF_SIZE] = {'\0'}; _u8 hexempty = 0xcc; _i32 retVal = -1; _i16 sd = -1; /********************* Open Socket for transceiver *********************/ sd = sl_Socket(SL_AF_RF,SL_SOCK_RAW,(_i16)channel); ASSERT_ON_ERROR(sd); /************************************ Creating filters *****************/ retVal = ChooseFilters(); ASSERT_ON_ERROR(retVal); /************ Receiving frames from the CC3100 and printing to screen*****/ if (!g_Exit) { printf("\nCollecting Packets...\n"); while(numpackets > 0) { retVal = sl_Recv(sd,buffer,MAX_RECV_BUF_SIZE,0); ASSERT_ON_ERROR(retVal); frameRadioHeader = (TransceiverRxOverHead_t *)buffer; printf("\nTimestamp: %i microsec\n",frameRadioHeader->timestamp); printf("Signal Strength: %i dB\n",frameRadioHeader->rssi); memcpy(MAC, buffer, sizeof(buffer)); PrintFrameSubtype(MAC[8]); printf("Destination MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n", MAC[12],MAC[13], MAC[14],MAC[15], MAC[16],MAC[17]); printf("Source MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n", MAC[18],MAC[19], MAC[20],MAC[21], MAC[22],MAC[23]); numpackets--; Sleep(500); } } retVal = sl_Close(sd); ASSERT_ON_ERROR(retVal); return SUCCESS; }
static telnet_result_t telnet_recv_text_non_blocking (void *buff, _i16 Maxlen, _i16 *rxLen) { *rxLen = sl_Recv(telnet_data.n_sd, buff, Maxlen, 0); // if there's data received, parse it if (*rxLen > 0) { telnet_data.timeout = 0; telnet_parse_input (buff, rxLen); if (*rxLen > 0) { return E_TELNET_RESULT_OK; } } else if (*rxLen != SL_EAGAIN) { // error telnet_reset(); return E_TELNET_RESULT_FAILED; } return E_TELNET_RESULT_AGAIN; }
char* HTTP_Request(const char *hostName, uint16_t port, const char *method, const char *request, char *requestData1, char *requestData2) { SlSockAddrIn_t Addr; int32_t retVal; uint32_t ASize = 0; cleanup(); strcpy(HostName, hostName); UARTprintf("\r\n\r\nUsing host: %s\r\n", HostName); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(port); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = -1; SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ uint32_t copyIndex = 0; strcpy(&SendBuff[copyIndex], method); copyIndex += strlen(method); strcpy(&SendBuff[copyIndex], " "); copyIndex += 1; strcpy(&SendBuff[copyIndex], request); copyIndex += strlen(request); if(requestData1) { strcpy(&SendBuff[copyIndex], requestData1); copyIndex += strlen(requestData1); } if(requestData2) { strcpy(&SendBuff[copyIndex], requestData2); copyIndex += strlen(requestData2); } strcpy(&SendBuff[copyIndex], REQ_1); copyIndex += strlen(REQ_1); strcpy(&SendBuff[copyIndex], hostName); copyIndex += strlen(hostName); strcpy(&SendBuff[copyIndex], REQ_2); copyIndex += strlen(REQ_2); SendBuff[copyIndex] = '\0'; UARTprintf("Sending request: %s\r\n\r\n", SendBuff); sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); return Recvbuff; } } return NULL; }
int cc3200_read(Network* n, unsigned char* buffer, int len, int timeout_ms) { SlTimeval_t timeVal; SlFdSet_t fdset; int rc = 0; int recvLen = 0; SL_FD_ZERO(&fdset); SL_FD_SET(n->my_socket, &fdset); timeVal.tv_sec = 0; timeVal.tv_usec = timeout_ms * 1000; if (sl_Select(n->my_socket + 1, &fdset, NULL, NULL, &timeVal) == 1) { do { rc = sl_Recv(n->my_socket, buffer + recvLen, len - recvLen, 0); recvLen += rc; } while(recvLen < len); } return recvLen; }
/* * ::recv() */ int recv(int socket, void *buffer, size_t length, int flags) { int result = sl_Recv(socket, buffer, length, flags); if (result < 0) { switch (result) { default: errno = EINVAL; break; case SL_POOL_IS_EMPTY: usleep(10000); /* fall through */ case SL_EAGAIN: errno = EAGAIN; break; } return -1; } return result; }
static int UpdateSockets(void) { int retval; for(int i=0; i<NUM_SOCKETS; i++){ if(!GetSockConnected(i)){ if(SockAccept(i) == RET_FAILURE) {RETURN_ERROR(ERROR_UNKNOWN, "Socket accept fail");} } else{ xSemaphoreTake(socket_state[i].buf_access, portMAX_DELAY); //Update TX if(socket_state[i].tx_buf_occupancy){ retval = sl_Send(socket_state[i].child_id, &(socket_state[i].tx_buf[socket_state[i].tx_buf_i_out % SOCKET_RXBUF_SIZE]), MIN(socket_state[i].tx_buf_occupancy, SOCKET_TXBUF_SIZE - (socket_state[i].tx_buf_i_out % SOCKET_RXBUF_SIZE)), //Prevent overflow at wraparound point 0); if(retval<0) { LogSLError(retval); xSemaphoreGive(socket_state[i].buf_access); RETURN_ERROR(retval, "Socket send fail"); } else{ socket_state[i].tx_buf_occupancy -= retval; socket_state[i].tx_buf_i_out += retval; } } if((xSemaphoreTake(socket_state[i].tx_buf_full, 0) == pdFALSE) //poll semaphore && (socket_state[i].tx_buf_occupancy<SOCKET_TXBUF_SIZE)){ xSemaphoreGive(socket_state[i].tx_buf_full); //unblock threads waiting for space } //Update RX retval = sl_Recv(socket_state[i].child_id, &(socket_state[i].rx_buf[socket_state[i].rx_buf_i_in % SOCKET_RXBUF_SIZE]), MIN((SOCKET_RXBUF_SIZE - socket_state[i].rx_buf_occupancy), SOCKET_RXBUF_SIZE - (socket_state[i].rx_buf_i_in % SOCKET_RXBUF_SIZE)), //Prevent overflow at wraparound point 0); if(retval > 0){ socket_state[i].rx_buf_i_in += retval; socket_state[i].rx_buf_occupancy += retval; if(xSemaphoreTake(socket_state[i].rx_buf_empty, 0) == pdFALSE) { //poll semaphore xSemaphoreGive(socket_state[i].rx_buf_empty); //unblock threads waiting for characters } } else if(retval==0){ socket_state[i].status = SOCKET_STARTED; LOG(LOG_VERBOSE, "Socket %d: client disconnected/broken.", i); sl_Close(socket_state[i].child_id); } else if((retval<0) && (retval!=SL_EAGAIN)) { LogSLError(retval); xSemaphoreGive(socket_state[i].buf_access); RETURN_ERROR(retval, "Socket recv fail"); } xSemaphoreGive(socket_state[i].buf_access); } } return RET_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(UINT16 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((UINT16)Port); LocalAddr.sin_addr.s_addr = 0; SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID < 0 ) { /* error */ return -1; } AddrSize = sizeof(SlSockAddrIn_t); Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize); if( Status < 0 ) { /* error */ sl_Close(SockID); return -1; } Status = sl_Listen(SockID, 0); if( Status < 0 ) { sl_Close(SockID); return -1; } Status = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlocking, sizeof(nonBlocking)); if( Status < 0 ) { return -1; } newSockID = SL_EAGAIN; while( newSockID < 0 ) { 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); return -1; } } while (LoopCount < TCP_PACKET_COUNT) { Status = sl_Recv(newSockID, uBuf.BsdBuf, BUF_SIZE, 0); if( Status <= 0 ) { /* error */ sl_Close(newSockID); sl_Close(SockID); return -1; } LoopCount++; } GPIO_IF_LedOn(MCU_EXECUTE_SUCCESS_IND); sl_Close(newSockID); sl_Close(SockID); return 0; }
//***************************************************************************** // //! Gets the current time from the selected SNTP server //! //! \brief This function obtains the NTP time from the server. //! //! \param pGetTime is pointer to Get time structure //! //! \return 0 : success, -ve : failure //! // //***************************************************************************** long GetSNTPTime(tGetTime *pGetTime) { /* NTP Packet Header: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |LI | VN |Mode | Stratum | Poll | Precision | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Delay | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Dispersion | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reference Identifier | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Reference Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Originate Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Receive Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Transmit Timestamp (64) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Key Identifier (optional) (32) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | | | Message Digest (optional) (128) | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ char cDataBuf[48]; long lRetVal = 0; SlSockAddr_t sAddr; unsigned long ulElapsedSec; // // Send a query ? to the NTP server to get the NTP time // memset(cDataBuf, 0, sizeof(cDataBuf)); cDataBuf[0] = '\x1b'; sAddr.sa_family = AF_INET; // the source port sAddr.sa_data[0] = 0x00; sAddr.sa_data[1] = 0x7B; // UDP port number for NTP is 123 sAddr.sa_data[2] = (char)((pGetTime->ulNtpServerIP >>24)&0xff); sAddr.sa_data[3] = (char)((pGetTime->ulNtpServerIP >>16)&0xff); sAddr.sa_data[4] = (char)((pGetTime->ulNtpServerIP >>8)&0xff); sAddr.sa_data[5] = (char)(pGetTime->ulNtpServerIP&0xff); lRetVal = sl_SendTo(pGetTime->iSocket, cDataBuf, sizeof(cDataBuf), 0, &sAddr, sizeof(sAddr)); if (lRetVal != sizeof(cDataBuf)) { return FAILURE; } lRetVal = sl_Recv(pGetTime->iSocket, cDataBuf, sizeof(cDataBuf), 0); // // Confirm that the MODE is 4 --> server // if ((cDataBuf[0] & 0x7) != 4) // expect only server response { return FAILURE; } else { // // Getting the data from the Transmit Timestamp (seconds) field // This is the time at which the reply departed the // server for the client // ulElapsedSec = cDataBuf[40]; ulElapsedSec <<= 8; ulElapsedSec += cDataBuf[41]; ulElapsedSec <<= 8; ulElapsedSec += cDataBuf[42]; ulElapsedSec <<= 8; ulElapsedSec += cDataBuf[43]; // // Compute the UTC time // TimeToString(ulElapsedSec, sDisplayInfo.ucUTCTime); // // Set the time zone // ulElapsedSec += (pGetTime->ucGmtDiffHr * SEC_IN_HOUR); ulElapsedSec += (pGetTime->ucGmtDiffMins * SEC_IN_MIN); // // Compute the local time // TimeToString(ulElapsedSec, sDisplayInfo.ucLocalTime); } return SUCCESS; }
int GetFileFromServer(const int socket, const char* filename, const char* filenameInFlash) { int transfer_len = 0; long retVal = 0; long fileHandle = -1; unsigned long Token = 0, bytesReceived = 0; unsigned char *pBuff = 0; unsigned long file_size = 0; unsigned char buffer[MAX_BUFF_SIZE + 1]; UART_PRINT("Start downloading the file %s\r\n", filename); memset(buffer, 0, sizeof(buffer)); // Puts together the HTTP GET string. strcpy((char *) buffer, PREFIX_BUFFER); strcat((char *) buffer, filename); strcat((char *) buffer, POST_BUFFER); // Send the HTTP GET string to the opened TCP/IP socket. transfer_len = sl_Send(socket, buffer, strlen((const char *) buffer), 0); if (transfer_len < 0) { // error UART_PRINT("Socket Send Error\r\n"); return -1; } memset(buffer, 0, sizeof(buffer)); // get the reply from the server in buffer. transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0); if (transfer_len > 0) { // Check for 404 return code if (strstr((const char *) buffer, HTTP_FILE_NOT_FOUND) != 0) { UART_PRINT("File not found, check the file and try again\r\n"); return -1; } // if not "200 OK" return error if (strstr((const char *) buffer, HTTP_STATUS_OK) == 0) { UART_PRINT("Error during downloading the file\r\n"); return -1; } // check if content length is transfered with headers pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_CONTENT_LENGTH); if (pBuff != 0) { pBuff += strlen(HTTP_CONTENT_LENGTH); while (*pBuff != 0x0d) pBuff++; unsigned long multiplicant = 1; pBuff--; while (*pBuff != ' ') { file_size += (*pBuff - '0') * multiplicant; multiplicant *= 10; pBuff--; } if (file_size == 0) { UART_PRINT("\nContent Length not detected.\r\n"); return -1; } UART_PRINT("Content Length %d\r\n", file_size); } else { UART_PRINT("\nContent Length not detected.\r\n"); return -1; } // "\r\n\r\n" marks the end of headers pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_END_OF_HEADER); if (pBuff == 0) { UART_PRINT("Invalid response\r\n"); return -1; } // Increment by 4 to skip "\r\n\r\n" pBuff += 4; // Adjust buffer data length for header size transfer_len -= (pBuff - buffer); } // Delete eventually existing temporary file sl_FsDel((unsigned char *) filenameInFlash, Token); // Create a temporary file to save the downloaded file // open a user file for writing retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_WRITE, &Token, &fileHandle); if (retVal < 0) { // File Doesn't exit create a new of file_size KB file retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_CREATE(file_size, _FS_FILE_PUBLIC_WRITE), &Token, &fileHandle); if (retVal < 0) { UART_PRINT("Error during opening the temporary file\r\n"); return -1; } } while (bytesReceived < file_size) { retVal = sl_FsWrite(fileHandle, bytesReceived, (unsigned char *) pBuff, transfer_len); if (retVal < 0) { retVal = sl_FsClose(fileHandle, 0, 0, 0); retVal = sl_FsDel((unsigned char *) filenameInFlash, Token); UART_PRINT("Error during writing the file\r\n"); return -1; } bytesReceived += transfer_len; if (bytesReceived == file_size) break; memset(buffer, 0, sizeof(buffer)); transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0); pBuff = buffer; } // Close the opened file retVal = sl_FsClose(fileHandle, 0, 0, 0); if (bytesReceived != file_size) { UART_PRINT("Error While File Download\r\n"); retVal = sl_FsDel((unsigned char *) filenameInFlash, Token); return -1; } else { UART_PRINT("\nDownloading File Completed\r\n"); } return 0; }
int main(void){int32_t retVal; SlSecParams_t secParams; char *pConfig = NULL; INT32 ASize = 0; SlSockAddrIn_t Addr; ADC0_InitSWTriggerSeq3_Ch9(); // allow time to finish activating initClk(); // PLL 50 MHz Output_On(); UART_Init(); // Send data to PC, 115200 bps Timer1_Init(); LED_Init(); // initialize LaunchPad I/O UARTprintf("Weather App\n"); retVal = configureSimpleLinkToDefaultState(pConfig); // set policies if(retVal < 0)Crash(4000000); retVal = sl_Start(0, pConfig, 0); if((retVal < 0) || (ROLE_STA != retVal) ) Crash(8000000); secParams.Key = PASSKEY; secParams.KeyLen = strlen(PASSKEY); secParams.Type = SEC_TYPE; // OPEN, WPA, or WEP sl_WlanConnect(SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0); while((0 == (g_Status&CONNECTED)) || (0 == (g_Status&IP_AQUIRED))){ _SlNonOsMainLoopTask(); } UARTprintf("Connected\n"); while(1){ int i = 0; while(i < 10){ int sendc = 0; strcpy(HostName,"openweathermap.org"); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ strcpy(SendBuff,REQUEST); sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); LED_GreenOn(); UARTprintf("\r\n\r\n"); UARTprintf(Recvbuff); UARTprintf("\r\n"); } } ST7735_OutUDec(sendc); ST7735_OutString("\n"); i++; } //while(Board_Input()==0){}; // wait for touch LED_GreenOff(); //Temp Part e getTemp(Recvbuff); ST7735_OutChar('T'); ST7735_OutChar('e'); ST7735_OutChar('m'); ST7735_OutChar('p'); ST7735_OutChar(' '); ST7735_OutChar('='); ST7735_OutChar(' '); for(int i = 0; i < 5; i++){ ST7735_OutChar(myArray[i]); } ST7735_OutChar('\n'); //ADC Part f ADC0_SAC_R = ADC_SAC_AVG_64X; //enable 64 times average before obtaining result int voltage = ADC0_InSeq3(); ST7735_OutString("Voltage~"); ST7735_sDecOut3(voltage); char* voltageString; char voltageStringNum[5]; sprintf(voltageStringNum, "%.1d.%.3d", voltage/1000, voltage%1000); //ST7735_OutString(voltageStringNum); char* sendString; char str1[173] = "GET /query?city=Austin%20Texas&id=Ty%20Winkler%20Jeremiah%20Bartlett&greet=Voltage%3D"; strcat(str1, voltageStringNum); strcat(str1, "V&edxcode=8086 HTTP/1.1\r\nUser-Agent: Keil\r\nHost: embsysmooc.appspot.com\r\n\r\n"); strcpy(HostName,"embsysmooc.appspot.com"); retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET); if(retVal == 0){ Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian ASize = sizeof(SlSockAddrIn_t); SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( SockID >= 0 ){ retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize); } if((SockID >= 0)&&(retVal >= 0)){ strcpy(SendBuff, str1); count = 0; sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response sl_Close(SockID); LED_GreenOn(); UARTprintf("\r\n\r\n"); //ST7735_OutString(Recvbuff); UARTprintf("\r\n"); } } while(1); } }
static int http_post(int iTLSSockID, char data[200]){ char acSendBuff[512]; char acRecvbuff[1460]; char cCLLength[200]; char* pcBufHeaders; int lRetVal = 0; pcBufHeaders = acSendBuff; strcpy(pcBufHeaders, POSTHEADER); pcBufHeaders += strlen(POSTHEADER); strcpy(pcBufHeaders, " HTTP/1.1\r\n"); pcBufHeaders += strlen(" HTTP/1.1\r\n"); strcpy(pcBufHeaders, HOSTHEADER); pcBufHeaders += strlen(HOSTHEADER); // strcpy(pcBufHeaders, CHEADER0); pcBufHeaders += strlen(CHEADER0); // strcpy(pcBufHeaders, CHEADER); pcBufHeaders += strlen(CHEADER); strcpy(pcBufHeaders, "\r\n\r\n"); //calculates the length of the message, DATA1 + text message + DATA2 int dataLength = strlen(DATA1); dataLength += strlen(data); dataLength += strlen(DATA3); 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, data); pcBufHeaders += strlen(data); strcpy(pcBufHeaders, DATA3); pcBufHeaders += strlen(DATA3); int testDataLength = strlen(pcBufHeaders); // // Send the packet to the server */ // printf("%s\n", acSendBuff); lRetVal = sl_Send(iTLSSockID, acSendBuff, strlen(acSendBuff), 0); if(lRetVal < 0) { UART_PRINT("POST failed. Error Number: %i\n\r",lRetVal); sl_Close(iTLSSockID); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } lRetVal = sl_Recv(iTLSSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0); if(lRetVal < 0) { UART_PRINT("Received failed. Error Number: %i\n\r",lRetVal); //sl_Close(iSSLSockID); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } else { acRecvbuff[lRetVal+1] = '\0'; UART_PRINT(acRecvbuff); UART_PRINT("\n\r\n\r"); } return 0; }
void ControlServer(void *pvParameters) { char ServerBuffer[CONFIG_SERVER_BUFFER]; char MsgBuffer[100]; char *pMsgBuffer; SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; int32_t i32SockID; int32_t i32NewSockID; int32_t i32DataSize; int32_t i32NonBlocking = 1; SlSocklen_t i32AddrSize; int32_t retval; pMsgBuffer = &MsgBuffer[0]; InitVariables(); retval = ResetSimpleLink(); if (retval < 0) while (1) ; WlanConnect(); sprintf(MsgBuffer, "Connectado a rede: %s\n\r" "IP: %d.%d.%d.%d\n\r" "Gateway: %d.%d.%d.%d\n\r", SL_IPV4_BYTE(g_sSLCon.DeviceIP, 3), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 2), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 1), SL_IPV4_BYTE(g_sSLCon.DeviceIP, 0), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 3), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 2), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 1), SL_IPV4_BYTE(g_sSLCon.GatewayIP, 0)); osi_MsgQWrite(&g_sUartQuee, &pMsgBuffer, OSI_NO_WAIT); sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short) g_sSLCon.PortNumber); sLocalAddr.sin_addr.s_addr = 0; i32SockID = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0); sl_Bind(i32SockID, (SlSockAddr_t *) &sLocalAddr, sizeof(SlSockAddrIn_t)); sl_Listen(i32SockID, 0); sl_SetSockOpt(i32SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &i32NonBlocking, sizeof(i32NonBlocking)); while (1) { i32NewSockID = SL_EAGAIN; while (i32NewSockID < 0) { i32NewSockID = sl_Accept(i32SockID, (struct SlSockAddr_t *) &sAddr, (SlSocklen_t*) &i32AddrSize); if (i32NewSockID == SL_EAGAIN) { osi_Sleep(100); } else if (i32NewSockID < 0) { while (1) { } } } i32DataSize = sl_Recv(i32NewSockID, ServerBuffer, CONFIG_SERVER_BUFFER, 0); if (strcmp(ServerBuffer, "Led On") == 0) { Led_Green(LED_ON); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Led Off") == 0) { Led_Green(LED_OFF); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Lamp On") == 0) { MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, GPIO_PIN_6); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } else if (strcmp(ServerBuffer, "Lamp Off") == 0) { MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, 0); strcpy(ServerBuffer, "OK"); i32DataSize = 3; } sl_Send(i32NewSockID, ServerBuffer, i32DataSize, 0); sl_Close(i32NewSockID); } }
//***************************************************************************** // //! 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; }
//--tested, working--// //--client and server side--// int WiFiClient::available() { // //don't do anything if not properly set up // if (_socketIndex == NO_SOCKET_AVAIL) { return 0; } // //if the buffer doesn't have any data in it or we've read everything //then receive some data // int bytesLeft = rx_fillLevel - rx_currentIndex; if (bytesLeft <= 0) { SlTimeval_t timeout; memset(&timeout, 0, sizeof(SlTimeval_t)); timeout.tv_sec = 0; timeout.tv_usec = 500; SlFdSet_t readsds, errorsds; SL_FD_ZERO(&readsds); SL_FD_ZERO(&errorsds); SL_FD_SET(WiFiClass::_handleArray[_socketIndex], &readsds); SL_FD_SET(WiFiClass::_handleArray[_socketIndex], &errorsds); // sl_Select(WiFiClass::_handleArray[_socketIndex] + 1, &readsds, NULL, &errorsds, &timeout); // if(!SL_FD_ISSET(WiFiClass::_handleArray[_socketIndex], &readsds)) return 0; // //Receive any pending information into the buffer //if the connection has died, call stop() to make the object aware it's dead // int iRet = sl_Recv(WiFiClass::_handleArray[_socketIndex], rx_buffer, TCP_RX_BUFF_MAX_SIZE, 0); if ((iRet <= 0) && (iRet != SL_EAGAIN)) { sl_Close(WiFiClass::_handleArray[_socketIndex]); WiFiClass::_portArray[_socketIndex] = -1; WiFiClass::_handleArray[_socketIndex] = -1; WiFiClass::_typeArray[_socketIndex] = -1; _socketIndex = NO_SOCKET_AVAIL; memset(rx_buffer, 0, TCP_RX_BUFF_MAX_SIZE); return 0; } // //receive successful. Reset rx index pointer and set buffer fill level indicator //(if SL_EAGAIN was received, the actual number of bytes received was zero, not -11) // rx_currentIndex = 0; rx_fillLevel = (iRet != SL_EAGAIN) ? iRet : 0; bytesLeft = rx_fillLevel - rx_currentIndex; } // //limit bytes left to >= 0 // if (bytesLeft < 0) { bytesLeft = 0; } return bytesLeft; }
//***************************************************************************** // //! 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; }
//**************************************************************************** // //! \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; }
/*! \brief Entering raw Transmitter\Receiver mode in order to perform Rx statistic over a specific WLAN channel \param[in] Channel number on which the statistics will be calculated \return 0 for success, -ve otherwise \note \warning We must be disconnected from WLAN AP in order to succeed changing to Receiver mode */ static _i32 RxStatisticsCollect(_i16 channel) { SlGetRxStatResponse_t rxStatResp; _u8 buffer[MAX_BUF_RX_STAT] = {'\0'}; _u8 var[MAX_BUF_SIZE] = {'\0'}; _i32 idx = -1; _i16 sd = -1; _i32 retVal = -1; memset(&rxStatResp, 0, sizeof(rxStatResp)); sd = sl_Socket(SL_AF_RF,SL_SOCK_RAW,channel); if(sd < 0) { printf("Error In Creating the Socket\n"); ASSERT_ON_ERROR(sd); } retVal = sl_Recv(sd, buffer, BYTES_TO_RECV, 0); ASSERT_ON_ERROR(retVal); printf("Press \"Enter\" to start collecting statistics.\n"); fgets((char *)var, sizeof(var), stdin); retVal = sl_WlanRxStatStart(); ASSERT_ON_ERROR(retVal); printf("Press \"Enter\" to get the statistics.\n"); fgets((char *)var, sizeof(var), stdin); retVal = sl_WlanRxStatGet(&rxStatResp, 0); ASSERT_ON_ERROR(retVal); printf("\n\n*********************Rx Statistics**********************\n\n"); printf("Received Packets - %d\n",rxStatResp.ReceivedValidPacketsNumber); printf(" Received FCS - %d\n",rxStatResp.ReceivedFcsErrorPacketsNumber); printf(" Received PLCP - %d\n",rxStatResp.ReceivedPlcpErrorPacketsNumber); printf("Average Rssi for management: %d Average Rssi for other packets: %d\n", rxStatResp.AvarageMgMntRssi,rxStatResp.AvarageDataCtrlRssi); for(idx = 0 ; idx < SIZE_OF_RSSI_HISTOGRAM ; idx++) { printf("Rssi Histogram cell %d is %d\n", idx, rxStatResp.RssiHistogram[idx]); } printf("\n"); for(idx = 0 ; idx < NUM_OF_RATE_INDEXES; idx++) { printf("Rate Histogram cell %d is %d\n", idx, rxStatResp.RateHistogram[idx]); } printf("The data was sampled in %u microseconds.\n", ((_i16)rxStatResp.GetTimeStamp - rxStatResp.StartTimeStamp)); printf("\n\n*******************End Rx Statistics********************\n"); retVal = sl_WlanRxStatStop(); ASSERT_ON_ERROR(retVal); retVal = sl_Close(sd); ASSERT_ON_ERROR(retVal); return SUCCESS; }
//***************************************************************************** // //! 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; }