int CreateTCPClientSocket(int iSockDesc)
{
  sockaddr sClientAddr;
  SlSocklen_t uiClientAddrLen = sizeof(sClientAddr);
  int sock = -1;
  SlTimeval_t timeVal;
  SlSockNonblocking_t enableOption;

  sock = accept(iSockDesc, &sClientAddr, &uiClientAddrLen);
  if(sock >= 0)
  {
    enableOption.NonblockingEnabled = 0;
#if 1
    //Blocking socket - Enable blocking mode
    if(sl_SetSockOpt(sock,SOL_SOCKET,SL_SO_NONBLOCKING, &enableOption,sizeof(enableOption)) < 0)
    {
      CloseTCPClientSocket(sock);
      return -1;
    }
#endif
    timeVal.tv_sec =  1;             // 1 Seconds
    timeVal.tv_usec = 0;             // Microseconds. 10000 microseconds resoultion
    if((sl_SetSockOpt(sock,SOL_SOCKET,SL_SO_RCVTIMEO, &timeVal, sizeof(timeVal))) < 0)
    {
      CloseTCPClientSocket(sock);
      return -1;
    }// Enable receive timeout
  }

  return sock;
}
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;
}
Example #3
0
//--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;
}
Example #4
0
static bool telnet_create_socket (void) {
    SlSockNonblocking_t nonBlockingOption;
    sockaddr_in         sServerAddress;
    _i16 result;

    // Open a socket for telnet
    ASSERT ((telnet_data.sd = sl_Socket(AF_INET, SOCK_STREAM, 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, SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlockingOption, sizeof(nonBlockingOption))) == SL_SOC_OK);

        // Bind the socket to a port number
        sServerAddress.sin_family = AF_INET;
        sServerAddress.sin_addr.s_addr = INADDR_ANY;
        sServerAddress.sin_port = 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;
}
Example #5
0
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;
}
Example #6
0
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;
}
Example #7
0
//*****************************************************************************
//
//! \brief     Get the NTP time
//!
//! \param    none
//!
//! \return void
//! \note
//! \warning
//
//*****************************************************************************
uint8_t GetTime(struct tm * decodedTime)
{
    const char * g_acSNTPserver = "wwv.nist.gov"; //Add any one of the above servers
    unsigned long ulDestinationIP;
    int iSocketDesc;
    long lRetVal;
    char cDataBuf[48];
    int iAddrSize;
    SlSockAddr_t sAddr;
    SlSockAddrIn_t sLocalAddr;

    //
    // Create UDP socket
    //
    iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(iSocketDesc < 0)
    {
        ERR_PRINT(iSocketDesc);
        return 0;
    }
    //g_sAppData.iSockID = iSocketDesc;

    UART_PRINT("Socket created\n\r");

    //
    // Get the NTP server host IP address using the DNS lookup
    //
    lRetVal = Network_IF_GetHostIP((char*)g_acSNTPserver, &ulDestinationIP);

    if( lRetVal >= 0)
    {

        struct SlTimeval_t timeVal;
        timeVal.tv_sec =  SERVER_RESPONSE_TIMEOUT;    // Seconds
        timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
        lRetVal = sl_SetSockOpt(iSocketDesc,SL_SOL_SOCKET,SL_SO_RCVTIMEO,\
                        (unsigned char*)&timeVal, sizeof(timeVal));
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            //
            // Close the socket
            //
            close(iSocketDesc);
            UART_PRINT("Socket closed\n\r");
            return 0;
        }

        //
        // Send a query ? to the NTP server to get the NTP time
        //
        memset(cDataBuf, 0, sizeof(cDataBuf));
        cDataBuf[0] = '\x1b';

        sAddr.sa_family = AF_INET;
        // the source port
        sAddr.sa_data[0] = 0x00;
        sAddr.sa_data[1] = 0x7B;    // UDP port number for NTP is 123
        sAddr.sa_data[2] = (char)((ulDestinationIP>>24)&0xff);
        sAddr.sa_data[3] = (char)((ulDestinationIP>>16)&0xff);
        sAddr.sa_data[4] = (char)((ulDestinationIP>>8)&0xff);
        sAddr.sa_data[5] = (char)(ulDestinationIP&0xff);

        lRetVal = sl_SendTo(iSocketDesc,
                         cDataBuf,
                         sizeof(cDataBuf), 0,
                         &sAddr, sizeof(sAddr));
        if (lRetVal != sizeof(cDataBuf))
        {
            // could not send SNTP request
            //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);
            return 0;
        }

        //
        // Wait to receive the NTP time from the server
        //
        sLocalAddr.sin_family = SL_AF_INET;
        sLocalAddr.sin_port = 0;
        sLocalAddr.sin_addr.s_addr = 0;
        lRetVal = sl_Bind(iSocketDesc,
                (SlSockAddr_t *)&sLocalAddr,
                sizeof(SlSockAddrIn_t));

        iAddrSize = sizeof(SlSockAddrIn_t);

        lRetVal = sl_RecvFrom(iSocketDesc,
                           cDataBuf, sizeof(cDataBuf), 0,
                           (SlSockAddr_t *)&sLocalAddr,
                           (SlSocklen_t*)&iAddrSize);
        //ASSERT_ON_ERROR(lRetVal);

        if(lRetVal < 0)
        {
            UART_PRINT("Server Get Time failed\n\r");
            //
            // Close the socket
            //
            close(iSocketDesc);
            UART_PRINT("Socket closed\n\r");
            return 0;
        }

        // We received the time
        DecodeSNTPTime(cDataBuf, decodedTime);
    }
    else
    {
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;
}
Example #10
0
//****************************************************************************
//
//! Task function implementing the gettime functionality using an NTP server
//!
//! \param none
//!
//! This function
//!    1. Initializes the required peripherals
//!    2. Initializes network driver and connects to the default AP
//!    3. Creates a UDP socket, gets the NTP server IP address using DNS
//!    4. Periodically gets the NTP time and displays the time
//!
//! \return Returns \b TASK_RET_IN_PROG.
//
//****************************************************************************
int GetNTPTimeTask(void *pvParameters)
{
    SlSecParams_t SecurityParams;
    long lRetVal = -1;
    struct SlTimeval_t timeVal;
    static char cTaskOwnState = GET_TIME_TASK_STATE_INIT;
    static tGetTime sGetTime;
    long OptionLen;
    int SetCommitInt;
    unsigned char OptionVal;

    switch(cTaskOwnState)
    {

    case GET_TIME_TASK_STATE_INIT:
        //
        // Start networking service in default STA_MODE state
        //
        lRetVal = NetStartDefaultState();
        if(lRetVal < 0)
        {
          return TASK_RET_DONE;
        }

        //
        // Set the status as stated
        //
        sDisplayInfo.ucNetStat = NET_STAT_STARTED;

        //
        // Set the time zone
        //
        sGetTime.ucGmtDiffHr   = GMT_DIFF_TIME_HRS;
        sGetTime.ucGmtDiffMins = GMT_DIFF_TIME_MINS;

        //
        // Set conneting status
        //
        sDisplayInfo.ucNetStat = NET_STAT_CONN;

        //
        // Get the Version Info
        //
        NetFwInfoGet(&sDisplayInfo.sNwpVersion);

        //
        // Make the formated string for firmware version
        //
        sprintf(sDisplayInfo.ucNwpVersion,
                "%d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d",
                sDisplayInfo.sNwpVersion.NwpVersion[0],
                sDisplayInfo.sNwpVersion.NwpVersion[1],
                sDisplayInfo.sNwpVersion.NwpVersion[2],
                sDisplayInfo.sNwpVersion.NwpVersion[3],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[0],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[1],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[2],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[3],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[0],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[1],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[2],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[3]);

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_CONN;

        //
        // Signal display refresh
        //
        DisplayRefresh();
        break;

    case GET_TIME_TASK_STATE_CONN:

        //
        // Initialize AP security params
        //
        SecurityParams.Key = (signed char *)SECURITY_KEY;
        SecurityParams.KeyLen = strlen(SECURITY_KEY);
        SecurityParams.Type = SECURITY_TYPE;

        //
        // Connect to Access Point
        //
        lRetVal = NetWlanConnect(SSID_NAME,&SecurityParams);

        //
        // Failed to connect to AP, kill the task
        //
        if(lRetVal != 0)
        {
          return TASK_RET_DONE;
        }

        //
	// Check if this image is booted in test mode
	//
	sl_extLib_OtaGet(pvOtaApp,EXTLIB_OTA_GET_OPT_IS_PENDING_COMMIT,
                         &OptionLen,&OptionVal);

	if(OptionVal == true)
	{


            SetCommitInt = OTA_ACTION_IMAGE_COMMITED;
            sl_extLib_OtaSet(pvOtaApp, EXTLIB_OTA_SET_OPT_IMAGE_COMMIT,
                             sizeof(int), (_u8 *)&SetCommitInt);

            //
            // Set status
            //
            g_ulSysState = SYS_STATE_TEST_REBOOT;
            DisplayRefresh();

            //
            // Reboot the MCU
            //
            cTaskOwnState = GET_TIME_TASK_STATE_DONE;
            break;
	}

        //
        // Set the status
        //
        sDisplayInfo.ucNetStat = NET_STAT_CONNED;
        DisplayRefresh();

        //
        // Signal the network start
        //
        TaskSyncObjSignal(&g_NetStatSyncObj);

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_OPEN_SOCK;

        break;

    case GET_TIME_TASK_STATE_OPEN_SOCK:

        //
        // Create UDP socket
        //
        sGetTime.iSocket = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        //
        // Failed to create a socket, kill the task
        //
        while(sGetTime.iSocket < 0)
        {
          return TASK_RET_DONE;
        }

        //
        // Set socket time option
        //
        timeVal.tv_sec =  20;
        timeVal.tv_usec = 0;
        sl_SetSockOpt(sGetTime.iSocket,SOL_SOCKET,SL_SO_RCVTIMEO, &timeVal,
                      sizeof(timeVal));

        //
        // Initialize Server Index
        //
        sDisplayInfo.ucServerIndex = 0;
        DisplayRefresh();

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_GET_IP;
        break;


    case GET_TIME_TASK_STATE_GET_IP:

        //
        // Get the NTP server host IP address using the DNS lookup
        //
        lRetVal = NetGetHostIP((char*)g_acSNTPserver[sDisplayInfo.ucServerIndex],
                         &sGetTime.ulNtpServerIP);

        sDisplayInfo.ulServerIP = sGetTime.ulNtpServerIP;
        DisplayRefresh();

        //
        // Set the net task state based on return value
        //
        if(lRetVal >= 0)
        {
          //
          // Go to get time
          //
          cTaskOwnState = GET_TIME_TASK_STATE_GET_TIME;
        }
        else
        {
          //
          // Go back and try a new NTP server
          //
          cTaskOwnState = GET_TIME_TASK_STATE_SET_SERVER;
        }
        break;

    case GET_TIME_TASK_STATE_GET_TIME:

        //
        // Get the NTP time and display the time
        //
        lRetVal = GetSNTPTime(&sGetTime);
        DisplayRefresh();

        //
        // On failure go back and try a new NTP server
        //
        if(lRetVal != 0)
        {
          //
          // Chech and wait if we are disconnected
          //
          while( !NetIsConnectedToAP() )
          {

          }

          cTaskOwnState = GET_TIME_TASK_STATE_SET_SERVER;
        }

        //
        // End the task if Reboot was requested
        //
        if(g_ulSysState == SYS_STATE_REBOOT)
        {
          cTaskOwnState = GET_TIME_TASK_STATE_DONE;
        }

        //
        // Set some sleep
        //
        TaskSleep(5*1000);
        break;

    case GET_TIME_TASK_STATE_SET_SERVER:

          strcpy((char *)sDisplayInfo.ucUTCTime,"NTP Server Error. Retrying...");
          sDisplayInfo.ucLocalTime[0]='-';
          sDisplayInfo.ucLocalTime[1]='\0';

          sDisplayInfo.ucServerIndex
            = ((sDisplayInfo.ucServerIndex + 1)%NOF_NTP_SERVER);

          cTaskOwnState = GET_TIME_TASK_STATE_GET_IP;
          DisplayRefresh();
          break;

    default:

        //
        // Disconnect and stop networking service
        //
        NetStop();

        sDisplayInfo.ucNetStat = NET_STAT_OFF;
        DisplayRefresh();

        //
        // Reboot nonw
        //
        RebootMCU();

        //
        // Return task done
        //
        return TASK_RET_DONE;
    }

    //
    // Return task in progress
    //
    return TASK_RET_IN_PROG;
}
Example #11
0
/*
 * ::setsocketopt()
 */
