Exemple #1
0
//--tested, working--//
//--client and server side--//
size_t WiFiClient::write(const uint8_t *buffer, size_t size)
{
    //
    //don't do anything if not properly set up
    //
    if (_socketIndex == NO_SOCKET_AVAIL) {
        return 0;
    }

    //
    //write the buffer to the socket
    //
    int iRet = sl_Send(WiFiClass::_handleArray[_socketIndex], buffer, size, 0);

    // Flow control signal; perform a paced-retry.
    while (iRet == SL_EAGAIN) {
        delay(10);
#ifndef SL_PLATFORM_MULTI_THREADED$
        /* HACK: required in nonos builds, otherwise we hang in this loop */
        sl_Task();
#endif
        iRet = sl_Send(WiFiClass::_handleArray[_socketIndex], buffer, size, 0);
    }

    if ((iRet < 0) || (iRet != size)) {
        //
        //if an error occured or the socket has died, call stop()
        //to make the object aware that it's dead
        //
        stop();
        return 0;
    } else {
        return iRet;
    }
}
_i32 _ReadFileHeaders(_i16 fileSockId, _u8 *domian_name, _u8 *file_name)
{
    _i32 status=0;
    _i32 len;
    _u8 *send_buf = http_send_buf();

    Report("_ReadFileHeaders: domain=%s, file=%s\r\n", domian_name, file_name);
    http_build_request (send_buf, "GET ", domian_name, NULL, file_name, NULL, NULL);  

    len = sl_Send(fileSockId, send_buf, (_i16)strlen((const char *)send_buf), 0);
    if (len <= 0)
    {
        Report("_ReadFileHeaders: ERROR, sl_Send, status=%ld\r\n", len);
        return OTA_STATUS_ERROR;
    }

    Report("_ReadFileHeaders: skip http headers\r\n");
    status = http_skip_headers(fileSockId);
    if (status < 0)
    {
        Report("_ReadFileHeaders: ERROR, http_skip_headers, status=%ld\r\n", status);
        return OTA_STATUS_ERROR;
    }

    return OTA_STATUS_OK;
}
Exemple #3
0
/*!
    \brief Entering raw Transmitter\Receiver mode in order to send raw data
           over the WLAN PHY

    This function shows how to send raw data, in this case ping packets over
    the air in transmitter mode.

    \param[in]      Channel - number on which the data will be sent
    \param[in]      rate    - Rate for tx
    \param[in]      numberOfPackets - packets to be send
    \param[in]      interval - interval between each packet, should be greater
                    than 50ms.

    \return         0 for success, -ve otherwise

    \warning        We must be disconnected from WLAN AP in order to succeed
                    changing to transmitter mode
*/
static _i32 TxContinues(_i16 channel, SlRateIndex_e rate,
                        _u16 numberOfPackets, DWORD interval)
{
    _i16 sd = -1;
    _i16 len = -1;
    _u32 retVal = -1;

    sd = sl_Socket(SL_AF_RF, SL_SOCK_RAW, channel);
    if(sd < 0)
    {
        printf("Error In Creating the Socket\n");
        ASSERT_ON_ERROR(sd);
    }

    printf("Transmitting pinging data...\n");
    len = sizeof(RawData_Ping);
    while(numberOfPackets > 0)
    {
        retVal = sl_Send(sd, RawData_Ping, len,
                         SL_RAW_RF_TX_PARAMS(channel, rate, POWER_LEVEL_TONE, PREAMBLE));
        ASSERT_ON_ERROR(retVal);

        Sleep(interval);
        numberOfPackets--;
    }
    printf("Transmitting complete.\n");

    retVal = sl_Close(sd);
    ASSERT_ON_ERROR(retVal);

    return SUCCESS;
}
Exemple #4
0
//*****************************************************************************
//
//! Tx_continuous
//!
//! This function
//!        1. Function for sending out pinging data on the
//!                channel given by the user.
//!
//! \return none
//
//*****************************************************************************
static int Tx_continuous(int iChannel,SlRateIndex_e rate,int iNumberOfPackets,
                                    int iTxPowerLevel,long dIntervalMiliSec)
{
    int iSoc;
    long lRetVal = -1;
    long ulIndex;

    iSoc = sl_Socket(SL_AF_RF,SL_SOCK_RAW,iChannel);
    ASSERT_ON_ERROR(iSoc);

    UART_PRINT("Transmitting data...\r\n");
    for(ulIndex = 0 ; ulIndex < iNumberOfPackets ; ulIndex++)
    {
        lRetVal = sl_Send(iSoc,RawData_Ping,sizeof(RawData_Ping),\
                   SL_RAW_RF_TX_PARAMS(iChannel,  rate, iTxPowerLevel, PREAMBLE));
        if(lRetVal < 0)
        {
            sl_Close(iSoc);
            ASSERT_ON_ERROR(lRetVal);
        }
        //Sleep(dIntervalMiliSec);
        MAP_UtilsDelay(4000000);
    }

    lRetVal = sl_Close(iSoc);
    ASSERT_ON_ERROR(lRetVal);

    UART_PRINT("Transmission complete.\r\n");
    return SUCCESS;
}
static int32_t Lab16(void){uint32_t i;
  char *pt = NULL;

  memcpy(appData.HostName,SERVER,strlen(SERVER));
  if(GetHostIP() == 0){
    if( (appData.SockID = CreateConnection()) < 0 ) return -1;

/* HTTP GET string. */
    strcpy(appData.SendBuff,REQUEST); 
// 1) change Austin Texas to your city
// 2) you can change metric to imperial if you want temperature in F
    /* Send the HTTP GET string to the open TCP/IP socket. */
    sl_Send(appData.SockID, appData.SendBuff, strlen(appData.SendBuff), 0);

/* Receive response */
    sl_Recv(appData.SockID, &appData.Recvbuff[0], MAX_RECV_BUFF_SIZE, 0);
    appData.Recvbuff[strlen(appData.Recvbuff)] = '\0';

/* find ticker name in response*/
    pt = strstr(appData.Recvbuff, "id");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 5; // skip over id":"
      while((i<MAXLEN)&&(*pt)&&(*pt!='\"')){
        Id[i] = *pt; // copy into Id string
        pt++; i++;    
      }
    }
    Id[i] = 0;

/* find score Value in response */
    pt = strstr(appData.Recvbuff, "\"score\"");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 8; // skip over "score":
      while((i<MAXLEN)&&(*pt)&&(*pt!=',')){
        Score[i] = *pt; // copy into Score string
        pt++; i++;    
      }
    }
    Score[i] = 0;

