//***************************************************************************** // //! Tx_continuous //! //! This function //! 1. Function for sending out pinging data on the //! channel given by the user. //! //! \return none // //***************************************************************************** static int Tx_continuous(int iChannel,SlRateIndex_e rate,int iNumberOfPackets, int iTxPowerLevel,long dIntervalMiliSec) { int iSoc; long lRetVal = -1; long ulIndex; iSoc = sl_Socket(SL_AF_RF,SL_SOCK_RAW,iChannel); ASSERT_ON_ERROR(iSoc); UART_PRINT("Transmitting data...\r\n"); for(ulIndex = 0 ; ulIndex < iNumberOfPackets ; ulIndex++) { lRetVal = sl_Send(iSoc,RawData_Ping,sizeof(RawData_Ping),\ SL_RAW_RF_TX_PARAMS(iChannel, rate, iTxPowerLevel, PREAMBLE)); if(lRetVal < 0) { sl_Close(iSoc); ASSERT_ON_ERROR(lRetVal); } //Sleep(dIntervalMiliSec); MAP_UtilsDelay(4000000); } lRetVal = sl_Close(iSoc); ASSERT_ON_ERROR(lRetVal); UART_PRINT("Transmission complete.\r\n"); return SUCCESS; }
static int SockAccept(unsigned int slot) { if(!IS_SOCK_STARTED(slot) || IS_SOCK_CONNECTED(slot)) {RETURN_ERROR(ERROR_UNKNOWN, "Uninit fail")}; int addrsize = sizeof(SlSockAddrIn_t); int newid = sl_Accept(socket_state[slot].parent_id, (SlSockAddr_t*)&(socket_state[slot].addr_local), (SlSocklen_t *) &addrsize); if((newid != SL_EAGAIN) && (newid>=0)){ LOG(LOG_VERBOSE, "Socket %d: client connected.", slot); socket_state[slot].status |= SOCKET_CONNECTED; socket_state[slot].child_id = newid; //set to non-blocking again long nonblock = 1; int retval = sl_SetSockOpt(socket_state[slot].child_id, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonblock, sizeof(nonblock)); if(retval < 0){ sl_Close(socket_state[slot].child_id); RETURN_ERROR(retval, "Socket opt fail"); } if(slot == SOCKET_LOG){ mem_log_start_putchar(&ExtThread_LogSocketPutChar); serialconfig_start(&ExtThread_LogSocketGetChar); } } else if(newid != SL_EAGAIN){ sl_Close(socket_state[slot].child_id); sl_Close(socket_state[slot].parent_id); socket_state[slot].status = 0; RETURN_ERROR(newid, "Socket accept fail"); } return RET_SUCCESS; }
//**************************************************************************** // //! \brief Opening a UDP client side socket and sending data //! //! This function opens a UDP socket and tries to connect to a Server IP_ADDR //! waiting on port PORT_NUM. //! Then the function will send 1000 UDP packets to the server. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, -1 on Error. // //**************************************************************************** int BsdUdpClient(unsigned short usPort) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; // 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 sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)usPort); sAddr.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); if( iSockID < 0 ) { // error ASSERT_ON_ERROR(UCP_CLIENT_FAILED); } // for a UDP connection connect is not required // sending 1000 packets to the UDP server while (lLoopCount < g_ulPacketCount) { // sending packet iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, (SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus <= 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_CLIENT_FAILED); } lLoopCount++; } UART_PRINT("Sent %u packets successfully\n\r",g_ulPacketCount); //closing the socket after sending 1000 packets sl_Close(iSockID); return SUCCESS; }
static int StartSerialSock(unsigned short port, unsigned int slot) { if(!IS_IP_ACQUIRED(wifi_state.status)) {RETURN_ERROR(ERROR_UNKNOWN, "Uninit fail");} if(IS_SOCK_STARTED(slot)) {RETURN_ERROR(ERROR_UNKNOWN, "Uninit fail");} LOG(LOG_VERBOSE, "Starting socket %d on port %d...", slot, port); int retval; socket_state[slot].addr_local.sin_family = SL_AF_INET; socket_state[slot].addr_local.sin_port = sl_Htons(port); socket_state[slot].addr_local.sin_addr.s_addr = 0; socket_state[slot].parent_id = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0); if(socket_state[slot].parent_id < 0) {RETURN_ERROR(socket_state[slot].parent_id, "Socket create fail");} retval = sl_Bind(socket_state[slot].parent_id, (SlSockAddr_t*)&(socket_state[slot].addr_local), sizeof(SlSockAddrIn_t)); if(retval < 0){ sl_Close(socket_state[slot].parent_id); RETURN_ERROR(retval, "Socket bind fail"); } retval = ListenSerialSock(slot); LOG(LOG_VERBOSE, "Socket started."); socket_state[slot].status = SOCKET_STARTED; return RET_SUCCESS; }
static void StopSockets(void) { for(int i = 0; i<NUM_SOCKETS; i++){ if(IS_SOCK_CONNECTED(i)){ sl_Close(socket_state[i].child_id); socket_state[i].child_id = -1; } if(IS_SOCK_STARTED(i)){ sl_Close(socket_state[i].parent_id); socket_state[i].parent_id = -1; } socket_state[i].status = 0; } return; }
/*! \brief Entering raw Transmitter\Receiver mode in order to send raw data over the WLAN PHY This function shows how to send raw data, in this case ping packets over the air in transmitter mode. \param[in] Channel - number on which the data will be sent \param[in] rate - Rate for tx \param[in] numberOfPackets - packets to be send \param[in] interval - interval between each packet, should be greater than 50ms. \return 0 for success, -ve otherwise \warning We must be disconnected from WLAN AP in order to succeed changing to transmitter mode */ static _i32 TxContinues(_i16 channel, SlRateIndex_e rate, _u16 numberOfPackets, DWORD interval) { _i16 sd = -1; _i16 len = -1; _u32 retVal = -1; sd = sl_Socket(SL_AF_RF, SL_SOCK_RAW, channel); if(sd < 0) { printf("Error In Creating the Socket\n"); ASSERT_ON_ERROR(sd); } printf("Transmitting pinging data...\n"); len = sizeof(RawData_Ping); while(numberOfPackets > 0) { retVal = sl_Send(sd, RawData_Ping, len, SL_RAW_RF_TX_PARAMS(channel, rate, POWER_LEVEL_TONE, PREAMBLE)); ASSERT_ON_ERROR(retVal); Sleep(interval); numberOfPackets--; } printf("Transmitting complete.\n"); retVal = sl_Close(sd); ASSERT_ON_ERROR(retVal); return SUCCESS; }
//--tested, working--// void WiFiClient::stop() { // //don't do anything if not properly set up // if (_socketIndex == NO_SOCKET_AVAIL) { return; } // //disconnect, destroy the socket, and reset the socket tracking variables //in WiFiClass, but don't destroy any of the received data // int iRet = sl_Close(WiFiClass::_handleArray[_socketIndex]); if (iRet < 0) { return; } // //since no error occurred while closing the socket, reset WiFiClass variables // WiFiClass::_portArray[_socketIndex] = -1; WiFiClass::_handleArray[_socketIndex] = -1; WiFiClass::_typeArray[_socketIndex] = -1; _socketIndex = NO_SOCKET_AVAIL; }
int CloseTCPClientSocket(int iSockDesc) { int ittr = 0; if(iSockDesc < 0) { return 0; } do { if(sl_Close(iSockDesc) >= 0) { iSockDesc = -1; HttpDebug("\n Http client socket closed\n\r"); return 0; } else { HttpDebug("\n client socket close error\n\r"); OSI_DELAY(500);//wait 500ms } ittr++; }while(ittr < 3); return -1; }
int ConnectNetwork(Network* n, char* addr, int port) { SlSockAddrIn_t sAddr; int addrSize; int retVal; unsigned long ipAddress; sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET); sAddr.sin_family = AF_INET; sAddr.sin_port = sl_Htons((unsigned short)port); sAddr.sin_addr.s_addr = sl_Htonl(ipAddress); addrSize = sizeof(SlSockAddrIn_t); n->my_socket = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( n->my_socket < 0 ) { // error return -1; } retVal = sl_Connect(n->my_socket, ( SlSockAddr_t *)&sAddr, addrSize); if( retVal < 0 ) { // error sl_Close(n->my_socket); return retVal; } SysTickIntRegister(SysTickIntHandler); SysTickPeriodSet(80000); SysTickEnable(); return retVal; }
static void telnet_wait_for_connection (void) { SlSocklen_t in_addrSize; sockaddr_in sClientAddress; // accepts a connection from a TCP client, if there is any, otherwise returns SL_EAGAIN telnet_data.n_sd = sl_Accept(telnet_data.sd, (SlSockAddr_t *)&sClientAddress, (SlSocklen_t *)&in_addrSize); if (telnet_data.n_sd == SL_EAGAIN) { return; } else { // close the listening socket, we don't need it anymore sl_Close(telnet_data.sd); if (telnet_data.n_sd <= 0) { // error telnet_reset(); return; } // client connected, so go on telnet_data.rxWindex = 0; telnet_data.rxRindex = 0; telnet_data.txRetries = 0; telnet_data.state = E_TELNET_STE_CONNECTED; telnet_data.substate.connected = E_TELNET_STE_SUB_WELCOME; telnet_data.credentialsValid = true; telnet_data.logginRetries = 0; telnet_data.timeout = 0; } }
void servers_close_socket (int16_t *sd) { if (*sd > 0) { modusocket_socket_delete(*sd); sl_Close(*sd); *sd = -1; } }
int NetworkConnectTLS(Network *n, char* addr, int port, SlSockSecureFiles_t* certificates, unsigned char sec_method, unsigned int cipher, char server_verify) { SlSockAddrIn_t sAddr; int addrSize; int retVal; unsigned long ipAddress; retVal = sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET); if (retVal < 0) { return -1; } sAddr.sin_family = AF_INET; sAddr.sin_port = sl_Htons((unsigned short)port); sAddr.sin_addr.s_addr = sl_Htonl(ipAddress); addrSize = sizeof(SlSockAddrIn_t); n->my_socket = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_SEC_SOCKET); if (n->my_socket < 0) { return -1; } SlSockSecureMethod method; method.secureMethod = sec_method; retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method)); if (retVal < 0) { return retVal; } SlSockSecureMask mask; mask.secureMask = cipher; retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &mask, sizeof(mask)); if (retVal < 0) { return retVal; } if (certificates != NULL) { retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_FILES, certificates->secureFiles, sizeof(SlSockSecureFiles_t)); if (retVal < 0) { return retVal; } } retVal = sl_Connect(n->my_socket, (SlSockAddr_t *)&sAddr, addrSize); if (retVal < 0) { if (server_verify || retVal != -453) { sl_Close(n->my_socket); return retVal; } } SysTickIntRegister(SysTickIntHandler); SysTickPeriodSet(80000); SysTickEnable(); return retVal; }
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; }
STATIC void wlan_socket_close(mod_network_socket_obj_t *s) { // this is to prevent the finalizer to close a socket that failed when being created if (s->sock_base.sd >= 0) { modusocket_socket_delete(s->sock_base.sd); sl_Close(s->sock_base.sd); s->sock_base.sd = -1; } }
void modusocket_close_all_user_sockets (void) { sl_LockObjLock (&modusocket_LockObj, SL_OS_WAIT_FOREVER); for (int i = 0; i < MOD_NETWORK_MAX_SOCKETS; i++) { if (modusocket_sockets[i].sd >= 0 && modusocket_sockets[i].user) { sl_Close(modusocket_sockets[i].sd); modusocket_sockets[i].sd = -1; } } sl_LockObjUnlock (&modusocket_LockObj); }
static int ListenSerialSock(unsigned int slot) { long nonblock = 1; int retval = sl_Listen(socket_state[slot].parent_id, 0); if(retval < 0){ sl_Close(socket_state[slot].parent_id); RETURN_ERROR(retval, "Socket listen fail"); } //set to non-blocking retval = sl_SetSockOpt(socket_state[slot].parent_id, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonblock, sizeof(nonblock)); if(retval < 0){ sl_Close(socket_state[slot].parent_id); RETURN_ERROR(retval, "Socket nonblock fail"); } return RET_SUCCESS; }
void CdnClient_CloseServer(void *pvCdnClient) { CdnClient_t *pCdnClient = (CdnClient_t *)pvCdnClient; pCdnClient->cdn_server_name[0] = 0; if (pCdnClient->fileSockId >= 0) { sl_Close(pCdnClient->fileSockId); pCdnClient->fileSockId = -1; } }
//--tested, working--// //--client side--// int WiFiClient::connect(IPAddress ip, uint16_t port) { // //this function should only be called once and only on the client side // if (_socketIndex != NO_SOCKET_AVAIL) { return false; } // //get a socket index and attempt to create a socket //note that the socket is intentionally left as BLOCKING. This allows an //abusive user to send as many requests as they want as fast as they can try //and it won't overload simplelink. // int socketIndex = WiFiClass::getSocket(); if (socketIndex == NO_SOCKET_AVAIL) { return false; } int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_IPPROTO_TCP); if (socketHandle < 0) { return false; } // //connect the socket to the requested IP address and port. Check for success // SlSockAddrIn_t server = {0}; server.sin_family = SL_AF_INET; server.sin_port = sl_Htons(port); server.sin_addr.s_addr = ip; int iRet = sl_Connect(socketHandle, (SlSockAddr_t*)&server, sizeof(SlSockAddrIn_t)); if (iRet < 0) { sl_Close(socketHandle); return false; } int enableOption = 1; sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &enableOption, sizeof(enableOption)); sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_KEEPALIVE, &enableOption, sizeof(enableOption)); // //we've successfully created a socket and connected, so store the //information in the arrays provided by WiFiClass // _socketIndex = socketIndex; WiFiClass::_handleArray[socketIndex] = socketHandle; WiFiClass::_typeArray[socketIndex] = TYPE_TCP_CLIENT; WiFiClass::_portArray[socketIndex] = port; return true; }
/*! \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; }
int _close_r(struct _reent *reent, int s) #endif { int result = sl_Close(s); if (result < 0) { switch (result) { default: errno = EBADF; break; } return -1; } return 0; }
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; }
//--tested, working--// void WiFiUDP::stop() { // //only do the rest of this function if a socket actually exists // if (_socketIndex == NO_SOCKET_AVAIL) { return; } // //close the socket and reset any important variables // flush(); sl_Close(WiFiClass::_handleArray[_socketIndex]); WiFiClass::_handleArray[_socketIndex] = -1; WiFiClass::_portArray[_socketIndex] = -1; WiFiClass::_typeArray[_socketIndex] = -1; _socketIndex = NO_SOCKET_AVAIL; }
//--tested, working--// uint8_t WiFiUDP::begin(uint16_t port) { // //get a socket from the WiFiClass (convoluted method from the arduino library) // int socketIndex = WiFiClass::getSocket(); if (socketIndex == NO_SOCKET_AVAIL) { return 0; } // //get a socket handle from the simplelink api and make sure it's valid // int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, SL_IPPROTO_UDP); if (socketHandle < 0) { return 0; } // //bind the socket to the requested port and check for success //if failure, gracefully close the socket and return // SlSockAddrIn_t portAddress; portAddress.sin_family = SL_AF_INET; portAddress.sin_port = sl_Htons(port); portAddress.sin_addr.s_addr = 0; int iRet = sl_Bind(socketHandle, (SlSockAddr_t*)&portAddress, sizeof(portAddress)); if (iRet < 0) { sl_Close(socketHandle); return 0; } // //now that simplelink api calls are done, set the object's variables // _socketIndex = socketIndex; WiFiClass::_handleArray[socketIndex] = socketHandle; WiFiClass::_portArray[socketIndex] = port; WiFiClass::_typeArray[socketIndex] = TYPE_UDP_PORT; return 1; }
/*! \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; }
//--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; }
int WiFiClient::sslConnect(IPAddress ip, uint16_t port) { // //this function should only be called once and only on the client side // if (_socketIndex != NO_SOCKET_AVAIL) { return false; } // //get a socket index and attempt to create a socket //note that the socket is intentionally left as BLOCKING. This allows an //abusive user to send as many requests as they want as fast as they can try //and it won't overload simplelink. // int socketIndex = WiFiClass::getSocket(); if (socketIndex == NO_SOCKET_AVAIL) { return false; } int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_SEC_SOCKET); if (socketHandle < 0) { return false; } // Utilize rootCA file for verifying server certificate if it's been supplied with .sslRootCA() previously if (hasRootCA) { sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, ROOTCA_PEM_FILE, strlen(ROOTCA_PEM_FILE)); } sslIsVerified = true; // //connect the socket to the requested IP address and port. Check for success // SlSockAddrIn_t server = {0}; server.sin_family = SL_AF_INET; server.sin_port = sl_Htons(port); server.sin_addr.s_addr = ip; int iRet = sl_Connect(socketHandle, (SlSockAddr_t*)&server, sizeof(SlSockAddrIn_t)); if ( iRet < 0 && (iRet != SL_ESECSNOVERIFY && iRet != SL_ESECDATEERROR) ) { sslLastError = iRet; sl_Close(socketHandle); return false; } // If the remote-end server cert could not be verified, and we demand strict verification, ABORT. if ( sslVerifyStrict && (iRet == SL_ESECSNOVERIFY || iRet == SL_ESECDATEERROR) ) { sslLastError = iRet; sl_Close(socketHandle); return false; } if (iRet == SL_ESECSNOVERIFY || iRet == SL_ESECDATEERROR) { sslLastError = iRet; sslIsVerified = false; } int enableOption = 1; sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &enableOption, sizeof(enableOption)); sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_KEEPALIVE, &enableOption, sizeof(enableOption)); // //we've successfully created a socket and connected, so store the //information in the arrays provided by WiFiClass // _socketIndex = socketIndex; WiFiClass::_handleArray[socketIndex] = socketHandle; WiFiClass::_typeArray[socketIndex] = TYPE_TCP_CLIENT; WiFiClass::_portArray[socketIndex] = port; return true; }
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); } } } }
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 } } }
//**************************************************************************** // //! \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; }
void servers_close_socket (int16_t *sd) { if (*sd > 0) { sl_Close(*sd); *sd = -1; } }