int setsockopt(int s, int level, int option_name,
               const void *option_value, socklen_t option_len)
{
    int result;

    switch (level)
    {
        default:
            errno = EINVAL;
            return -1;
        case SOL_SOCKET:
            switch (option_name)
            {
                default:
                    errno = EINVAL;
                    return -1;
                case SO_REUSEADDR:
                    /* CC32xx does not care about SO_REUSEADDR, ignore it */
                    result = 0;
                    break;
                case SO_BROADCAST:
                    /* CC32xx does not care about SO_BROADCAST, ignore it */
                    result = 0;
                    break;
                case SO_RCVBUF:
                    if (option_len != sizeof (int))
                    {
                        errno = EINVAL;
                        return -1;
                    }
                    else
                    {
                        SlSockWinsize_t size;
                        size.WinSize = *((int *)option_value);
                        result = sl_SetSockOpt(s, SL_SOL_SOCKET, SL_SO_RCVBUF,
                                               &size, sizeof(size));
                    }
                    break;
                case SO_SNDBUF:
                    /* CC32xx does not care about SO_SNDBUF, ignore it */
                    result = 0;
                    break;
            }
            break;
        case IPPROTO_TCP:
            switch (option_name)
            {
                default:
                    errno = EINVAL;
                    return -1;
                case TCP_NODELAY:
                    /* CC32xx does not care about Nagel algorithm, ignore it */
                    result = 0;
                    break;
            }
            break;
    }

    if (result < 0)
    {
        switch (result)
        {
            default:
                errno = EINVAL;
                break;
        }
        return -1;
    }

    return result;
}
Example #12
0
File: main.c Project: nqd/cc3200
//****************************************************************************
//
//! Task function implementing the gettime functionality using an NTP server
//!
//! \param none
//!
//! This function
//!    1. Initializes the required peripherals
//!    2. Initializes network driver and connects to the default AP
//!    3. Creates a UDP socket, gets the NTP server IP address using DNS
//!    4. Periodically gets the NTP time and displays the time
//!
//! \return None.
//
//****************************************************************************
void GetNTPTimeTask(void *pvParameters)
{
    int iSocketDesc;
    long lRetVal = -1;

    UART_PRINT("GET_TIME: Test Begin\n\r");

    //
    // Configure LED
    //
    GPIO_IF_LedConfigure(LED1|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);    


    //
    // Reset The state of the machine
    //
    Network_IF_ResetMCUStateMachine();

    //
    // Start the driver
    //
    lRetVal = Network_IF_InitDriver(ROLE_STA);
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to start SimpleLink Device\n\r",lRetVal);
       LOOP_FOREVER();
    }

    // switch on Green LED to indicate Simplelink is properly up
    GPIO_IF_LedOn(MCU_ON_IND);

    // Start Timer to blink Red LED till AP connection
    LedTimerConfigNStart();

    // Initialize AP security params
    SecurityParams.Key = (signed char *)SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    //
    // Connect to the Access Point
    //
    lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams);
    if(lRetVal < 0)
    {
       UART_PRINT("Connection to an AP failed\n\r");
       LOOP_FOREVER();
    }

    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    LedTimerDeinitStop();

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    //
    // Create UDP socket
    //
    iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(iSocketDesc < 0)
    {
        ERR_PRINT(iSocketDesc);
        goto end;
    }
    g_sAppData.iSockID = iSocketDesc;

    UART_PRINT("Socket created\n\r");

    //
    // Get the NTP server host IP address using the DNS lookup
    //
    lRetVal = Network_IF_GetHostIP((char*)g_acSNTPserver, \
                                    &g_sAppData.ulDestinationIP);
    
    if( lRetVal >= 0)
    {
    
        struct SlTimeval_t timeVal;
        timeVal.tv_sec =  SERVER_RESPONSE_TIMEOUT;    // Seconds
        timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
        lRetVal = sl_SetSockOpt(g_sAppData.iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO,\
                        (unsigned char*)&timeVal, sizeof(timeVal)); 
        if(lRetVal < 0)
        {
           ERR_PRINT(lRetVal);
           LOOP_FOREVER();
        }
        
        while(1)
        {
            //
            // Get the NTP time and display the time
            //
            lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS);
            if(lRetVal < 0)
            {
                UART_PRINT("Server Get Time failed\n\r");
                break;                
            }

            //
            // Wait a while before resuming
            //
            MAP_UtilsDelay(SLEEP_TIME);
        }
    }
    else
    {
        UART_PRINT("DNS lookup failed. \n\r");
    }

    //
    // Close the socket
    //
    close(iSocketDesc);
    UART_PRINT("Socket closed\n\r");