/* find edxpost in response */
    pt = strstr(appData.Recvbuff, "edxpost");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 9; // skip over edxpost":
      for(i=0; i<8; i++){
        Edxpost[i] = *pt; // copy into Edxpost string
        pt++;     
      }
    }
    Edxpost[i] = 0;
    
    sl_Close(appData.SockID);
  }

  return 0;
}
Exemple #6
0
void WeatherForecastGet(int iSockID, cInt8 * acSendBuff,cInt8 * acRecvbuff)
{
    int iTXStatus;
    int iRXDataStatus;
    char* pcBufLocation;

    const char prefixBuffer[] = "GET /data/2.5/forecast?";
    const char postBuffer[]   = "&mode=xml&units=metric HTTP/1.1\r\nHost: api.openweathermap.org\r\nAccept: */";
    const char postBuffer2[]  = "*\r\n\r\n";


     memset(acRecvbuff, 0, RX_BUFF_SIZE);

    // Puts together the HTTP GET string.
    //
     pcBufLocation = acSendBuff;
     strcpy(pcBufLocation, prefixBuffer);
     pcBufLocation += strlen(prefixBuffer);

     #ifdef LOCATION_GPS
         int l_size;
         l_size = sprintf(pcBufLocation,"lat=%.6f&lon=%.6f",LOCATION_GPS_LAT,LOCATION_GPS_LON);
         pcBufLocation += l_size;
     #else
         strcpy(pcBufLocation,"q=");
         pcBufLocation += strlen("q=");
         strcpy(pcBufLocation,LOCATION_CITY_NAME);
         pcBufLocation += strlen(LOCATION_CITY_NAME);
     #endif

     strcpy(pcBufLocation, postBuffer);
     pcBufLocation += strlen(postBuffer);
     strcpy(pcBufLocation, postBuffer2);


    //
    // Send the HTTP GET string to the open TCP/IP socket.
    //
    DBG_PRINT("Sent HTTP GET request. \n\r");
    iTXStatus = sl_Send(iSockID, acSendBuff, strlen(acSendBuff), 0);
    MAP_UtilsDelay(DELAY_CLK_1_SEK *3);
    DBG_PRINT("Return value: %d \n\r", iTXStatus);

    //
    // Store the reply from the server in buffer.
    //
    DBG_PRINT("Received HTTP GET response data. \n\r");
    iRXDataStatus = sl_Recv(iSockID, &acRecvbuff[0], RX_BUFF_SIZE, 0);
    DBG_PRINT("Return value: %d \n\r", iRXDataStatus);
    acRecvbuff[RX_BUFF_SIZE - 1] = 0;

    DBG_PRINT(acRecvbuff);
}
Exemple #7
0
static telnet_result_t telnet_send_non_blocking (void *data, _i16 Len) {
    int16_t result = sl_Send(telnet_data.n_sd, data, Len, 0);

    if (result > 0) {
        telnet_data.txRetries = 0;
        return E_TELNET_RESULT_OK;
    }
    else if ((TELNET_TX_RETRIES_MAX >= ++telnet_data.txRetries) && (result == SL_EAGAIN)) {
        return E_TELNET_RESULT_AGAIN;
    }
    else {
        // error
        telnet_reset();
        return E_TELNET_RESULT_FAILED;
    }
}
/*
 * ::send()
 */
