int main0(void){ // "Embedded Systems: Real Time Interfacing to ARM Cortex M Microcontrollers", // ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2014, Volume 2, Program 11.2 UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr; UINT16 AddrSize = 0; INT16 SockID = 0; UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); initClk(); // PLL 50 MHz, ADC needs PPL active 15 ADC0_InitSWTriggerSeq3(7); // Ain7 is on PD0 16 sl_Start(0, 0, 0); // Initializing the CC3100 device 17 WlanConnect(); // connect to AP 18 sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len, // 19 (unsigned char *)&ipV4); // 20 Addr.sin_family = SL_AF_INET; // 21 Addr.sin_port = sl_Htons((UINT16)PORT_NUM); // 22 Addr.sin_addr.s_addr = sl_Htonl((UINT32)IP_ADDR); // 23 AddrSize = sizeof(SlSockAddrIn_t); // 24 SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); // 25 while(1){ uBuf[0] = ATYPE; // analog data type 26 uBuf[1] = '='; // 27 data = ADC0_InSeq3(); // 0 to 4095, Ain7 is on PD0 28 Int2Str(data,(char*)&uBuf[2]); // 6 digit number 29 sl_SendTo(SockID, uBuf, BUF_SIZE, 0, // 30 (SlSockAddr_t *)&Addr, AddrSize); // 31 ROM_SysCtlDelay(ROM_SysCtlClockGet() / 25); // 40ms 32 } }
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; }
//--tested, working--// int WiFiUDP::endPacket() { // //only do the rest of this function if a socket actually exists // if (_socketIndex == NO_SOCKET_AVAIL) { return 0; } // //fill in the address structure // SlSockAddrIn_t sendAddress; memset(&sendAddress, 0, sizeof(SlSockAddrIn_t)); sendAddress.sin_family = SL_AF_INET; sendAddress.sin_port = sl_Htons(_sendPort); sendAddress.sin_addr.s_addr = _sendIP; // //use the simplelink library to send the tx buffer // int socketHandle = WiFiClass::_handleArray[_socketIndex]; int iRet = sl_SendTo(socketHandle, tx_buf, tx_fillLevel, NULL, (SlSockAddr_t*)&sendAddress, sizeof(SlSockAddrIn_t)); if (iRet < 0) { return 0; } // //reset all tx buffer indicators // memset(tx_buf, 0, UDP_TX_PACKET_MAX_SIZE); tx_fillLevel = 0; return 1; }
/*! \brief Create TCP connection with openweathermap.org \param[in] none \return Socket descriptor for success otherwise negative \warning */ static int CreateConnection(void){ SlSockAddrIn_t Addr; INT32 sd = 0; INT32 AddrSize = 0; INT16 ret_val = 0; Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(80); /* Change the DestinationIP endianity, to big endian */ Addr.sin_addr.s_addr = sl_Htonl(appData.DestinationIP); AddrSize = sizeof(SlSockAddrIn_t); sd = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( sd < 0 ){ LCD_OutString("Error creating socket\r\n"); return sd; } ret_val = sl_Connect(sd, ( SlSockAddr_t *)&Addr, AddrSize); if( ret_val < 0 ){ /* error */ LCD_OutString("Error connecting to socket\r\n"); return ret_val; } return sd; }
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 bool telnet_create_socket (void) { SlSockNonblocking_t nonBlockingOption; SlSockAddrIn_t sServerAddress; _i16 result; // Open a socket for telnet ASSERT ((telnet_data.sd = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_IPPROTO_TCP)) > 0); if (telnet_data.sd > 0) { // add the socket to the network administration modusocket_socket_add(telnet_data.sd, false); // Enable non-blocking mode nonBlockingOption.NonblockingEnabled = 1; ASSERT ((result = sl_SetSockOpt(telnet_data.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlockingOption, sizeof(nonBlockingOption))) == SL_SOC_OK); // Bind the socket to a port number sServerAddress.sin_family = SL_AF_INET; sServerAddress.sin_addr.s_addr = SL_INADDR_ANY; sServerAddress.sin_port = sl_Htons(TELNET_PORT); ASSERT ((result |= sl_Bind(telnet_data.sd, (const SlSockAddr_t *)&sServerAddress, sizeof(sServerAddress))) == SL_SOC_OK); // Start listening ASSERT ((result |= sl_Listen (telnet_data.sd, TELNET_MAX_CLIENTS)) == SL_SOC_OK); if (result == SL_SOC_OK) { return true; } servers_close_socket(&telnet_data.sd); } return false; }
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; }
// //--tested, working--// //bit of a misnomer. This waits to receive a packet and then stores it in a buffer //it is important that this is called before any of the read or available commands //are called. This does the actual work. Read, peek, etc. are just organizational. // int WiFiUDP::parsePacket() { // //make sure we actually have a socket // if (_socketIndex == NO_SOCKET_AVAIL) { return 0; } // //the sl_select command blocks until something interesting happens or //it times out (current timeout set for 10 ms, the minimum) // SlTimeval_t timeout; timeout.tv_sec = 0; timeout.tv_usec = 10000; int socketHandle = WiFiClass::_handleArray[_socketIndex]; SlFdSet_t readSocketHandles, errorSocketHandles; SL_FD_ZERO(&readSocketHandles); SL_FD_ZERO(&errorSocketHandles); SL_FD_SET(socketHandle, &readSocketHandles); SL_FD_SET(socketHandle, &errorSocketHandles); int iRet = sl_Select(socketHandle+1, &readSocketHandles, NULL, &errorSocketHandles, &timeout); if (iRet <= 0) { return 0; } // //Since we've reached this point, the sl_select command has indicated //that either we're going to get an error, or an immediate read // SlSockAddrIn_t address = {0}; int AddrSize = sizeof(address); int bytes = sl_RecvFrom(socketHandle, rx_buf, UDP_RX_PACKET_MAX_SIZE, NULL, (SlSockAddr_t*)&address, (SlSocklen_t*)&AddrSize); // //store the sender's address (sl_HtonX reorders bits to processor order) //!! Although this follows some examples (upd_socket), it goes against the //!! API documentation. The API maintains that the 5th arg to RecvFrom is not in/out // _remoteIP = address.sin_addr.s_addr; _remotePort = sl_Htons(address.sin_port); // //If an error occured, return 0, otherwise return the byte length of the packet //and reset the buffer index counter and fill level variables // if (bytes < 0) { rx_fillLevel = 0; return 0; } else { rx_currentIndex = 0; rx_fillLevel = bytes; return bytes; } }
//--tested, working--// WiFiClient WiFiServer::available(byte* status) { // //Get a socket number from the wificlass // int clientSocketIndex = WiFiClass::getSocket(); if (clientSocketIndex == NO_SOCKET_AVAIL) { return WiFiClient(255); } // //create the client address structure to be filled in by sl_accept // SlSockAddrIn_t clientAddress = {0}; unsigned int clientAddressSize = sizeof(clientAddress); // //get the client handle, if there's a queued client. If no client, return 0 // int socketHandle = WiFiClass::_handleArray[_socketIndex]; int clientHandle = sl_Accept(socketHandle, (SlSockAddr_t*)&clientAddress, &clientAddressSize); // //We've successfully created a socket, so store everything in the wificlass //arrays used to keep track of the connected sockets, port #s, and types // if (clientHandle > 0) { WiFiClass::_handleArray[clientSocketIndex] = clientHandle; WiFiClass::_typeArray[clientSocketIndex] = TYPE_TCP_CONNECTED_CLIENT; WiFiClass::_portArray[clientSocketIndex] = sl_Htons(clientAddress.sin_port); WiFiClass::clients[clientSocketIndex] = WiFiClient(clientSocketIndex); } // //Now loop through the connected clients // uint8_t oneclient = 0; for(uint8_t i = 0; i < MAX_SOCK_NUM; i++) { if(WiFiClass::_handleArray[i] != -1 && WiFiClass::_typeArray[i] == TYPE_TCP_CONNECTED_CLIENT) { if( i == _lastServicedClient) { oneclient = 1; continue; } _lastServicedClient = i; return WiFiClass::clients[i]; } } if(oneclient) { return WiFiClass::clients[_lastServicedClient]; } _lastServicedClient = -1; return WiFiClient(255); }
//**************************************************************************** // //! \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; }
//--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; }
// "Embedded Systems: Real Time Interfacing to ARM Cortex M Microcontrollers", // ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2014, Volume 2, Program 11.3 int main3(void){ UINT8 IsDHCP = 0; _NetCfgIpV4Args_t ipV4; SlSockAddrIn_t Addr, LocalAddr; UINT16 AddrSize = 0; INT16 SockID = 0; INT16 Status = 1; // ok UINT32 data; unsigned char len = sizeof(_NetCfgIpV4Args_t); initClk(); // PLL 50 MHz, ADC needs PPL active 16 ST7735_InitR(INITR_REDTAB); // Initialize 17 ST7735_OutString("Internet of Things\n"); // 18 ST7735_OutString("Embedded Systems\n"); // 19 ST7735_OutString("Vol. 2, Valvano"); // 20 ST7735_PlotClear(0,4095); // range from 0 to 4095 21 sl_Start(0, 0, 0); // Initializing the CC3100 device 22 WlanConnect(); // connect to AP 23 sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&IsDHCP,&len, // 24 (unsigned char *)&ipV4); // 25 LocalAddr.sin_family = SL_AF_INET; // 26 LocalAddr.sin_port = sl_Htons((UINT16)PORT_NUM); // 27 LocalAddr.sin_addr.s_addr = 0; // 28 AddrSize = sizeof(SlSockAddrIn_t); // 29 while(1){ SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); // 31 Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, // 32 AddrSize); // 33 Status = sl_RecvFrom(SockID, uBuf, BUF_SIZE, 0, // 34 (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize );// 35 if((uBuf[0]==ATYPE)&&(uBuf[1]== '=')){ // 36 int i,bOk; uint32_t place; // 37 data = 0; bOk = 1; // 38 i=4; // ignore possible negative sign 39 for(place = 1000; place; place = place/10){ // 40 if((uBuf[i]&0xF0)==0x30){ // ignore spaces 41 data += place*(uBuf[i]-0x30); // 42 }else{ // 43 if((uBuf[i]&0xF0)!= ' '){ // 44 bOk = 0; // 45 } // 46 } // 47 i++; // 48 } // 49 if(bOk){ // 50 ST7735_PlotLine(data); // 51 ST7735_PlotNextErase(); // 51 } } } }
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--// 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; }
ext_tcp_utils_function_return_state_t ext_tcp_utils_getaddrbyhost(kaa_dns_resolve_listener_t *resolve_listener , const kaa_dns_resolve_info_t *resolve_props , kaa_sockaddr_t *result , kaa_socklen_t *result_size) { (void)resolve_listener; KAA_RETURN_IF_NIL4(resolve_props, resolve_props->hostname, result, result_size, RET_STATE_VALUE_ERROR); if (*result_size < sizeof(struct sockaddr_in)) return RET_STATE_BUFFER_NOT_ENOUGH; unsigned long out_ip = 0; int ai_family; int resolve_error = 0; struct sockaddr_in tmp_addr; ai_family = AF_INET; *result_size = sizeof(struct sockaddr_in); char hostname_str[resolve_props->hostname_length + 1]; memcpy(hostname_str, resolve_props->hostname, resolve_props->hostname_length); hostname_str[resolve_props->hostname_length] = '\0'; if (strcmp(hostname_str, "localhost")) resolve_error = sl_NetAppDnsGetHostByName((signed char*)hostname_str, resolve_props->hostname_length, &out_ip, ai_family); else out_ip = 0x7F000001; memset(&tmp_addr, 0, *result_size); tmp_addr.sin_family = ai_family; tmp_addr.sin_addr.s_addr = sl_Htonl((unsigned int)out_ip); tmp_addr.sin_port = sl_Htons((unsigned short)resolve_props->port); if (resolve_error || !out_ip) return RET_STATE_VALUE_ERROR; memcpy(result, (struct sockaddr*)&tmp_addr, *result_size); return RET_STATE_VALUE_READY; }
//**************************************************************************** // //! \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; }
//***************************************************************************** // //! \brief Task Created by main fucntion. This task creates a udp server and //! wait for packets. Upon receiving the packet, signals the other task. //! //! \param pvParameters is a general void pointer (not used here). //! //! \return none // //***************************************************************************** void UDPServerTask(void *pvParameters) { unsigned char ucSyncMsg; unsigned char ucQueueMsg = 3; int iSockDesc = 0; int iRetVal = 0; sockaddr_in sLocalAddr; sockaddr_in sClientAddr; unsigned int iAddrSize = 0; // // waiting for the other task to start simplelink and connection to the AP // osi_MsgQRead(&g_tConnectionFlag, &ucSyncMsg, OSI_WAIT_FOREVER); osi_MsgQDelete(&g_tConnectionFlag); // // configure the Server // sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short)APP_UDP_PORT); sLocalAddr.sin_addr.s_addr = 0; iAddrSize = sizeof(sockaddr_in); // // 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(); } // // binding the socket // iRetVal = sl_Bind(iSockDesc, (SlSockAddr_t *)&sLocalAddr, iAddrSize); if(iRetVal < 0) { UART_PRINT("bind error\n\r"); LOOP_FOREVER(); } while(FOREVER) { // // waiting on a UDP packet // iRetVal = sl_RecvFrom(iSockDesc, g_cBuffer, BUFF_SIZE, 0, ( SlSockAddr_t *)&sClientAddr, (SlSocklen_t*)&iAddrSize ); if(iRetVal > 0) { // // signal the other task about receiving the UDP packet // osi_MsgQWrite(&g_tWkupSignalQueue, &ucQueueMsg, OSI_WAIT_FOREVER); } else { UART_PRINT("recv error\n\r"); LOOP_FOREVER(); } } }
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(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; }
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); } } } }
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); } }
//**************************************************************************** // //! \brief Opening a UDP server side socket and receiving data //! //! This function opens a UDP socket in Listen mode and waits for an incoming //! UDP connection. //! If a socket connection is established then the function will try to //! read 1000 UDP packets from the connected client. //! //! \param[in] port number on which the server will be listening on //! //! \return 0 on success, Negative value on Error. // //**************************************************************************** int BsdUdpServer(unsigned short usPort) { SlSockAddrIn_t sAddr; SlSockAddrIn_t sLocalAddr; int iCounter; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; short sTestBufLen; // filling the buffer for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++) { g_cBsdBuf[iCounter] = (char)(iCounter % 10); } sTestBufLen = BUF_SIZE; //filling the UDP server socket address sLocalAddr.sin_family = SL_AF_INET; sLocalAddr.sin_port = sl_Htons((unsigned short)usPort); sLocalAddr.sin_addr.s_addr = 0; iAddrSize = sizeof(SlSockAddrIn_t); // creating a UDP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( iSockID < 0 ) { // error ASSERT_ON_ERROR(UCP_SERVER_FAILED); } // binding the UDP socket to the UDP server address iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize); if( iStatus < 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_SERVER_FAILED); } // no listen or accept is required as UDP is connectionless protocol /// waits for 1000 packets from a UDP client while (lLoopCount < g_ulPacketCount) { iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0, ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize ); if( iStatus < 0 ) { // error sl_Close(iSockID); ASSERT_ON_ERROR(UCP_SERVER_FAILED); } lLoopCount++; } UART_PRINT("Recieved %u packets successfully\n\r",g_ulPacketCount); //closing the socket after receiving 1000 packets sl_Close(iSockID); return SUCCESS; }
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); } }
int BsdTcpServer(unsigned short usPort) { UART_PRINT("BsdTcpServer\r\n"); while( wlanConnectStatus == 0); 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 = 0; //0 :non-blocking, 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; char uttMessage[50]={0}; snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet()); UART_PRINT(uttMessage); serverCreatOK = 1; 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); char uttMessage[50]={0}; snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet()); UART_PRINT(uttMessage); // vTaskResume((xTaskHandle)&clientTaskHandle); vTaskSuspend((xTaskHandle)&ServerTaskHandle); // UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); } /* else if( iNewSockID < 0 ) { // error UART_PRINT(" iNewSockID < 0! \n\r"); return -1; }*/ } char utttMessage[50]={0}; snprintf(utttMessage,sizeof(utttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet()); UART_PRINT(utttMessage); 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; } /* //#define SL_POLICY_CONNECTION (0x10) //#define SL_POLICY_SCAN (0x20) //#define SL_POLICY_PM (0x30) // while(1){ // Z_DelayS(1); // char OutMessage[50]={0}; // snprintf(OutMessage,sizeof(OutMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet()); // sl_Send(iNewSockID, OutMessage, strlen(OutMessage), 0 ); // } char *setbuffer= "\n set policy \n\r"; sl_Send(iNewSockID, setbuffer, strlen(setbuffer), 0 ); char recBuffer[2] = {0}; char numBuffer[15]={0}; while(1){ char sl_policy = '0'; char set_prar = '0'; char OutMessage[50] = {0}; char num = 0; while(1){ char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0); if(temp_num>0) num += temp_num; if(num == 1) sl_policy = recBuffer[0]-'0'; if(num == 3) set_prar = recBuffer[0]-'0'; if(num>3 && (recBuffer[0]=='\r' || recBuffer[0]=='\n')) break; if(num>3){ num = 0; char *send_buffer= "\nplease input again!!!\n\r"; sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );} snprintf(numBuffer,sizeof(numBuffer),"num:%d\n\r",num); UART_PRINT(numBuffer); } char *send_buffer= "\nfinished input!\n\r"; sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 ); switch(sl_policy*16){ case SL_POLICY_CONNECTION://1 x snprintf(OutMessage,sizeof(OutMessage),"CONN= first:%d, second:%d,\n\r",sl_policy, set_prar); UART_PRINT(OutMessage); break; case SL_POLICY_SCAN://2 x snprintf(OutMessage,sizeof(OutMessage),"SCAN= first:%d, second:%d,\n\r",sl_policy, set_prar); if(set_prar == 0) sl_WlanPolicySet(SL_POLICY_SCAN,0,0,0); else sl_WlanPolicySet(SL_POLICY_SCAN,1,(unsigned char *)&set_prar,sizeof(set_prar)); UART_PRINT(OutMessage); break; case SL_POLICY_PM://3 x : x=0(normal),x=1(latency),x=2(low),x=3(always on), snprintf(OutMessage,sizeof(OutMessage),"PM= first:%d, second:%d,\n\r",sl_policy, set_prar); UART_PRINT(OutMessage); sl_WlanPolicySet(SL_POLICY_PM , set_prar, NULL,0); break; case 0x00://0 x :finished set break; case 0x40:{//4xx: hibernate char *send_buffer= "\nsl_hibernate!\n\r"; sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 ); sl_Stop(0); break;} case 0x50:{//4xx: hibernate char *send_buffer= "\ndevice_hibernate!\n\r"; sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 ); PRCMHibernateEnter(); break;} default: snprintf(OutMessage,sizeof(OutMessage),"Error= first:%d, second:%d,\n\r",sl_policy, set_prar); UART_PRINT(OutMessage); break; } if(sl_policy == 0) break; } Sl_WlanNetworkEntry_t netEntries[20]; char message[80]; /****no scan*********/ /* #define SL_SCAN_DISABLE 0 sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_DISABLE,0,0); while(1); return 0; UINT8 intervalInSeconds=1; while(1){ Z_DelayS(1); sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds)); } */ /* char *noticebuffer= "\n set send message time \n\r"; sl_Send(iNewSockID, noticebuffer, strlen(noticebuffer), 0 ); while(1){ char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0); if(temp_num>0) break; } 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(recBuffer[0]-'0'); } // close the connected socket after receiving from connected TCP client sl_Close(iNewSockID); // close the listening socket sl_Close(iSockID); return 0; */ }
int BsdTcpClient(unsigned short usPort) { UART_PRINT("BsdTcpClient\r\n"); while(serverCreatOK == 0) { //looping till simplelink starts Z_DelayMS(10); // ; UART_PRINT("serverCreatOK == 0 \n\r"); } UART_PRINT("serverCreatOK == 1\r\n"); int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; long lLoopCount = 0; long lBytesSent = 0; long lNonBlocking = 0; //0 :non-blocking, // 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 = sl_Htons((unsigned short)PORT_NUM); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(192,168,2,5)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); // vTaskSuspend(clientTaskHandle); vTaskResume((xTaskHandle)&ServerTaskHandle); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); // sending 1000 packets to the TCP server while (lLoopCount < 1) { // sending packet iStatus = sl_Send(iSockID, g_cBsdBuf, sTestBufLen, 0 ); /* if( iStatus <= 0 ) { // error return -1; } */ vTaskResume((xTaskHandle)&ServerTaskHandle); lLoopCount++; lBytesSent += iStatus; } //closing the socket after sending 1000 packets sl_Close(iSockID); Report("closing the socket after sending 1000 packets\r\n"); //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)1883); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(9,186,88,87)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); //filling the TCP server socket address sAddr.sin_family = SL_AF_INET; sAddr.sin_port = sl_Htons((unsigned short)1883); sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)SL_IPV4_VAL(9,186,88,87)); iAddrSize = sizeof(SlSockAddrIn_t); // creating a TCP socket iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); if( iSockID < 0 ) { // error return -1; } Report("creating a TCP socket yes\r\n"); lNonBlocking =1; iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); Report("connecting to TCP server\r\n"); // connecting to TCP server while(0>sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize)){ Report("connecting to TCP server error\r\n"); } /* iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize); if( iStatus < 0 ) { // error return -1; } */ Report("connecting to TCP server yes\r\n"); return 0; }
//**************************************************************************** // //! \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, unsigned long ulDesitnationIP) { int iCounter; short sTestBufLen; SlSockAddrIn_t sAddr; int iAddrSize; int iSockID; int iStatus; int iPackets; // 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)ulDesitnationIP); iAddrSize = sizeof(SlSockAddrIn_t); // // Initialize number of packets variable // iPackets = UDP_PACKET_COUNT; // // Creating a UDP socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0); if( iSockID < 0 ) { // error return -1; } UART_PRINT("\n\rSending Packets\n\r"); // // Loop forever sending packets // while (1) { // // Sending packet // iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0, ( SlSockAddr_t *)&sAddr, iAddrSize); // // Decrement the packet count // iPackets--; UART_PRINT("."); // // If send fails or packet count reaches 0 stop acking the watchdog // so that it resets the system // if( iStatus > 0 && iPackets > 0) { WatchdogAck(); } UtilsDelay(8000000); } }
//***************************************************************************** // //! This function demonstrates how certificate can be used with SSL. //! The procedure includes the following steps: //! 1) connect to an open AP //! 2) get the server name via a DNS request //! 3) define all socket options and point to the CA certificate //! 4) connect to the server via TCP //! //! \param None //! //! \return 0 on success else error code //! \return LED1 is turned solid in case of success //! LED2 is turned solid in case of failure //! //***************************************************************************** static long ssl() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_SSLV3; unsigned int uiIP,uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; long lRetVal = -1; int iSockID; GPIO_IF_LedConfigure(LED1|LED3); GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); lRetVal = InitializeAppVariables(); ASSERT_ON_ERROR(lRetVal); // // Following function configure the device to default state by cleaning // the persistent settings stored in NVMEM (viz. connection profiles & // policies, power policy etc) // // Applications may choose to skip this step if the developer is sure // that the device is in its default state at start of applicaton // // Note that all profiles and persistent settings that were done on the // device will be lost // lRetVal = ConfigureSimpleLinkToDefaultState(); if(lRetVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == lRetVal) UART_PRINT("Failed to configure the device in its default state \n\r"); return lRetVal; } UART_PRINT("Device is configured in default state \n\r"); CLR_STATUS_BIT_ALL(g_ulStatus); /// // Assumption is that the device is configured in station mode already // and it is in its default state // lRetVal = sl_Start(0, 0, 0); if (lRetVal < 0 || ROLE_STA != lRetVal) { UART_PRINT("Failed to start the device \n\r"); return lRetVal; } UART_PRINT("Device started as STATION \n\r"); // //Connecting to WLAN AP // lRetVal = WlanConnect(); if(lRetVal < 0) { UART_PRINT("Failed to establish connection w/ an AP \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } UART_PRINT("Connection established w/ AP and IP is aquired \n\r"); //Set time of the device for certificate verification. lRetVal = set_time(); if(lRetVal < 0) { UART_PRINT("Unable to set time in the device"); return lRetVal; } lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { UART_PRINT("Device couldn't retrive the host name \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // opens a secure socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSockID < 0 ) { UART_PRINT("Device unable to create secure socket \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // configure the socket as SSLV3.0 // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\ sizeof(ucMethod)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket as RSA with RC4 128 SHA // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\ sizeof(uiCipher)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket with GOOGLE CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CA_FILE_NAME, \ SL_SSL_CA_CERT_FILE_NAME, \ strlen(SL_SSL_CA_CERT_FILE_NAME)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SO_SECURE_DOMAIN_NAME_VERIFICATION, \ g_Host, strlen((const char *)g_Host)); if( lRetVal < 0 ) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } /* connect to the peer device - Google server */ lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { UART_PRINT("Device couldn't connect to Google server \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); return SUCCESS; }
//***************************************************************************** // //! This function demonstrates how certificate can be used with SSL. //! The procedure includes the following steps: //! 1) connect to an open AP //! 2) get the server name via a DNS request //! 3) define all socket options and point to the CA certificate //! 4) connect to the server via TCP //! //! \param None //! //! \return 0 on success else error code //! \return LED1 is turned solid in case of success //! LED2 is turned solid in case of failure //! //***************************************************************************** static int tls_connect() { SlSockAddrIn_t Addr; int iAddrSize; unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1_2; unsigned int uiIP,uiCipher = SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; long lRetVal = -1; int iSockID; lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET); if(lRetVal < 0) { UART_PRINT("Device couldn't retrive the host name \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(uiIP); iAddrSize = sizeof(SlSockAddrIn_t); // // opens a secure socket // iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( iSockID < 0 ) { UART_PRINT("Device unable to create secure socket \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // // configure the socket as TLS1.2 // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\ sizeof(ucMethod)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket as ECDHE RSA WITH AES256 CBC SHA // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\ sizeof(uiCipher)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } // //configure the socket with CA certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CA_FILE_NAME, \ SL_SSL_CA_CERT, \ strlen(SL_SSL_CA_CERT)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } //configure the socket with Client Certificate - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, \ SL_SSL_CLIENT, \ strlen(SL_SSL_CLIENT)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } //configure the socket with Private Key - for server verification // lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \ SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, \ SL_SSL_PRIVATE, \ strlen(SL_SSL_PRIVATE)); if(lRetVal < 0) { UART_PRINT("Device couldn't set socket options \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } /* connect to the peer device - Google server */ lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize); if(lRetVal < 0) { UART_PRINT("Device couldn't connect to AWS server \n\r"); GPIO_IF_LedOn(MCU_RED_LED_GPIO); return lRetVal; } else{ UART_PRINT("Device has connected to the website:"); UART_PRINT(SERVER_NAME); UART_PRINT("\n\r"); } GPIO_IF_LedOff(MCU_RED_LED_GPIO); GPIO_IF_LedOn(MCU_GREEN_LED_GPIO); return iSockID; }
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 main(int argc, char** argv) { SlSockAddrIn_t Addr = {0}; _u32 cipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA; _u32 googleIP = 0; _u8 method = SL_SO_SEC_METHOD_SSLV3; _i32 AddrSize = -1; _i32 g_SockID = -1; _i32 retVal = -1; retVal = initializeAppVariables(); ASSERT_ON_ERROR(retVal); /* Stop WDT and initialize the system-clock of the MCU These functions needs to be implemented in PAL */ stopWDT(); initClk(); /* Configure command line interface */ CLI_Configure(); displayBanner(); /* * Following function configures the device to default state by cleaning * the persistent settings stored in NVMEM (viz. connection profiles & * policies, power policy etc) * * Applications may choose to skip this step if the developer is sure * that the device is in its default state at start of application * * Note that all profiles and persistent settings that were done on the * device will be lost */ retVal = configureSimpleLinkToDefaultState(); if(retVal < 0) { if (DEVICE_NOT_IN_STATION_MODE == retVal) { CLI_Write(" Failed to configure the device in its default state \n\r"); } LOOP_FOREVER(); } CLI_Write(" Device is configured in default state \n\r"); /* * Assumption is that the device is configured in station mode already * and it is in its default state */ /* Initializing the CC3100 device */ retVal = sl_Start(0, 0, 0); if ((retVal < 0) || (ROLE_STA != retVal) ) { CLI_Write(" Failed to start the device \n\r"); LOOP_FOREVER(); } CLI_Write(" Device started as STATION \n\r"); /* Connecting to WLAN AP - Set with static parameters defined at the top After this call we will be connected and have IP address */ retVal = establishConnectionWithAP(); if(retVal < 0) { CLI_Write(" Failed to establish connection w/ an AP \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection established w/ AP and IP is acquired \n\r"); /* Update the CC3100 time */ retVal = SetTime(); if (retVal < 0) { CLI_Write(" Failed to set the device time \n\r"); LOOP_FOREVER(); } CLI_Write(" Establishing secure connection w/ google server \n\r"); /* get the server name via a DNS request */ retVal = sl_NetAppDnsGetHostByName(g_Google, pal_Strlen(g_Google), &googleIP, SL_AF_INET); if( retVal < 0 ) { CLI_Write(" Failed to get the IP address \n\r"); LOOP_FOREVER(); } Addr.sin_family = SL_AF_INET; Addr.sin_port = sl_Htons(GOOGLE_DST_PORT); Addr.sin_addr.s_addr = sl_Htonl(googleIP); AddrSize = sizeof(SlSockAddrIn_t); /* opens a secure socket */ g_SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if( g_SockID < 0 ) { CLI_Write(" Failed to open socket \n\r"); LOOP_FOREVER(); } /* configure the socket as SSLV3.0 */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket as RSA with RC4 128 SHA */ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &cipher, sizeof(cipher)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* configure the socket with GOOGLE CA certificate-for server verification*/ retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT, pal_Strlen(SL_SSL_CA_CERT)); if( retVal < 0 ) { CLI_Write(" Failed to configure the socket \n\r"); LOOP_FOREVER(); } /* connect to the peer device - GMail server */ retVal = sl_Connect(g_SockID, ( SlSockAddr_t *)&Addr, AddrSize); if (retVal < 0 ) { CLI_Write(" Failed to connect w/ google server \n\r"); LOOP_FOREVER(); } CLI_Write(" Connection w/ google server established successfully \n\r"); /* Stop the CC3100 device */ retVal = sl_Stop(SL_STOP_TIMEOUT); if(retVal < 0) LOOP_FOREVER(); return 0; }