end:
    //
    // Stop the driver
    //
    lRetVal = Network_IF_DeInitDriver();
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to stop SimpleLink Device\n\r");
       LOOP_FOREVER();
    }

    //
    // Switch Off RED & Green LEDs to indicate that Device is
    // disconnected from AP and Simplelink is shutdown
    //
    GPIO_IF_LedOff(MCU_IP_ALLOC_IND);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    UART_PRINT("GET_TIME: Test Complete\n\r");

    //
    // Loop here
    //
    LOOP_FOREVER();
}
Example #13
0
int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
  int err;
  const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  DBG(("%p ssl ctx: %p", nc, ctx));

  if (ctx == NULL) return 0;
  DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
       (ctx->ssl_key ? ctx->ssl_cert : "-"),
       (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
       (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
  if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
    char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
    if (ssl_cert != NULL) {
      err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
                          SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
                          strlen(ssl_cert));
      MG_FREE(ssl_cert);
      LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
      ssl_key = sl_pem2der(ctx->ssl_key);
      if (ssl_key != NULL) {
        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
                            SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
                            strlen(ssl_key));
        MG_FREE(ssl_key);
        LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
      } else {
        err = -1;
      }
    } else {
      err = -1;
    }
    if (err != 0) return err;
  }
  if (ctx->ssl_ca_cert != NULL) {
    if (ctx->ssl_ca_cert[0] != '\0') {
      char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
      if (ssl_ca_cert != NULL) {
        err =
            sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
                          ssl_ca_cert, strlen(ssl_ca_cert));
        LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
      } else {
        err = -1;
      }
      MG_FREE(ssl_ca_cert);
      if (err != 0) return err;
    }
  }
  if (ctx->ssl_server_name != NULL) {
    err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
                        SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
                        ctx->ssl_server_name, strlen(ctx->ssl_server_name));
    DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
    /* Domain name verificationw as added in a NWP service pack, older
     * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
     * about it,
     * so we ignore the error. */
    if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
  }
  return 0;
}
Example #14
0
void cc3200_set_non_blocking_mode(int fd) {
  SlSockNonblocking_t opt;
  opt.NonblockingEnabled = 1;
  sl_SetSockOpt(fd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
}
Example #15
0
File: main.c Project: Mecabot/IoT
//*****************************************************************************
//
//! This function obtains the current time from a SNTP server if required due
//! to not having current time (when booting up) or periodically to update
//! the time
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  Error Number of failure
//
//*****************************************************************************
long GetCurrentTime()
{
    int iSocketDesc;
    long lRetVal = -1;

	//
	// Get the time and date currently stored in the RTC
	//
	getDeviceTimeDate();

	//
	// Calculate time difference between the last time we obtained time from a NTP server
	//
	timeDifference = dateTime.sl_tm_hour - hourSet; // This roughly works, it does however reset after midnight.

	//
	// Get the NTP time to use with the SSL process. Only call this every 6 hours to update the RTC
	// As we do not want to be calling the NTP server too often
	//
	if (timeDifference > 6 || timeDifference < 0)
	{
		//
		// Create UDP socket
		//
		iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		if(iSocketDesc < 0)
		{
			CLI_Write("Could not create UDP socket.\n\r");
			close(iSocketDesc);
			return iSocketDesc;
		}
		else
		{
			CLI_Write("Socket successfully created\n\r");
		}
		g_sAppData.iSockID = iSocketDesc;

		//
		// Get the NTP server host IP address using the DNS lookup
		//
		lRetVal = getHostIP((char*)g_acSNTPserver, &g_sAppData.ulDestinationIP);
		if( lRetVal >= 0)
		{
			//
			// Configure the recieve timeout
			//
			struct SlTimeval_t timeVal;
			timeVal.tv_sec =  SERVER_RESPONSE_TIMEOUT;    // Seconds
			timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
			lRetVal = sl_SetSockOpt(g_sAppData.iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal));
			if(lRetVal < 0)
			{
			   CLI_Write("Could not configure socket option (receive timeout).\n\r");
			   close(iSocketDesc);
			   return lRetVal;
			}
		}
		else
		{
			CLI_Write("DNS lookup failed.");
		}

		//
		// Get current time from the SNTP server
		//
		CLI_Write("Fetching Time From SNTP Server\n\r");
		lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS);
		if(lRetVal < 0)
		{
			CLI_Write("Server Get Time failed.\n\r");
			close(iSocketDesc);
			return lRetVal;
		}
		else
		{
			hourSet = dateTime.sl_tm_hour; // Set to current hour as we did get the time successfully
			CLI_Write("Server Get Time Successful\n\n\r");
		}

		//
		// Close the socket
		//
		close(iSocketDesc);
	}

	return 0;
}
Example #16
0
int OpenTCPServerSocket(unsigned int uiPortNum)
{
  int iSockDesc, iRetVal;
  sockaddr_in sServerAddress;
  SlSockNonblocking_t enableOption;
  enableOption.NonblockingEnabled = 1;

  //
  // opens a secure socket
  //
  if(443 == uiPortNum)
  {
  	iSockDesc = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
	}
	else //non secure
	{
		iSockDesc = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_IPPROTO_TCP);
	}

  if( iSockDesc < 0 )
  {
     return -1;
  }