int send(int socket, const void *buffer, size_t length, int flags)
{
    int result = sl_Send(socket, buffer, length, flags);

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

    return result;  
}
int cc3200_write(Network* n, unsigned char* buffer, int len, int timeout_ms) {
	SlTimeval_t timeVal;
	SlFdSet_t fdset;
	int rc = 0;
	int readySock;

	SL_FD_ZERO(&fdset);
	SL_FD_SET(n->my_socket, &fdset);

	timeVal.tv_sec = 0;
	timeVal.tv_usec = timeout_ms * 1000;
	do {
		readySock = sl_Select(n->my_socket + 1, NULL, &fdset, NULL, &timeVal);
	} while(readySock != 1);
	rc = sl_Send(n->my_socket, buffer, len, 0);
	return rc;
}
Exemple #10
0
static bool telnet_send_with_retries (int16_t sd, const void *pBuf, int16_t len) {
    int32_t retries = 0;
    // abort sending if we happen to be within interrupt context
    if ((HAL_NVIC_INT_CTRL_REG & HAL_VECTACTIVE_MASK) == 0) {
        do {
            _i16 result = sl_Send(sd, pBuf, len, 0);
            if (result > 0) {
                return true;
            }
            else if (SL_EAGAIN != result) {
                return false;
            }
            HAL_Delay (TELNET_WAIT_TIME_MS);
        } while (++retries <= TELNET_TX_RETRIES_MAX);
    }
    return false;
}
Exemple #11
0
char* HTTP_Request(const char *hostName, uint16_t port, const char *method, const char *request, char *requestData1, char *requestData2) {
	SlSockAddrIn_t Addr; int32_t retVal; uint32_t ASize = 0;
	cleanup();
	strcpy(HostName, hostName);
	UARTprintf("\r\n\r\nUsing host: %s\r\n", HostName);
	retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET);
	if(retVal == 0){
		Addr.sin_family = SL_AF_INET;
		Addr.sin_port = sl_Htons(port);
		Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
		ASize = sizeof(SlSockAddrIn_t);
		SockID = -1;
		SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
		if( SockID >= 0 ){
			retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
		}
		if((SockID >= 0)&&(retVal >= 0)){
			uint32_t copyIndex = 0;
			strcpy(&SendBuff[copyIndex], method);  copyIndex += strlen(method);
			strcpy(&SendBuff[copyIndex], " ");     copyIndex += 1;
			strcpy(&SendBuff[copyIndex], request); copyIndex += strlen(request);
			if(requestData1) {
				strcpy(&SendBuff[copyIndex], requestData1);
				copyIndex += strlen(requestData1);
			}
			if(requestData2) {
				strcpy(&SendBuff[copyIndex], requestData2);
				copyIndex += strlen(requestData2);
			}
			strcpy(&SendBuff[copyIndex], REQ_1);   copyIndex += strlen(REQ_1);
			strcpy(&SendBuff[copyIndex], hostName); copyIndex += strlen(hostName);
			strcpy(&SendBuff[copyIndex], REQ_2);   copyIndex += strlen(REQ_2);
			SendBuff[copyIndex] = '\0';
			
			UARTprintf("Sending request: %s\r\n\r\n", SendBuff);
			sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
			sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
			sl_Close(SockID);
			
			return Recvbuff;
		}
	}
	return NULL;
}
Exemple #12
0
static bool telnet_send_with_retries (int16_t sd, const void *pBuf, int16_t len) {
    int32_t retries = 0;
    uint32_t delay = TELNET_WAIT_TIME_MS;
    // only if we are not within interrupt context and interrupts are enabled
    if ((HAL_NVIC_INT_CTRL_REG & HAL_VECTACTIVE_MASK) == 0 && query_irq() == IRQ_STATE_ENABLED) {
        do {
            _i16 result = sl_Send(sd, pBuf, len, 0);
            if (result > 0) {
                return true;
            }
            else if (SL_EAGAIN != result) {
                return false;
            }
            // start with the default delay and increment it on each retry
            mp_hal_delay_ms(delay++);
        } while (++retries <= TELNET_TX_RETRIES_MAX);
    }
    return false;
}
Exemple #13
0
//!! With this implementation, only 1 server can run on each cc3200 !!//
size_t WiFiServer::write(const uint8_t *buffer, size_t size)
{
    //
    //iterate through the sockets and write the data to any connected clients
    //the arduino API dictates to write the data to ALL clients
    //
    int i;
    int sentBytes = 0;
    for (i = 0; i < MAX_SOCK_NUM; i++) {
        if (WiFiClass::_typeArray[i] == TYPE_TCP_CONNECTED_CLIENT) {
            //
            //Write the data to the connected client and increment
            //the number of bytes send
            //
            int handle = WiFiClass::_handleArray[i];
            sentBytes += sl_Send(handle, buffer, size, NULL);
        }
    }
    return sentBytes;
}
//****************************************************************************
//
//!	\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;
}
Exemple #15
0
static int UpdateSockets(void)
{
    int retval;

    for(int i=0; i<NUM_SOCKETS; i++){
        if(!GetSockConnected(i)){
            if(SockAccept(i) == RET_FAILURE) {RETURN_ERROR(ERROR_UNKNOWN, "Socket accept fail");}
        }
        else{
            xSemaphoreTake(socket_state[i].buf_access, portMAX_DELAY);

            //Update TX
            if(socket_state[i].tx_buf_occupancy){
                retval = sl_Send(socket_state[i].child_id,
                        &(socket_state[i].tx_buf[socket_state[i].tx_buf_i_out % SOCKET_RXBUF_SIZE]),
                        MIN(socket_state[i].tx_buf_occupancy,
                                SOCKET_TXBUF_SIZE - (socket_state[i].tx_buf_i_out % SOCKET_RXBUF_SIZE)), //Prevent overflow at wraparound point
                                0);
                if(retval<0) {
                    LogSLError(retval);
                    xSemaphoreGive(socket_state[i].buf_access); RETURN_ERROR(retval, "Socket send fail");
                }
                else{
                    socket_state[i].tx_buf_occupancy -= retval;
                    socket_state[i].tx_buf_i_out += retval;
                }
            }
            if((xSemaphoreTake(socket_state[i].tx_buf_full, 0) == pdFALSE) //poll semaphore
                    && (socket_state[i].tx_buf_occupancy<SOCKET_TXBUF_SIZE)){
                xSemaphoreGive(socket_state[i].tx_buf_full); //unblock threads waiting for space
            }

            //Update RX
            retval = sl_Recv(socket_state[i].child_id,
                    &(socket_state[i].rx_buf[socket_state[i].rx_buf_i_in % SOCKET_RXBUF_SIZE]),
                    MIN((SOCKET_RXBUF_SIZE - socket_state[i].rx_buf_occupancy),
                            SOCKET_RXBUF_SIZE - (socket_state[i].rx_buf_i_in % SOCKET_RXBUF_SIZE)), //Prevent overflow at wraparound point
                            0);
            if(retval > 0){
                socket_state[i].rx_buf_i_in += retval;
                socket_state[i].rx_buf_occupancy += retval;
                if(xSemaphoreTake(socket_state[i].rx_buf_empty, 0) == pdFALSE) { //poll semaphore
                    xSemaphoreGive(socket_state[i].rx_buf_empty); //unblock threads waiting for characters
                }
            }
            else if(retval==0){
                socket_state[i].status = SOCKET_STARTED;
                LOG(LOG_VERBOSE, "Socket %d: client disconnected/broken.", i);
                sl_Close(socket_state[i].child_id);
            }
            else if((retval<0) && (retval!=SL_EAGAIN)) {
                LogSLError(retval);
                xSemaphoreGive(socket_state[i].buf_access); RETURN_ERROR(retval, "Socket recv fail");
            }


            xSemaphoreGive(socket_state[i].buf_access);
        }
    }

    return RET_SUCCESS;
}
int GetFileFromServer(const int socket, const char* filename, const char* filenameInFlash) {
	int transfer_len = 0;
	long retVal = 0;
	long fileHandle = -1;
	unsigned long Token = 0, bytesReceived = 0;
	unsigned char *pBuff = 0;
	unsigned long file_size = 0;
	unsigned char buffer[MAX_BUFF_SIZE + 1];

	UART_PRINT("Start downloading the file %s\r\n", filename);

	memset(buffer, 0, sizeof(buffer));

	// Puts together the HTTP GET string.
	strcpy((char *) buffer, PREFIX_BUFFER);
	strcat((char *) buffer, filename);
	strcat((char *) buffer, POST_BUFFER);

	// Send the HTTP GET string to the opened TCP/IP socket.
	transfer_len = sl_Send(socket, buffer, strlen((const char *) buffer), 0);
	if (transfer_len < 0) {
		// error
		UART_PRINT("Socket Send Error\r\n");
		return -1;
	}

	memset(buffer, 0, sizeof(buffer));

	// get the reply from the server in buffer.
	transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);

	if (transfer_len > 0) {
		// Check for 404 return code
		if (strstr((const char *) buffer, HTTP_FILE_NOT_FOUND) != 0) {
			UART_PRINT("File not found, check the file and try again\r\n");
			return -1;
		}

		// if not "200 OK" return error
		if (strstr((const char *) buffer, HTTP_STATUS_OK) == 0) {
			UART_PRINT("Error during downloading the file\r\n");
			return -1;
		}

		// check if content length is transfered with headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_CONTENT_LENGTH);
		if (pBuff != 0) {
			pBuff += strlen(HTTP_CONTENT_LENGTH);

			while (*pBuff != 0x0d)
				pBuff++;
			unsigned long multiplicant = 1;

			pBuff--;
			while (*pBuff != ' ') {
				file_size += (*pBuff - '0') * multiplicant;
				multiplicant *= 10;
				pBuff--;
			}

			if (file_size == 0) {
				UART_PRINT("\nContent Length not detected.\r\n");
				return -1;
			}

			UART_PRINT("Content Length %d\r\n", file_size);
		} else {
			UART_PRINT("\nContent Length not detected.\r\n");
			return -1;
		}

		// "\r\n\r\n" marks the end of headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_END_OF_HEADER);
		if (pBuff == 0) {
			UART_PRINT("Invalid response\r\n");
			return -1;
		}
		// Increment by 4 to skip "\r\n\r\n"
		pBuff += 4;

		// Adjust buffer data length for header size
		transfer_len -= (pBuff - buffer);
	}

	// Delete eventually existing temporary file
	sl_FsDel((unsigned char *) filenameInFlash, Token);
	// Create a temporary file to save the downloaded file
	// open a user file for writing
	retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_WRITE, &Token, &fileHandle);
	if (retVal < 0) {
		// File Doesn't exit create a new of file_size KB file
		retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_CREATE(file_size, _FS_FILE_PUBLIC_WRITE), &Token, &fileHandle);
		if (retVal < 0) {
			UART_PRINT("Error during opening the temporary file\r\n");
			return -1;
		}
	}
	while (bytesReceived < file_size) {
		retVal = sl_FsWrite(fileHandle, bytesReceived, (unsigned char *) pBuff, transfer_len);
		if (retVal < 0) {
			retVal = sl_FsClose(fileHandle, 0, 0, 0);
			retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
			UART_PRINT("Error during writing the file\r\n");
			return -1;
		}
		bytesReceived += transfer_len;
		if (bytesReceived == file_size) break;

		memset(buffer, 0, sizeof(buffer));
		transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);
		pBuff = buffer;
	}

	// Close the opened file
	retVal = sl_FsClose(fileHandle, 0, 0, 0);

	if (bytesReceived != file_size) {
		UART_PRINT("Error While File Download\r\n");
		retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
		return -1;
	} else {
		UART_PRINT("\nDownloading File Completed\r\n");
	}
	return 0;
}
int 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;
}
Exemple #18
0
static int http_post(int iTLSSockID, char data[200]){
    char acSendBuff[512];
    char acRecvbuff[1460];
    char cCLLength[200];
    char* pcBufHeaders;
    int lRetVal = 0;

	pcBufHeaders = acSendBuff;
	strcpy(pcBufHeaders, POSTHEADER);
	pcBufHeaders += strlen(POSTHEADER);
	strcpy(pcBufHeaders, " HTTP/1.1\r\n");
	pcBufHeaders += strlen(" HTTP/1.1\r\n");
	strcpy(pcBufHeaders, HOSTHEADER);
	pcBufHeaders += strlen(HOSTHEADER);

	//
	strcpy(pcBufHeaders, CHEADER0);
	pcBufHeaders += strlen(CHEADER0);
	//

	strcpy(pcBufHeaders, CHEADER);
	pcBufHeaders += strlen(CHEADER);
	strcpy(pcBufHeaders, "\r\n\r\n");
  //calculates the length of the message, DATA1 + text message + DATA2
	int dataLength = strlen(DATA1);
	dataLength += strlen(data);
	dataLength += strlen(DATA3);
	strcpy(pcBufHeaders, CTHEADER);
	pcBufHeaders += strlen(CTHEADER);
	strcpy(pcBufHeaders, CLHEADER1);

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

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

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

	strcpy(pcBufHeaders, data);
	pcBufHeaders += strlen(data);

	strcpy(pcBufHeaders, DATA3);
	pcBufHeaders += strlen(DATA3);

	int testDataLength = strlen(pcBufHeaders);

	//
	// Send the packet to the server */
	//

	printf("%s\n", acSendBuff);

	lRetVal = sl_Send(iTLSSockID, acSendBuff, strlen(acSendBuff), 0);
	if(lRetVal < 0)
	{
		UART_PRINT("POST failed. Error Number: %i\n\r",lRetVal);
    	sl_Close(iTLSSockID);
    	GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    	return lRetVal;
	}
	lRetVal = sl_Recv(iTLSSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0);
	if(lRetVal < 0)
	{
		UART_PRINT("Received failed. Error Number: %i\n\r",lRetVal);
	    //sl_Close(iSSLSockID);
	    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
	       return lRetVal;
	}
	else
	{
		acRecvbuff[lRetVal+1] = '\0';
		UART_PRINT(acRecvbuff);
		UART_PRINT("\n\r\n\r");
	}

	return 0;
}
Exemple #19
0
int main(void){int32_t retVal;  SlSecParams_t secParams;
  char *pConfig = NULL; INT32 ASize = 0; SlSockAddrIn_t  Addr;
	ADC0_InitSWTriggerSeq3_Ch9();         // allow time to finish activating
  initClk();        // PLL 50 MHz
	Output_On();
	UART_Init();      // Send data to PC, 115200 bps
  Timer1_Init();
  LED_Init();       // initialize LaunchPad I/O 
  UARTprintf("Weather App\n");
  retVal = configureSimpleLinkToDefaultState(pConfig); // set policies
  if(retVal < 0)Crash(4000000);
  retVal = sl_Start(0, pConfig, 0);
  if((retVal < 0) || (ROLE_STA != retVal) ) Crash(8000000);
  secParams.Key = PASSKEY;
  secParams.KeyLen = strlen(PASSKEY);
  secParams.Type = SEC_TYPE; // OPEN, WPA, or WEP
  sl_WlanConnect(SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0);
  while((0 == (g_Status&CONNECTED)) || (0 == (g_Status&IP_AQUIRED))){
    _SlNonOsMainLoopTask();
  }
  UARTprintf("Connected\n");
  while(1){
		int i = 0;
		while(i < 10){
			int sendc = 0;
			strcpy(HostName,"openweathermap.org");
			retVal = sl_NetAppDnsGetHostByName(HostName,
							 strlen(HostName),&DestinationIP, SL_AF_INET);
			if(retVal == 0){
				Addr.sin_family = SL_AF_INET;
				Addr.sin_port = sl_Htons(80);
				Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
				ASize = sizeof(SlSockAddrIn_t);
				SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
				if( SockID >= 0 ){
					retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
				}
				if((SockID >= 0)&&(retVal >= 0)){
					strcpy(SendBuff,REQUEST); 
					sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
					sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
					sl_Close(SockID);
					LED_GreenOn();
					UARTprintf("\r\n\r\n");
					UARTprintf(Recvbuff);  UARTprintf("\r\n");
				}
			}
			ST7735_OutUDec(sendc);
			ST7735_OutString("\n");
			i++;
		}
		
		//while(Board_Input()==0){}; // wait for touch
		LED_GreenOff();
		//Temp Part e
		getTemp(Recvbuff);
		ST7735_OutChar('T');
		ST7735_OutChar('e');
		ST7735_OutChar('m');
		ST7735_OutChar('p');
		ST7735_OutChar(' ');
		ST7735_OutChar('=');
		ST7735_OutChar(' ');
		for(int i = 0; i < 5; i++){
			ST7735_OutChar(myArray[i]);
		}
		ST7735_OutChar('\n');

		//ADC Part f
		ADC0_SAC_R = ADC_SAC_AVG_64X;    //enable 64 times average before obtaining result
    int voltage = ADC0_InSeq3();
		ST7735_OutString("Voltage~");
		ST7735_sDecOut3(voltage);
		
		char* voltageString;
		char voltageStringNum[5];
		sprintf(voltageStringNum, "%.1d.%.3d", voltage/1000, voltage%1000);
		//ST7735_OutString(voltageStringNum);
		
		char* sendString;
		char str1[173] = "GET /query?city=Austin%20Texas&id=Ty%20Winkler%20Jeremiah%20Bartlett&greet=Voltage%3D";
		strcat(str1, voltageStringNum);
		strcat(str1, "V&edxcode=8086 HTTP/1.1\r\nUser-Agent: Keil\r\nHost: embsysmooc.appspot.com\r\n\r\n");
		
		
		strcpy(HostName,"embsysmooc.appspot.com");
		retVal = sl_NetAppDnsGetHostByName(HostName,
						 strlen(HostName),&DestinationIP, SL_AF_INET);
		if(retVal == 0){
			Addr.sin_family = SL_AF_INET;
			Addr.sin_port = sl_Htons(80);
			Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
			ASize = sizeof(SlSockAddrIn_t);
			SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
			if( SockID >= 0 ){
				retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
			}
			if((SockID >= 0)&&(retVal >= 0)){
				strcpy(SendBuff, str1);
				count = 0;					
				sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
				sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
				sl_Close(SockID);
				LED_GreenOn();
				UARTprintf("\r\n\r\n");
				//ST7735_OutString(Recvbuff);  
				UARTprintf("\r\n");
			}
		}
		while(1);
	}
}
Exemple #20
0
//*****************************************************************************
//
//! This function POST to Event Hub REST API using TLS
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  Error number on Failure
//
//*****************************************************************************
long PostEventHubSSL()
{
    SlSockAddrIn_t    Addr;
    int    iAddrSize;
    unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1; //SL_SO_SEC_METHOD_SSLv3_TLSV1_2; //SL_SO_SEC_METHOD_TLSV1_2; //SL_SO_SEC_METHOD_SSLV3;
    unsigned int uiIP;
    unsigned int uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;
    long lRetVal = -1;
    int iSSLSockID;
    char acSendBuff[512];
    char acRecvbuff[1460];
    //char* pcBufData;
    char* pcBufHeaders;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    int testDataLength = strlen(pcBufHeaders);

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

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

    sl_Close(iSSLSockID);

    return SUCCESS;
}
Exemple #21
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);
	}

}
/****************************************************************************
//
//!	\brief Opening a TCP client side socket and sending data
//!
//! This function opens a TCP socket and tries to connect to a Server IP_ADDR
//!	waiting on port PORT_NUM.
//!	If the socket connection is successful then the function will send 1000
//! TCP packets to the server.
//!
//!    \param[in] 		 port number on which the server will be listening on
//!
//!    \return	         0 on success, -1 on Error.
//
****************************************************************************/
int BsdTcpClient(unsigned short usPort)
{
    int             iCounter;
    short           sTestBufLen;
    SlSockAddrIn_t  sAddr;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    unsigned long            lLoopCount = 0;
    long            lBytesSent = 0;

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

    sTestBufLen  = BUF_SIZE;

    //filling the TCP server socket address
    sAddr.sin_family = SL_AF_INET;


//	sAddr.sin_port = usPort;
//	sAddr.sin_addr.s_addr = IP_ADDR ;
	
   sAddr.sin_port = sl_Htons((unsigned short)usPort);
   sAddr.sin_addr.s_addr = sl_Htonl((unsigned int)IP_ADDR);

    iAddrSize = sizeof(SlSockAddrIn_t);

    // creating a TCP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( iSockID < 0 )
    {

	UART_PRINT("error at creating a TCP socket ! \n\r"); 
        // error
       return -1;
    }


	UART_PRINT("iSockID :"); 
	Z_NumDispaly(iSockID, 2);


    // connecting to TCP server
    iStatus = sl_Connect(iSockID, ( SlSockAddr_t *)&sAddr, iAddrSize);
    if( iStatus < 0 )
    {

	UART_PRINT("error at connecting to TCP server ! \n\r"); 
        // error
    	return -1;
    }

	UART_PRINT("  connected to TCP server ok! \n\r"); 

    // sending 1000 packets to the TCP server
    while (lLoopCount < 1000)
    {
    	// sending packet
        iStatus = sl_Send(iSockID, g_cBsdBuf, sTestBufLen, 0 );
        if( iStatus <= 0 )
        {
        	UART_PRINT("error at sending packet"); 
		 Z_NumDispaly(lLoopCount,2);
            // error
        	return -1;
        }

        lLoopCount++;
        lBytesSent += iStatus;
    }

    //closing the socket after sending 1000 packets
    sl_Close(iSockID);

    return 0;
}