#if 1
  //non blocking socket - Enable nonblocking mode
  iRetVal = sl_SetSockOpt(iSockDesc,SOL_SOCKET,SL_SO_NONBLOCKING, &enableOption,sizeof(enableOption));
  if(iRetVal < 0)
  {
    CloseTCPServerSocket(iSockDesc);
    return -1;
  }
#endif
  if(443 == uiPortNum)
  {
		iRetVal = sl_SetSockOpt(iSockDesc, SL_SOL_SOCKET, SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME,SL_SSL_SRV_KEY, strlen(SL_SSL_SRV_KEY));
		if( iRetVal < 0 )
		{
				CloseTCPServerSocket(iSockDesc);
				return -1;
		}
		iRetVal = sl_SetSockOpt(iSockDesc, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME,SL_SSL_SRV_CERT, strlen(SL_SSL_SRV_CERT));
		if( iRetVal < 0 )
		{
				CloseTCPServerSocket(iSockDesc);
				return -1;
		}
	}

  //
  // Bind - Assign a port to the socket
  //
  sServerAddress.sin_family = AF_INET;
  sServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
  sServerAddress.sin_port = htons(uiPortNum);
  if ( bind(iSockDesc, (struct sockaddr*)&sServerAddress, sizeof(sServerAddress)) != 0 )
  {
    CloseTCPServerSocket(iSockDesc);
    return -1;
  }

  return iSockDesc;
}
Example #17
0
//*****************************************************************************
//
//! This function opens a TCP socket in Listen mode and waits for an incoming 
//! TCP connection.. If a socket connection is established then the function 
//! will try to read 1000 TCP packets from the connected client.
//!
//! \param port number on which the server will be listening on
//!
//! \return  0 on success, -ve on Error.
//!
//*****************************************************************************
static long BsdTcpServer(unsigned short Port)
{
    SlSockAddrIn_t  Addr;
    SlSockAddrIn_t  LocalAddr;
    int             indexCount,iAddrSize,SockID,iStatus,newSockID;
    long            LoopCount = 0;
    long            nonBlocking = 1;
    SlTimeval_t     timeVal;

    for (indexCount=0 ; indexCount<BUF_SIZE ; indexCount++)
    {
        g_uBuf.cBsdBuf[indexCount] = (char)(indexCount % 10);
    }

    LocalAddr.sin_family = SL_AF_INET;
    LocalAddr.sin_port = sl_Htons((unsigned short)Port);
    LocalAddr.sin_addr.s_addr = 0;
    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    ASSERT_ON_ERROR(SockID);

    iAddrSize = sizeof(SlSockAddrIn_t);
    iStatus = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, iAddrSize);

    if( iStatus < 0 )
    {
        // error
        ASSERT_ON_ERROR(sl_Close(SockID));
        ASSERT_ON_ERROR(iStatus);
    }

    iStatus = sl_Listen(SockID, 0);
    if( iStatus < 0 )
    {
        sl_Close(SockID);
        ASSERT_ON_ERROR(iStatus);
    }

    iStatus = sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, \
                            &nonBlocking,
                            sizeof(nonBlocking));
    newSockID = SL_EAGAIN;
    while( newSockID < 0 )
    {
        newSockID = sl_Accept(SockID, ( struct SlSockAddr_t *)&Addr, 
                                        (SlSocklen_t*)&iAddrSize);
        if( newSockID == SL_EAGAIN )
        {
                MAP_UtilsDelay(80000);
        }
        else if( newSockID < 0 )
        {
            ASSERT_ON_ERROR(sl_Close(SockID));
            // error
            ASSERT_ON_ERROR(newSockID);
        }
    }
    timeVal.tv_sec = 1;
    timeVal.tv_usec = 0;
    if( newSockID >= 0 )
    {
        iStatus = sl_SetSockOpt(newSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO,
                                &timeVal, sizeof(timeVal));
        ASSERT_ON_ERROR(iStatus);
    }

    while (LoopCount < PACKET_COUNT)
    {
        iStatus = sl_Recv(newSockID, g_uBuf.cBsdBuf, BUF_SIZE, 0);
        if( iStatus <= 0 )
        {
            // error
            ASSERT_ON_ERROR(sl_Close(newSockID));
            ASSERT_ON_ERROR(sl_Close(SockID));
            ASSERT_ON_ERROR(iStatus);
        }

        LoopCount++;
    }

    ASSERT_ON_ERROR(sl_Close(newSockID));
    ASSERT_ON_ERROR(sl_Close(SockID));
    return 0;
}
Example #18
0
//--tested, working--//
void WiFiServer::begin()
{
    //
    //Stop the port 80 internal http server if running a server on port 80
    //
    if (_port == 80) {
        sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
    }
    
    //
    //get a socket from the WiFiClass (convoluted method from the arduino library)
    //
    int socketIndex = WiFiClass::getSocket();
    if (socketIndex == NO_SOCKET_AVAIL) {
        return;
    }
    
    //
    //get a socket handle from the simplelink api and make sure it's valid
    //
    int socketHandle = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_IPPROTO_TCP);
    if (socketHandle < 0) {
        return;
    }
    //
    //bind the socket to the requested port and check for success
    //if failure, gracefully close the socket and return failure
    //
    SlSockAddrIn_t portAddress;
    portAddress.sin_family = SL_AF_INET;
    portAddress.sin_port = sl_Htons(_port);
    portAddress.sin_addr.s_addr = 0;
    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));

    int iRet = sl_Bind(socketHandle, (SlSockAddr_t*)&portAddress, sizeof(SlSockAddrIn_t));
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //Make the socket start listening for incoming tcp connections
    //(backlog of length 0)
    //
    iRet = sl_Listen(socketHandle, 0);
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //set socket operation to be non blocking
    //
    long NonBlocking = true;
    iRet = sl_SetSockOpt(socketHandle, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &NonBlocking, sizeof(NonBlocking));
    if (iRet < 0) {
        sl_Close(socketHandle);
        return;
    }
    
    //
    //Simplelink api calls are done, so set the object's variables
    //
    _socketIndex = socketIndex;
    WiFiClass::_handleArray[socketIndex] = socketHandle;
    WiFiClass::_portArray[socketIndex] = _port;
    WiFiClass::_typeArray[socketIndex] = TYPE_TCP_SERVER;
}
Example #19
0
//****************************************************************************
//                            MAIN FUNCTION
//****************************************************************************
int main(void)
{
    long lRetVal;
	char cCmdBuff[20];
	signed char cCmd = APP_SLEEP;

    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    SlSockAddrIn_t  sBrdAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    long            lLoopCount = 0;
    short           sTestBufLen;
    struct SlTimeval_t timeVal;

    //
    // Board Initialization
    //
    BoardInit();
    
    //
	// uDMA Initialization
	//
	UDMAInit();
    
    //
    // Configure the pinmux settings for the peripherals exercised
    // Note: pinmux has been modified after the output from pin mux tools
    // to enable sleep clk for the peripherals exercised
    //
    PinMuxConfig();

    //
	// Initialize the platform
	//
	platform_init();

    //
    // Initialise the UART terminal
    //
    InitTerm();

    //
	// Display banner
	//
    DisplayBanner();
    
	//
    // starting the simplelink
    //
	lRetVal = sl_Start(NULL, NULL, NULL);
	if (lRetVal < 0)
	{
		UART_PRINT("Failed to start the device \n\r");
		LOOP_FOREVER();
	}

    //
    // Swtich to STA mode if device is not
    //
    SwitchToStaMode(lRetVal);
    
    //
    // set connection policy
    //
    sl_WlanPolicySet(SL_POLICY_CONNECTION, 
                                SL_CONNECTION_POLICY(0, 0, 0, 0, 0), NULL, 0);
	//
	// Set the power management policy of NWP
	//
	lRetVal = sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0);

    UART_PRINT("Trying to Connect to AP: %s ...\r\n",SSID_NAME);

    //
    //Connecting to WLAN AP
    //
    lRetVal = WlanConnect();
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10);
    }
    
	sTestBufLen  = BUF_SIZE;
	//filling the UDP server socket address
	sLocalAddr.sin_family = SL_AF_INET;
	sLocalAddr.sin_port = sl_Htons((unsigned short)PORT_NUM);
	sLocalAddr.sin_addr.s_addr = 0;

	//filling the UDP server socket address
	sBrdAddr.sin_family = SL_AF_INET;
	sBrdAddr.sin_port = sl_Htons((unsigned short)PORT_NUM);
	sBrdAddr.sin_addr.s_addr = sl_Htonl((unsigned int)g_ulDestinationIp);

	iAddrSize = sizeof(SlSockAddrIn_t);

	// creating a UDP socket
	iSockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);

    /* setting time out for socket recv */
    timeVal.tv_sec =  5;             // Seconds
    timeVal.tv_usec = 0;             // Microseconds. 10000 microseconds resolution
    sl_SetSockOpt(iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (_u8 *)&timeVal, sizeof(timeVal));

    // binding the UDP socket to the UDP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
        // error
        sl_Close(iSockID);
        ASSERT_ON_ERROR(iStatus);
    }

	//
	// setting Apps power policy
	//
	lp3p0_setup_power_policy(POWER_POLICY_STANDBY);
    
    UART_PRINT("enter one of the following command:\n\r");
    UART_PRINT("sleep - for putting the system into LPDS mode\n\r");
    UART_PRINT("        GPIO 13 and timer(5 sec) are the wk source configured\n\r");
    UART_PRINT("recv  - for receiving 1000 UDP packets\n\r");
    UART_PRINT("send  - for broadcasting 1000 UDP packets\n\r");
	
    do{
        
		UART_PRINT("cmd#");
		//
		// get cmd over UART
		//
		GetCmd(cCmdBuff, 20);

		//
		// parse the command
		//
		ParseCmd(cCmdBuff, &cCmd);

		if(cCmd == APP_SLEEP)
		{
			//
			// set timer and gpio as wake src
			//
			set_rtc_as_wk_src(WK_LPDS, LPDS_DUR_SEC, false);
			set_gpio_as_wk_src(WK_LPDS, GPIO_SRC_WKUP, PRCM_LPDS_FALL_EDGE);
			cc_idle_task_pm();
		}
		else if(cCmd == APP_RECV)
		{
			lLoopCount = 0;
		    /// waits for 1000 packets from a UDP client
		    while (lLoopCount < g_ulPacketCount)
		    {
		        iStatus = sl_RecvFrom(iSockID, g_cBsdBuf, sTestBufLen, 0,
		                     ( SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize );

				if( iStatus < 0 )
				{
					//error
					break;
				}
				lLoopCount++;
		    }
		    UART_PRINT("Recieved %u packets successfully \n\r",lLoopCount);
		    if(lLoopCount != g_ulPacketCount)
		    {
                if(iStatus == SL_EAGAIN)
                {
                    UART_PRINT("timed out\n\r");
                }
                else
                {
                    UART_PRINT("recv error: %d\n\r", iStatus);
                }
		    }
		}
		else if(cCmd == APP_SEND)
		{
			lLoopCount = 0;
		    // sending 1000 packets to the UDP server
		    while (lLoopCount < g_ulPacketCount)
		    {
		        // sending packet
		        iStatus = sl_SendTo(iSockID, g_cBsdBuf, sTestBufLen, 0,
		                                (SlSockAddr_t *)&sBrdAddr, iAddrSize);
		        if( iStatus <= 0 )
		        {
		            // error
		            UART_PRINT("send error\n\r");
                    break;
		        }
		        lLoopCount++;
		    }
		    UART_PRINT("Sent %u packets successfully\n\r",lLoopCount);
		}
	}while(FOREVER);
}
Example #20
0
File: main.c Project: Mecabot/IoT
//*****************************************************************************
//
//! This function POST to Event Hub REST API using TLS
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  Error number on Failure
//
//*****************************************************************************
long PostEventHubSSL()
{
    SlSockAddrIn_t    Addr;
    int    iAddrSize;
    unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1; //SL_SO_SEC_METHOD_SSLv3_TLSV1_2; //SL_SO_SEC_METHOD_TLSV1_2; //SL_SO_SEC_METHOD_SSLV3;
    unsigned int uiIP;
    unsigned int uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;
    long lRetVal = -1;
    int iSSLSockID;
    char acSendBuff[512];
    char acRecvbuff[1460];
    //char* pcBufData;
    char* pcBufHeaders;

    //
    // Retrieve IP from Hostname
    //
    lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET);
    if(lRetVal < 0)
    {
        CLI_Write("Could not retrive the IP Address for Azure Server.\n\r");
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    Addr.sin_family = SL_AF_INET;
    Addr.sin_port = sl_Htons(SSL_DST_PORT);
    Addr.sin_addr.s_addr = sl_Htonl(uiIP);
    iAddrSize = sizeof(SlSockAddrIn_t);

    //
    // Opens a secure socket
    //
    iSSLSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
    if( iSSLSockID < 0 )
    {
        CLI_Write("Unable to create secure socket.\n\r");
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Configure the socket as TLS (SSLV3.0 does not work because of POODLE - http://en.wikipedia.org/wiki/POODLE)
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod, sizeof(ucMethod));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (TLS).\n\r");
        sl_Close(iSSLSockID);
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Configure the socket as RSA with RC4 128 SHA
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher, sizeof(uiCipher));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (RSA).\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Configure the socket with Azure CA certificate - for server verification
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT_FILE_NAME, strlen(SL_SSL_CA_CERT_FILE_NAME));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (CA Certificate).\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Configure the recieve timeout
    //
    struct SlTimeval_t timeVal;
    timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT;    // In Seconds
    timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal));
    if(lRetVal < 0)
    {
       CLI_Write("Couldn't set socket option (Receive Timeout).\n\r");
       sl_Close(iSSLSockID);
       return lRetVal;
    }

    //
    // Connect to the peer device - Azure server */
    //
    lRetVal = sl_Connect(iSSLSockID, ( SlSockAddr_t *)&Addr, iAddrSize);
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't connect to Azure server.\n\r");
        sl_Close(iSSLSockID);
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Generate a random number for the temperture
    //
    srand((unsigned int)time(NULL));
    float a = 5.0;
    float fRandTemp = 25 - (((float)rand()/(float)(RAND_MAX)) * a);

    char  cTempChar[5];
    sprintf(cTempChar, "%.2f", fRandTemp);

    //
    // Creates the HTTP POST string.
    //
    int dataLength = strlen(DATA1) + 5 + strlen(DATA2);
    char cCLLength[4];

    pcBufHeaders = acSendBuff;
    strcpy(pcBufHeaders, POSTHEADER);
    pcBufHeaders += strlen(POSTHEADER);
    strcpy(pcBufHeaders, HOSTHEADER);
    pcBufHeaders += strlen(HOSTHEADER);
    strcpy(pcBufHeaders, AUTHHEADER);
    pcBufHeaders += strlen(AUTHHEADER);
    strcpy(pcBufHeaders, CHEADER);
    pcBufHeaders += strlen(CHEADER);
    strcpy(pcBufHeaders, CTHEADER);
    pcBufHeaders += strlen(CTHEADER);
    strcpy(pcBufHeaders, CLHEADER1);

    pcBufHeaders += strlen(CLHEADER1);
    sprintf(cCLLength, "%d", dataLength);

    strcpy(pcBufHeaders, cCLLength);
    pcBufHeaders += strlen(cCLLength);
    strcpy(pcBufHeaders, CLHEADER2);
    pcBufHeaders += strlen(CLHEADER2);

    strcpy(pcBufHeaders, DATA1);
    pcBufHeaders += strlen(DATA1);
    strcpy(pcBufHeaders , cTempChar);
    pcBufHeaders += strlen(cTempChar);
    strcpy(pcBufHeaders, DATA2);

    int testDataLength = strlen(pcBufHeaders);

    //
    // Send the packet to the server */
    //
    lRetVal = sl_Send(iSSLSockID, acSendBuff, strlen(acSendBuff), 0);
    if(lRetVal < 0)
    {
        CLI_Write("POST failed.\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Receive response packet from the server */
    //
    lRetVal = sl_Recv(iSSLSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0);
	if(lRetVal < 0)
	{
        CLI_Write("Received failed.\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
	}
	else
	{
		CLI_Write("HTTP POST Successful. Telemetry successfully logged\n\r");
	}

    sl_Close(iSSLSockID);

    return SUCCESS;
}
Example #21
0
File: main.c Project: dlugaz/All
//****************************************************************************
//
//! \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;
}
Example #22
0
//*****************************************************************************
//
//! RxStatisticsCollect
//!
//! This function
//!        1. Function for performing the statistics by listening on the
//!                channel given by the user.
//!
//! \return none
//
//*****************************************************************************
static int RxStatisticsCollect()
{
    int iSoc;
    char acBuffer[1500];
    SlGetRxStatResponse_t rxStatResp;
    //char cChar;
    int iIndex;
    int iChannel;
    long lRetVal = -1;
    int iRightInput = 0;
    char acCmdStore[512];
    struct SlTimeval_t timeval;

    timeval.tv_sec =  0;             // Seconds
    timeval.tv_usec = 20000;         // Microseconds.

    //
    //Clear all fields to defaults
    //
    rxStatResp.ReceivedValidPacketsNumber = 0;
    rxStatResp.ReceivedFcsErrorPacketsNumber = 0;
    rxStatResp.ReceivedAddressMismatchPacketsNumber = 0;
    rxStatResp.AvarageMgMntRssi = 0;
    rxStatResp.AvarageDataCtrlRssi = 0;
    for(iIndex = 0 ; iIndex < SIZE_OF_RSSI_HISTOGRAM ; iIndex++)
    {
        rxStatResp.RssiHistogram[iIndex] = 0;
    }
    for(iIndex = 0 ; iIndex < NUM_OF_RATE_INDEXES ; iIndex++)
    {
        rxStatResp.RateHistogram[iIndex] = 0;
    }
    rxStatResp.GetTimeStamp = 0;
    rxStatResp.StartTimeStamp = 0;

    //
    //Prompt the user for channel number
    //
    do
    {
        UART_PRINT("\n\rEnter the channel to listen[1-13]:");
        //
        // Wait to receive a character over UART
        //
        lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore));
        if(lRetVal == 0)
        {
            //
            // No input. Just an enter pressed probably. Display a prompt.
            //
            UART_PRINT("\n\rEnter Valid Input.");
            iRightInput = 0;
        }
        else
        {
            iChannel = (int)strtoul(acCmdStore,0,10);
            if(iChannel <= 0 || iChannel > 13)
            {
                UART_PRINT("\n\rWrong Input");
                iRightInput = 0;
            }
            else
            {
                iRightInput = 1;
            }
        }

    }while(!iRightInput);


    UART_PRINT("\n\rPress any key to start collecting statistics...");

    //
    // Wait to receive a character over UART
    //
    MAP_UARTCharGet(CONSOLE);

    //
    //Start Rx statistics collection
    //
    lRetVal = sl_WlanRxStatStart();
    ASSERT_ON_ERROR(lRetVal);

    //
    //Open Socket on the channel to listen
    //
    iSoc = sl_Socket(SL_AF_RF,SL_SOCK_RAW,iChannel);
    ASSERT_ON_ERROR(iSoc);

    // Enable receive timeout
    lRetVal = sl_SetSockOpt(iSoc,SL_SOL_SOCKET,SL_SO_RCVTIMEO, &timeval, \
                                  sizeof(timeval));
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Recv(iSoc,acBuffer,1470,0);
    if(lRetVal < 0 && lRetVal != SL_EAGAIN)
    {
        //error
        ASSERT_ON_ERROR(sl_Close(iSoc));
        ASSERT_ON_ERROR(lRetVal);
    }

    UART_PRINT("\n\rPress any key to stop and display the statistics...");

    //
    // Wait to receive a character over UART
    //
    MAP_UARTCharGet(CONSOLE);

    //
    //Get the Statistics collected in this time window
    //
    lRetVal = sl_WlanRxStatGet(&rxStatResp,0);
    if(lRetVal < 0)
    {
        //error
        ASSERT_ON_ERROR(sl_Close(iSoc));
        ASSERT_ON_ERROR(lRetVal);
    }

    //
    //Printing the collected statistics
    //
    UART_PRINT("\n\n\n\r\t\t=========================================== \n \
               \r");
    UART_PRINT("\n\r\t\t\t\tRx Statistics \n\r");
    UART_PRINT("\t\t=========================================== \n\r");

    UART_PRINT("\n\n\rThe data sampled over %ld microsec\n\n\r",    \
               (unsigned int)(rxStatResp.GetTimeStamp -
                              rxStatResp.StartTimeStamp));

    UART_PRINT("Number of Valid Packets Received:  %d\n\r",
                            rxStatResp.ReceivedValidPacketsNumber);
    UART_PRINT("Number of Packets Received Packets with FCS: %d\n\r",
                   rxStatResp.ReceivedFcsErrorPacketsNumber);
    UART_PRINT("Number of Packets Received Packets with PLCP: %d\n\n\r",   \
                   rxStatResp.ReceivedAddressMismatchPacketsNumber);
    UART_PRINT("Average Rssi for management packets: %d\
                    \n\rAverage Rssi for other packets: %d\n\r",
                   rxStatResp.AvarageMgMntRssi,rxStatResp.AvarageDataCtrlRssi);
    for(iIndex = 0 ; iIndex < SIZE_OF_RSSI_HISTOGRAM ; iIndex++)
    {
        UART_PRINT("Number of packets with RSSI in range %d dbm - %d dbm: %d\n\r",
                     ((-40+(-8*iIndex))),((-40+(-8*(iIndex+1)))+1),
                       rxStatResp.RssiHistogram[iIndex]);
    }
    UART_PRINT("\n\r");

    //for(iIndex = 0 ; iIndex < NUM_OF_RATE_INDEXES ; iIndex++)
    iIndex = 0;
    {
        UART_PRINT("Number of Packets with Rate 1Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 2Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 5.5Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 11Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 6Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 9Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 12Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 18Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 24Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 36Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 48Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate 54Mbps  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_0  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_1  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_2  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_3  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_4  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_5  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_6  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
        UART_PRINT("Number of Packets with Rate MCS_7  : %d\n\r",
                 rxStatResp.RateHistogram[iIndex++]);
     }

    //
    //Stop Rx statistics collection
    //
    lRetVal = sl_WlanRxStatStop();
    ASSERT_ON_ERROR(lRetVal);

    //
    //Close the socket
    //
    lRetVal = sl_Close(iSoc);
    ASSERT_ON_ERROR(lRetVal);

    return SUCCESS;
}
Example #23
0
//****************************************************************************
//
//! \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;
}
Example #24
0
void ControlServer(void *pvParameters) {

	char ServerBuffer[CONFIG_SERVER_BUFFER];
	char MsgBuffer[100];
	char *pMsgBuffer;

	SlSockAddrIn_t sAddr;
	SlSockAddrIn_t sLocalAddr;
	int32_t i32SockID;
	int32_t i32NewSockID;
	int32_t i32DataSize;
	int32_t i32NonBlocking = 1;
	SlSocklen_t i32AddrSize;
	int32_t retval;

	pMsgBuffer = &MsgBuffer[0];

	InitVariables();
	retval = ResetSimpleLink();
	if (retval < 0)
		while (1)
			;

	WlanConnect();

	sprintf(MsgBuffer, "Connectado a rede: %s\n\r"
			"IP: %d.%d.%d.%d\n\r"
			"Gateway: %d.%d.%d.%d\n\r", SL_IPV4_BYTE(g_sSLCon.DeviceIP, 3),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 2),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 1),
			SL_IPV4_BYTE(g_sSLCon.DeviceIP, 0),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 3),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 2),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 1),
			SL_IPV4_BYTE(g_sSLCon.GatewayIP, 0));

	osi_MsgQWrite(&g_sUartQuee, &pMsgBuffer, OSI_NO_WAIT);

	sLocalAddr.sin_family = SL_AF_INET;
	sLocalAddr.sin_port = sl_Htons((unsigned short) g_sSLCon.PortNumber);
	sLocalAddr.sin_addr.s_addr = 0;

	i32SockID = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
	sl_Bind(i32SockID, (SlSockAddr_t *) &sLocalAddr, sizeof(SlSockAddrIn_t));
	sl_Listen(i32SockID, 0);
	sl_SetSockOpt(i32SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &i32NonBlocking,
			sizeof(i32NonBlocking));

	while (1) {
		i32NewSockID = SL_EAGAIN;

		while (i32NewSockID < 0) {
			i32NewSockID = sl_Accept(i32SockID, (struct SlSockAddr_t *) &sAddr,
					(SlSocklen_t*) &i32AddrSize);
			if (i32NewSockID == SL_EAGAIN) {
				osi_Sleep(100);
			} else if (i32NewSockID < 0) {
				while (1) {
				}
			}
		}

		i32DataSize = sl_Recv(i32NewSockID, ServerBuffer, CONFIG_SERVER_BUFFER,
				0);

		if (strcmp(ServerBuffer, "Led On") == 0) {
			Led_Green(LED_ON);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Led Off") == 0) {
			Led_Green(LED_OFF);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp On") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, GPIO_PIN_6);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		} else if (strcmp(ServerBuffer, "Lamp Off") == 0) {
			MAP_GPIOPinWrite(GPIOA0_BASE, GPIO_PIN_6, 0);
			strcpy(ServerBuffer, "OK");
			i32DataSize = 3;
		}

		sl_Send(i32NewSockID, ServerBuffer, i32DataSize, 0);
		sl_Close(i32NewSockID);
	}

}
Example #25
0
        if (MqttSocketFd < 0) {
            return (MqttSocketFd);
        }

        SecurityMethod = *((_u8 *) (nw_security_opts->method));
        SecurityCypher = *((_u32 *) (nw_security_opts->cipher));

        if (nw_security_opts->n_file < 1  || nw_security_opts->n_file > 4 ) {
            PRINTF("\n\r ERROR: security files missing or wrong number of\
                   security files\n\r");
            PRINTF("\n\r ERROR: Did not create socket\n\r");
            return (-1);
        }

        //Set Socket Options that were just defined
        Status = sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECMETHOD,
                &SecurityMethod, sizeof(SecurityMethod));
        if (Status < 0) {
            sl_Close(MqttSocketFd);
            return (Status);
        }

        Status = sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECURE_MASK,
                &SecurityCypher, sizeof(SecurityCypher));
        if (Status < 0) {
            sl_Close(MqttSocketFd);
            return (Status);
        }

        if(nw_security_opts->n_file == 1){
        	Status = sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
        			 nw_security_opts->files[0], strlen(nw_security_opts->files[0]));
Example #26
0
//*****************************************************************************
//
//! 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;
}
Example #27
0
//*****************************************************************************
//
//! 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;
}
Example #28
0
File: main.c Project: bmxrt/CC3100
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;
}
Example #29
0
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;
}
//****************************************************************************
//
//!	\brief Opening a TCP server side socket and receiving data
//!
//!	This function opens a TCP socket in Listen mode and waits for an incoming
//!	TCP connection.
//! If a socket connection is established then the function will try to read
//!	1000 TCP packets from the connected client.
//!
//! \param[in] 		 port number on which the server will be listening on
//!
//! \return	         0 on success, -1 on error.
//!
//!	\note            This function will wait for an incoming connection till
//!					 one is established
//
//****************************************************************************
int BsdTcpServer(unsigned short usPort)
{
    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    int             iNewSockID;
    unsigned long            lLoopCount = 0;
    long            lBytesSent = 0;
    long            lNonBlocking = 1;
    int             iTestBufLen;

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10) + '0';
    }

    iTestBufLen  = BUF_SIZE;

    //filling the TCP server socket address
    sLocalAddr.sin_family = SL_AF_INET;
   sLocalAddr.sin_port = sl_Htons((unsigned short)usPort);
   sLocalAddr.sin_addr.s_addr = 0;
   
//	sLocalAddr.sin_port = usPort;
//	sLocalAddr.sin_addr.s_addr = SL_IPV4_VAL(192,168,1,101);
    

    // creating a TCP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( iSockID < 0 )
    {
      
       UART_PRINT("error at creating a TCP socket ! \n\r"); 
       
        // error
        return -1;
    }
    
    UART_PRINT("iSockID :"); 
    Z_NumDispaly(iSockID, 2);
        

    iAddrSize = sizeof(SlSockAddrIn_t);

    // binding the TCP socket to the TCP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
    
    UART_PRINT("error at binding the TCP socket to the TCP server address ! \n\r"); 
     
      // error
    	return -1;
    }
    
    
	UART_PRINT("binding the TCP socket to the TCP server address ok! \n\r"); 
        
        

    // putting the socket for listening to the incoming TCP connection
    iStatus = sl_Listen(iSockID, 0);
    if( iStatus < 0 )
    {
      
      UART_PRINT("error at putting the socket for listening to the incoming TCP connection ! \n\r"); 
    	return -1;
    }

	UART_PRINT("listen end! \n\r"); 

    // setting socket option to make the socket as non blocking
    iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking));
    iNewSockID = SL_EAGAIN;

UART_PRINT(" waiting for an incoming TCP connection! \n\r"); 

    // waiting for an incoming TCP connection
    while( iNewSockID < 0 )
    {
    	// accepts a connection form a TCP client, if there is any
    	// otherwise returns SL_EAGAIN
       iNewSockID = sl_Accept(iSockID, ( struct SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize);
       if( iNewSockID == SL_EAGAIN )
       {
         UtilsDelay(10000);
//	  UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); 
       }
       else if( iNewSockID < 0 )
       {
    	  // error
    	   UART_PRINT(" iNewSockID < 0! \n\r"); 
    	   return -1;
       }
    }


	    UART_PRINT("connect succeed the new iSockID :"); 
    		Z_NumDispaly(iSockID, 5);

	unsigned long the_client_ip = sl_BIGtoLITTLE_l( (unsigned long)sAddr.sin_addr.s_addr );


	UART_PRINT("the client ip is :"); 
	Z_IPDispaly(&the_client_ip);


	unsigned short the_client_port = sl_BIGtoLITTLE_S( (unsigned short)sAddr.sin_port );
        


	UART_PRINT("the client port is :"); 
	Z_NumDispaly( (unsigned long)the_client_port,5);
	


/*
UART_PRINT(" waits for 1000 packets from the connected TCP client! \n\r"); 

    // waits for 1000 packets from the connected TCP client
    while (lLoopCount < 1000)
    {
        iStatus = sl_Recv(iNewSockID, g_cBsdBuf, iTestBufLen, 0);
        if( iStatus <= 0 )
		{
			// error
        	return -1;
		}

		lLoopCount++;
		lBytesSent += iStatus;
    }
  */



    // sending 3 packets to the TCP server
    while (lLoopCount < 3)
    {
    	// sending packet
 //       iStatus = sl_Send(iNewSockID, g_cBsdBuf, iTestBufLen, 0 );

	char *send_buffer = "hellow i am cc3200 , welcome to wifi world !\n\r";

	 iStatus = sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
        if( iStatus <= 0 )
        {
        	UART_PRINT("error at sending packet\n\r"); 
		 Z_NumDispaly(lLoopCount,5);
            // error
        	return -1;
        }

        lLoopCount++;
        lBytesSent += iStatus;




    }





  
  
Sl_WlanNetworkEntry_t netEntries[20];
 char message[80];
 
 
     unsigned long intervalInSeconds = 10;
    sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds));
 
 
 while(1){  
    

    //Get Scan Result
   UINT8 Index = sl_WlanGetNetworkList(0,20,&netEntries[0]);


    for(UINT8 i=0; i< Index; i++)
    {
         snprintf(message, 60, "%d) SSID %s  RSSI %d \n\r",i,netEntries[i].ssid,netEntries[i].rssi);
	UART_PRINT(message); 
        
        
        sl_Send(iNewSockID, message, strlen(message), 0 );
        
    }  
    
  Z_DelayS(3);  

  }    
    









    // close the connected socket after receiving from connected TCP client
    sl_Close(iNewSockID);

    // close the listening socket
    sl_Close(iSockID);

    return 0;
}