ERRORTYPE SensorManager::run()
	{
		ERRORTYPE eRet =  ET_OK;

		for(uint8_t u8Loop = 0; u8Loop < m_sConfig.u8SensorCount; ++u8Loop)
		{
			eRet = m_sConfig.pSensorList[u8Loop]->run();

			if(ET_OK != eRet)
			{
				xSemaphoreTake(xConsoleMutex, portMAX_DELAY);
				xSerialPrint_P(PSTR("/SENSOR MGR/ "));
				xSerialPrint_P(m_sConfig.pSensorList[u8Loop]->getMeasDataInfo(0).psMeasDataDescription);
				xSerialxPrintf_P( &xSerialPort, PSTR(", in state %u, encountered problems.\r\n"),m_sConfig.pSensorList[u8Loop]->getSensorState());
				xSemaphoreGive(xConsoleMutex);
				break;
			}
		}


		if( (ET_OK == eRet) &&
			(pdTRUE == xTaskCheckForTimeOut(&m_sLastResultPrintTimestamp, &m_sPrintResultsTimeout)))
		{
			this->printResultsStdOut();

			vTaskSetTimeOutState(&m_sLastResultPrintTimestamp);
			m_sPrintResultsTimeout = m_sConfig.sPrintResultsTimeout;
		}

		return eRet;
	}
	ERRORTYPE SensorManager::printResultsStdOut()
	{
		ERRORTYPE eRet =  ET_OK;

		//iterate through each sensor
		for(uint8_t u8SensorNo = 0; u8SensorNo < m_sConfig.u8SensorCount; ++u8SensorNo)
		{
			//iterate through each measurment data type which is provided by the sensor
			for(uint8_t u8MeasDataNo = 0; u8MeasDataNo < m_sConfig.pSensorList[u8SensorNo]->getMeasDataCount(); ++u8MeasDataNo)
			{
				ISensor::MeasurementDataInfo eMeasDataInfo = m_sConfig.pSensorList[u8SensorNo]->getMeasDataInfo(u8MeasDataNo);
				uint32_t u32Result = m_sConfig.pSensorList[u8SensorNo]->getResult(eMeasDataInfo.eMeasDataType);

				xSemaphoreTake(xConsoleMutex, portMAX_DELAY);
				xSerialPrint_P(PSTR("|Sensor Mgr| "));
				xSerialPrint_P(eMeasDataInfo.psMeasDataDescription);
				xSerialxPrintf_P( &xSerialPort, PSTR(" = %lu "),u32Result);
				xSerialPrint_P(eMeasDataInfo.psUnits);
				xSerialPrint_P(PSTR("\r\n"));
				xSemaphoreGive(xConsoleMutex);
			}
		}

		return eRet;
	}
Exemplo n.º 3
0
/**
 * @brief		Initialise the socket & buffer for HTTP server
 */
uint8_t init_httpd_ch(SOCKET s)
{
	uint8_t ret;
	ret = 0;

	if( getSn_SR(s) != SOCK_CLOSED )	// Check the preferred socket is available,
	{
		s = getSocket(SOCK_CLOSED, 0);	// otherwise find free socket,
		if(s == MAX_SOCK_NUM )        	// If there is no free socket?
			ret = 0;
	}
	else
	{
		ret = 1;
	}

	if(!socket(s, Sn_MR_TCP, IP_PORT_HTTP, 0x00)) // initialise the socket for DHCP service
	{
		xSerialPrintf_P(PSTR("HTTPD socket: %d, initialise fail..!\r\n"),s);
		ret = 0;
	}
#ifdef HTTP_DEBUG
	else
		xSerialPrintf_P(PSTR("HTTPD socket: %d, initialise success..!\r\n"),s);
#endif

	if(pHTTPRequest == NULL) // if there is no buffer allocated (pointer is NULL), then allocate request buffer for all HTTP functions.
	{
		if( !(pHTTPRequest = (HTTP_REQUEST *) pvPortMalloc( sizeof(HTTP_REQUEST) )))
		{
			xSerialPrint_P(PSTR("HTTP Request Buffer: malloc fail..!\r\n"));
			ret = 0;
		}
#ifdef HTTP_DEBUG
		else
			xSerialPrint_P(PSTR("HTTP Request Buffer: malloc success..!\r\n"));
#endif
	}

	if(pHTTPResponse == NULL) // if there is no buffer allocated (pointer is NULL), then allocate response buffer for all HTTP functions.
	{
		if( !(pHTTPResponse = (uint8_t *) pvPortMalloc( sizeof(uint8_t) * (FILE_BUFFER_SIZE + 1) )))
		{
			xSerialPrint_P(PSTR("HTTP Response Buffer: malloc fail..!\r\n"));
			vPortFree(pHTTPRequest);
			ret = 0;
		}
#ifdef HTTP_DEBUG
		else
			xSerialPrint_P(PSTR("HTTP Response Buffer: malloc success..!\r\n"));
#endif
	}

	HTTPD_SOCK = s;

	return ret;
}
Exemplo n.º 4
0
/**
@brief	This Socket function initialise the channel in particular mode, and set the port and wait for W5200/W5100 to complete its state change.
@return 1 for success else 0.
*/
uint8_t socket(
	SOCKET s, 			/**< for socket number */
	uint8_t protocol,	/**< for socket protocol */
	uint16_t port,		/**< the source port for the socket */
	uint8_t flag		/**< the option for the socket */
	)
{
	uint8_t ret;
#ifdef __DEF_WIZCHIP_DBG__
	xSerialPrint_P(PSTR(" socket()\r\n"));
#endif
	if (
		(protocol == Sn_MR_TCP) ||
		(protocol == Sn_MR_UDP) ||
		(protocol == Sn_MR_IPRAW) ||
		(protocol == Sn_MR_MACRAW) ||
		(protocol == Sn_MR_PPPOE)
		)
	{
		close(s);

		WIZCHIP_write(Sn_MR(s), (protocol | flag) );

		if (port != 0) {
			WIZCHIP_write(Sn_PORT0(s), (uint8_t)((port & 0xff00) >> 8));
			WIZCHIP_write(Sn_PORT1(s), (uint8_t)(port & 0x00ff));
		} else {
Exemplo n.º 5
0
void network_init(void)
{
	extern uip_eth_addr  my_eth_addr; // the Ethernet address assigned in the application

	/*-----------------------------------------------------------*/
	/* Network related stuff */

	IINCHIP_init(); 										// reset W5200 - First call to make

	setSHAR(my_eth_addr.addr);

#ifdef portW5200
	// TX MEM SIZE: Permissible values: 1:(1024) 2:(2048) 4:(4096) 8:(8192) 16:(16384)
	// RX MEM SIZE: Total for 8 ports shall equal not more than 16
	// Initialised in IINCHIP_init() in w5200.c
	extern uint8_t txsize[MAX_SOCK_NUM];
	extern uint8_t rxsize[MAX_SOCK_NUM];

    IINCHIP_sysinit ((uint8_t *)txsize, (uint8_t *)rxsize);	// set the Tx and Rx buffers

#else
	IINCHIP_sysinit(0x55, 0x55);
#endif

	if (!socket( MACRAW_PREFERRED_SOCKET, Sn_MR_MACRAW, 0x00, 0x00) ) // Opens the MAC raw mode socket.
	{
#ifdef __DEF_IINCHIP_DBG__
		xSerialPrint_P(PSTR("uIP MACRAW socket: 0, initialise fail..!\r\n"));
#endif
		return;

	}

}
Exemplo n.º 6
0
/**
 * This method is called periodically to check for new messages on the USB bus and process them.
 */
void hid_poll(void)
{
	hid_bootReport message;

	// Poll the USB layer.
	usb_poll();

	// If no USB device, there's no work for us to be done, so just return.
	if (hidDevice==NULL)
		return;

	// If not connected just return.
	if (!connected)
		return;

	// Check for an incoming HID message. don't wait for incoming packet so set "true"
	if ( !hid_pollMessage(&message, true) )
		{return;}

#ifdef DEBUG
	else
		{ xSerialPrint_P(PSTR("\r\nIN >> ")); hid_printMessage(&message);}
#endif

	// Handle messages
	if (*theConnection == HID_OPEN )
		hid_handleMessage( &message );
	else
		hid_handleOkay( &message ); // we got a character, so set the Connection to OPEN.

}
Exemplo n.º 7
0
void network_init(void)
{
	/*-----------------------------------------------------------*/
	/* Network related stuff */

#if (_WIZCHIP_ == 5100)
	WIZCHIP_init(); 										// reset W5200 - First call to make
	WIZCHIP_sysinit(0x55, 0x55);
#else
	WIZCHIP_init(); 										// reset W5200/W5500 - First call to make
	// TX MEM SIZE: Permissible values: 1:(1024) 2:(2048) 4:(4096) 8:(8192) 16:(16384)
	// RX MEM SIZE: Total for 8 ports shall equal not more than 16
	// Initialised in WIZCHIP_init() in wizchip_conf.c
	extern uint8_t txsize[_WIZCHIP_MAX_SOC_NUM_];
	extern uint8_t rxsize[_WIZCHIP_MAX_SOC_NUM_];

    WIZCHIP_sysinit ((uint8_t *)txsize, (uint8_t *)rxsize);	// set the Tx and Rx buffers
#endif

#if (_WIZCHIP_ != 5500) // xxx the Wiz550io has its MAC address loaded by the onboard MCU.
	extern uip_eth_addr  my_eth_addr; // the Ethernet address assigned in the application
	setSHAR(my_eth_addr.addr);
#endif

	if (!socket( MACRAW_SOCKET, Sn_MR_MACRAW, 0x00, 0x00) ) // Opens the MAC raw mode socket.
	{
#ifdef __DEF_WIZCHIP_DBG__
		xSerialPrint_P(PSTR("uIP MACRAW socket: 0, initialise fail..!\r\n"));
#endif
		return;

	}

}
Exemplo n.º 8
0
/**
 @brief	make response header such as html, gif, jpeg, zip, etc.
 */
void make_http_response_head(
	uint8_t * buf, 	/**< pointer to response header to be made */
	uint8_t type, 	/**< response type */
	uint32_t len	/**< size of response file / document */
	)
{
	PGM_P head = 0;
	uint8_t tmp[16];

	switch (type) {

		case PTYPE_HTML :
			head = RES_HTMLHEAD_OK;
			break;

		case PTYPE_GIF :
			head = RES_GIFHEAD_OK;
			break;

		case PTYPE_TEXT :
			head = RES_TEXTHEAD_OK;
			break;

		case PTYPE_JPEG :
			head = RES_JPEGHEAD_OK;
			break;

		case PTYPE_FLASH :
			head = RES_FLASHHEAD_OK;
			break;

		case PTYPE_MPEG :
			head = RES_MPEGHEAD_OK;
			break;

		case PTYPE_PDF :
			head = RES_PDFHEAD_OK;
			break;

		case PTYPE_ZIP :
			head = RES_ZIPHEAD_OK;
			break;

		default:
#ifdef HTTP_DEBUG
			xSerialPrint_P(PSTR("\r\n\r\nHTTP RESPONSE HEADER UNKNOWN-\r\n"));
#endif
			break;
	}

	sprintf((char *)tmp,"%ld", len);

	strcpy_P((char *)buf, head);
	strcat((char *)buf, (const char *)tmp);
	strcat_P((char *)buf, PSTR("\r\n\r\n\0"));
}
Exemplo n.º 9
0
void network_send(void)
{
	if (uip_len > 0)
	{
		if( !macraw_send( (uint8_t*)uip_buf, uip_len) )
		{
#ifdef __DEF_WIZCHIP_DBG__
			xSerialPrint_P(PSTR("\r\nuIP MACRAW: Fatal Error(0)."));
#endif
		}
	}
}
Exemplo n.º 10
0
void network_send(void)
{
	if (uip_len > 0)
	{
		if( !macrawsend( MACRAW_PREFERRED_SOCKET, (uint8_t*)uip_buf, uip_len) )
		{
#ifdef __DEF_IINCHIP_DBG__
			xSerialPrint_P(PSTR("\r\nuIP MACRAW: Fatal Error(0)."));
#endif
		}
	}
}
Exemplo n.º 11
0
static void TaskMonitor(void *pvParameters) // Monitor for Serial Interface
{
    (void) pvParameters;

	uint8_t *ptr;
	int32_t p1;

	// create the buffer on the heap (so they can be moved later).
	if(LineBuffer == NULL) // if there is no Line buffer allocated (pointer is NULL), then allocate buffer.
		if( !(LineBuffer = (uint8_t *) pvPortMalloc( sizeof(uint8_t) * LINE_SIZE )))
			xSerialPrint_P(PSTR("pvPortMalloc for *LineBuffer fail..!\r\n"));


    while(1)
    {
    	xSerialPutChar(&xSerialPort, '>');

		ptr = LineBuffer;
		get_line(ptr, (uint8_t)(sizeof(uint8_t)* LINE_SIZE)); //sizeof (Line);

		switch (*ptr++) {

		case 'h' : // help
			xSerialPrint_P( PSTR("rt - reset maximum & minimum temperatures\r\n") );
			xSerialPrint_P( PSTR("t  - show the time\r\n") );
			xSerialPrint_P( PSTR("t  - set the time\r\nt [<year yy> <month mm> <date dd> <day: Sun=0> <hour hh> <minute mm> <second ss>]\r\n") );
			break;

#ifdef portRTC_DEFINED
		case 't' :	/* t [<year yy> <month mm> <date dd> <day: Sun=0> <hour hh> <minute mm> <second ss>] */

			if (xatoi(&ptr, &p1)) {
				SetTimeDate.tm_year = (uint8_t)p1 + 100; 			// convert to (Gregorian - 1900)
				xatoi(&ptr, &p1); SetTimeDate.tm_mon = (uint8_t)p1;
				xatoi(&ptr, &p1); SetTimeDate.tm_mday = (uint8_t)p1;
				xatoi(&ptr, &p1); SetTimeDate.tm_wday = (uint8_t)p1;
				xatoi(&ptr, &p1); SetTimeDate.tm_hour = (uint8_t)p1;
				xatoi(&ptr, &p1); SetTimeDate.tm_min = (uint8_t)p1;
				if (!xatoi(&ptr, &p1))
					break;
				SetTimeDate.tm_sec = (uint8_t)p1;

				xSerialPrintf_P(PSTR("Set: %u/%u/%u %2u:%02u:%02u\r\n"), SetTimeDate.tm_year, SetTimeDate.tm_mon, SetTimeDate.tm_mday, SetTimeDate.tm_hour, SetTimeDate.tm_min, SetTimeDate.tm_sec);
				if (setDateTimeDS1307( &SetTimeDate ) == pdTRUE)
					xSerialPrint_P( PSTR("Setting successful\r\n") );

			} else {

				if (getDateTimeDS1307( &xCurrentTempTime.DateTime) == pdTRUE)
					xSerialPrintf_P(PSTR("Current: %u/%u/%u %2u:%02u:%02u\r\n"), xCurrentTempTime.DateTime.tm_year + 1900, xCurrentTempTime.DateTime.tm_mon, xCurrentTempTime.DateTime.tm_mday, xCurrentTempTime.DateTime.tm_hour, xCurrentTempTime.DateTime.tm_min, xCurrentTempTime.DateTime.tm_sec);
			}
			break;
#endif

		case 'r' : // reset
			switch (*ptr++) {
			case 't' : // temperature

				xMaximumTempTime = xCurrentTempTime;
				xMinimumTempTime = xCurrentTempTime;
				// Now we commit the time and temperature to the EEPROM, forever...
				eeprom_update_block(&xMaximumTempTime, &xMaximumEverTempTime, sizeof(xRTCTempArray));
				eeprom_update_block(&xMinimumTempTime, &xMinimumEverTempTime, sizeof(xRTCTempArray));
				break;

			default :
				break;
			}
			break;

		default :
			break;
		}
// 		xSerialPrintf_P(PSTR("\r\nSerial Monitor: Stack HighWater @ %u"), uxTaskGetStackHighWaterMark(NULL));
//		xSerialPrintf_P(PSTR("\r\nFree Heap Size: %u\r\n"), xPortGetMinimumEverFreeHeapSize() ); // needs heap_1, heap_2 or heap_4 for this function to succeed.

    }

}
Exemplo n.º 12
0
/**
 @brief	Analyse HTTP request and then services WEB.
*/
void process_HTTP(
	SOCKET s, 			/**< http server socket */
	uint8_t * buffer, 	/**< buffer pointer included http request */
	uint16_t length		/**< length of http request */
	)
{
	uint8_t * name;
	uint16_t bytes_read;
	TickType_t wait_send;
	FIL source_file;	/* File object for the source file */

	parse_HTTP_request(pHTTPRequest, buffer);			// After analysing request, convert into pHTTPRequest

	/* method Analyse */
	switch (pHTTPRequest->METHOD)
	{
		case METHOD_HEAD:
		case METHOD_GET :
		case METHOD_POST :

			name = get_HTTP_URI_name(pHTTPRequest->URI);

			if (!strcmp((const char *)name, "/")) strcpy((char *)name,"index.htm");	// If URI is "/", respond by index.htm

#ifdef WEB_DEBUG
			if(strlen( (const char *)name) < MAX_INT_STR ) xSerialPrintf_P(PSTR("\r\nPAGE : %s "), name);
			else xSerialPrint_P(PSTR("\r\nFILENAME TOO LONG"));
#endif

			find_HTTP_URI_type(&pHTTPRequest->TYPE, name);	//Check file type (HTML, TEXT, ICO, GIF, JPEG, ZIP are included)

			// OK now we start to respond to the info we've decoded.

			/* Open the specified file stored in the SD card FAT32 */
			if (f_open(&source_file, (const TCHAR *)name, FA_OPEN_EXISTING | FA_READ))
			{	// if file open failure

				memcpy_P( (char *)pHTTPResponse, ERROR_HTML_PAGE, strnlen_P(ERROR_HTML_PAGE, FILE_BUFFER_SIZE) );

#ifdef WEB_DEBUG
				xSerialPrint_P(PSTR("HTTP Unknown file or page.\r\n"));
				xSerialPrintf_P(PSTR("HTTP Response...\r\n%s\r\nResponse Size: %u \r\n"), pHTTPResponse, strlen_P(ERROR_HTML_PAGE));
#endif

				send( s, (const uint8_t*)pHTTPResponse, strlen_P(ERROR_HTML_PAGE));

			}
			else
			{	// if file open success

				make_HTTP_response_header( pHTTPResponse, pHTTPRequest->TYPE, source_file.fsize);

#ifdef WEB_DEBUG
				xSerialPrintf_P(PSTR("HTTP Opened file: %s  Source Size: %u \r\n"), name, source_file.fsize);
				xSerialPrintf_P(PSTR("HTTP Response Header...\r\n%s\r\nResponse Header Size: %u \r\n"), pHTTPResponse, strlen((char*)pHTTPResponse ));
#endif

				send(s, (const uint8_t*)pHTTPResponse, strlen((char*)pHTTPResponse ));

				wait_send = xTaskGetTickCount();

				while(getSn_TX_FSR(s)!= WIZCHIP_getTxMAX(s))

				{
					if( (xTaskGetTickCount() - wait_send) > (WEBSERVER_SOCKET_TIMEOUT / portTICK_PERIOD_MS) ) // wait up to 1.5 Sec
					{
#ifdef WEB_DEBUG
						xSerialPrint_P(PSTR("HTTP Response head send fail\r\n"));
#endif
						break;
					}
					vTaskDelay( 0 ); // yield until next tick.
				}

				for (;;)
				{
					if ( f_read(&source_file, pHTTPResponse, (sizeof(uint8_t)*(FILE_BUFFER_SIZE) ), &bytes_read) || bytes_read == 0 )
						break;   // read error or reached end of file

					if(pHTTPRequest->TYPE == PTYPE_HTML) // if we've got a html document, there might be some system variables to set
					{
						*(pHTTPResponse + bytes_read + 1) = 0; // make the buffer a string, null terminated
						bytes_read = replace_sys_env_value(pHTTPResponse, bytes_read); // Replace html system environment value to real value
					}

					if (send(s, (const uint8_t*)pHTTPResponse, bytes_read) != bytes_read)
						break;  // TCP/IP send error

					wait_send = xTaskGetTickCount();

					while(getSn_TX_FSR(s)!= WIZCHIP_getTxMAX(s))

					{
						if( (xTaskGetTickCount() - wait_send) > (WEBSERVER_SOCKET_TIMEOUT / portTICK_PERIOD_MS) ) // wait up to 1.5 Sec
						{
#ifdef WEB_DEBUG
							xSerialPrint_P(PSTR("HTTP Response body send fail\r\n"));
#endif
							break;
						}
						vTaskDelay( 0 ); // yield until next tick.
					}
				}
				f_close(&source_file);

				eeprom_busy_wait();
				eeprom_update_dword( &pagesServed, eeprom_read_dword(&pagesServed) +1 );
			}
			break;

		case METHOD_ERR :

			memcpy_P( (char *)pHTTPResponse, ERROR_REQUEST_PAGE, strnlen_P(ERROR_REQUEST_PAGE, FILE_BUFFER_SIZE) );

#ifdef WEB_DEBUG
			xSerialPrint_P(PSTR("HTTP Method Error.\r\n"));
			xSerialPrintf_P(PSTR("HTTP Response...\r\n%s\r\nResponse Size: %u \r\n"), pHTTPResponse, strlen_P(ERROR_REQUEST_PAGE));
#endif

			send( s, (const uint8_t*)pHTTPResponse, strlen_P(ERROR_REQUEST_PAGE));

			break;

		default :
			break;
	}
}
Exemplo n.º 13
0
static void hid_printMessage(hid_bootReport * message)
{
	xSerialPrint_P(PSTR("HID message\r\n"));
	hid_put_dump (message->generic, sizeof(hid_bootReport));
}
Exemplo n.º 14
0
/**
 * Handles events from the USB layer.
 *
 * @param device USB device that generated the event.
 * @param event USB event.
 */
static void hid_usbEventHandler(usb_device * device, usb_eventType event)
{
	hid_usbConfiguration handle;

	switch (event)
	{
	case USB_CONNECT:
		xSerialPrint_P(PSTR("HID_USB_CONNECT\r\n"));
		// Check if the newly connected device is an HID device, and initialise it if so.
		if (hid_isHIDDevice(device, HID_PROTOCOL_KEYBOARD, &handle))
		{
			hid_initUsb(device, &handle);

			// Success, signal that we are now connected by setting the global device handler to the connected device.
			hidDevice = device;
			connected = true;

			*theConnection = HID_OPEN;

			// set the device to idle so that it (particularly for a keyboard) only reports when there is an event.
			hid_setIdle(device);
		}
		break;

	case USB_DISCONNECT:
		xSerialPrint_P(PSTR("HID_USB_DISCONNECT\r\n"));
		// Check if the device that was disconnected is the HID device we've been using.
		if (device == hidDevice)
		{
			// Close all open HID connections.
			hid_closeAll();

			// Signal that we're no longer connected by setting the global device handler to NULL;
			hidDevice = NULL;
			connected = false;

			*theConnection = HID_CLOSED;
		}
		break;

	case 	USB_ADRESSING_ERROR:
		xSerialPrint_P(PSTR("HID_USB_ADRESSING_ERROR\r\n"));
		// Check if the device that was disconnected is the HID device we've been using.
		if (device == hidDevice)
		{
			// Close all open HID connections.
			hid_closeAll();

			// Signal that we're no longer connected by setting the global device handler to NULL;
			hidDevice = NULL;
			connected = false;

			*theConnection = HID_ERROR;
		}
		break;

	default:
		// ignore
		break;
	}
}
Exemplo n.º 15
0
int usb_dispatchPacket(uint8_t token, usb_endpoint * endpoint, unsigned int nakLimit)
{
//	uint32_t timeout = avr_millis() + USB_XFER_TIMEOUT;
	uint16_t timeout = xTaskGetTickCount() + USB_XFER_TIMEOUT / portTICK_RATE_MS; // XXX from freeRTOS
	uint8_t tmpdata;
	uint8_t rcode = 0;
	unsigned int nak_count = 0;
	char retry_count = 0;

	while (timeout > xTaskGetTickCount() )
	{
		// Analyze transfer result.

		// Launch the transfer.
		max3421e_write(MAX_REG_HXFR, (token | endpoint->address));
		rcode = 0xff;

		// Wait for interrupt
		while (timeout > xTaskGetTickCount() )
		{
			tmpdata = max3421e_read(MAX_REG_HIRQ);
			if (tmpdata & bmHXFRDNIRQ)
			{
				// Clear the interrupt.
				max3421e_write(MAX_REG_HIRQ, bmHXFRDNIRQ);

				rcode = 0x00;
				break;
			}
		}

		// Exit if timeout.
		if (rcode != 0x00)
			return (rcode);

		// Wait for HRSL
		while (timeout > xTaskGetTickCount() )
		{
			rcode = (max3421e_read(MAX_REG_HRSL) & 0x0f);
			if (rcode != hrBUSY)
				break;
			else
				xSerialPrint_P(PSTR("USB dispatch busy!\r\n"));
		}


		switch (rcode)
		{
			case hrNAK:
				nak_count++;
				if (nak_count == nakLimit)
					return (rcode);
				break;
			case hrTIMEOUT:
				retry_count++;
				if (retry_count == USB_RETRY_LIMIT)
					return (rcode);
				break;
			default:
				return (rcode);
		}
	}

	return (rcode);
}
Exemplo n.º 16
0
/**
 @brief 	Send ping-request to the specified peer and receive ping-reply from the specified peer.
 @return	1 - success, 0 - fail because free socket is not found or can't be opened.
 */
uint8_t ping(
	uint8_t count, 		/**< Ping request count. */
	uint16_t time, 		/**< wait ping reply time (unit : ms) */
	uint8_t* addr, 		/**< Peer IP Address string in dotted decimal format */
	PING_LOG* log		/**< result of ping */
	)
{

	PING_MSG* pPingRequest;		// pointer for Ping Request
	PING_MSG* pPingReply;		// pointer for Ping Reply
	uint32_t peerip;            // 32 bit Peer IP Address
	uint32_t tempip;			// IP address received from a destination
	uint16_t port;              // port number received from a destination

	SOCKET   s;					// socket variable for pinging

	uint16_t RandomSeqNum;		// Ping-Request ID

	uint16_t len;
	uint8_t  IsReceived;    	// Received packet = 1, not received packet = 0

    portTickType xInitialTick;

	/* Initialise PingRequest */


	if( !(pPingRequest = (PING_MSG *) pvPortMalloc( sizeof(PING_MSG) )))
		return 0;

	if( !(pPingReply   = (PING_MSG *) pvPortMalloc( sizeof(PING_MSG) )))
	{
		vPortFree(pPingRequest);
		return 0;
	}

	RandomSeqNum = htons( (uint16_t)rand());		// set ping-request's sequence number to random integer value

	pPingRequest->type = 0x08;           			// Ping-Request - ICMP
	pPingRequest->code = 0x00;						// always 0
	pPingRequest->checksum = 0;						// value of checksum before calculating checksum of ping-request packet
	pPingRequest->id = htons(PING_ID);				// set ping-request ID

	for(uint16_t i = 0 ; i < PING_OPT_LEN; i++)
		pPingRequest->OPT[i] = 'a' + i % 23;		// fill 'a'~'w' characters into ping-request's data

	/* Initialise result of ping */
	memset((void*)log,0,sizeof(PING_LOG));

    /* Verify arguments */
	if(!count) count = 4;					// set count to default value (4 pings)
	if(!time) time = 1000;					// set response time to default value (1000ms)

	/* Create a ping socket */
	s = getSocket(SOCK_CLOSED,0);
	if(s == MAX_SOCK_NUM)					// if it isn't exist free socket, Error
	{
		vPortFree(pPingRequest);
		vPortFree(pPingReply);
		return 0;
	}

	setSn_PROTO(s,IP_PROTO_ICMP);           	// Set upper-protocol of IP protocol
	if( socket( s, Sn_MR_IPRAW, 3000, 0) == 0)	// Open IP_RAW Mode , if fail then Error
	{
		vPortFree(pPingRequest);
		vPortFree(pPingReply);
		return 0;
	}
	peerip = htonl( inet_addr(addr));				// convert address string into 32bit address

	xSerialPrintf_P(PSTR("\r\nPinging %s with %d bytes of data:\r\n"), addr, (sizeof(PING_MSG) - 8));


	/* Ping Service */
	while( count-- != 0)
	{
		IsReceived = 0;
		pPingRequest->seqNum = htons( RandomSeqNum++);	// Increase Sequence number for next ping-request packet
		pPingRequest->checksum = 0;
		pPingRequest->checksum = htons( checksum( (uint8_t*)pPingRequest, sizeof(PING_MSG)));	// update checksum field

		(*log).PingRequest++;							// Increase PingRequest's value

		xInitialTick = xTaskGetTickCount();

		if( sendto( s, (const uint8_t *)pPingRequest, sizeof(PING_MSG), (uint8_t*)&peerip, 3000)== 0)	// Send Ping-Request to the specified peer. If fail, then it is occurred ARP Error.
		{
			(*log).ARPErr++;							// Increase ARPErr
			close(s);									// close the pinging socket

			/* Reopen pinging socket */
			setSn_PROTO(s,IP_PROTO_ICMP);
			if(socket( s, Sn_MR_IPRAW, 3000, 0)==0)
				{
				vPortFree(pPingRequest);
				vPortFree(pPingReply);
				return 0;
				}
			continue;
		}

		while( xTaskGetTickCount() < (xInitialTick + ( time / portTICK_RATE_MS )) )	// as long as time is remaining
		{

			if((len = getSn_RX_RSR(s)) > 0)		// Has pinging socket received a packet?
			{
				len = recvfrom( s, (uint8_t*)pPingReply, len, (uint8_t*)&tempip, &port);	// receive a packet from unknown peer

				xSerialPrintf_P(PSTR("\r\nReply from %s"), inet_ntoa( ntohl(tempip))); // convert 32 bit unknown peer IP address into string of IP Address.

				if( checksum((uint8_t*)pPingReply,len) != 0)		// if the packet's checksum value is correct
				{                                                   // not correct
					(*log).CheckSumErr++;                           // checksum error
					if(tempip == peerip) IsReceived = 1;
					xSerialPrint_P(PSTR(": Checksum Error"));
				}
				else if(pPingReply->type == 0)					// if the received packet is ping-reply
				{

					if((pPingReply->id!=pPingRequest->id) || (pPingReply->seqNum!=pPingRequest->seqNum) || (tempip!=peerip)) // verify id,sequence nubmer, and ip address
					{
						xSerialPrint_P(PSTR(": Unmatched ID / SeqNum from peer"));			// fail to verify
						(*log).UnknownMSG++;
					}
					else                                                    // success
					{
						IsReceived = 1;
						xSerialPrintf_P(PSTR(": bytes=%d, time<=%dms"),len-8,(xTaskGetTickCount()-xInitialTick)*portTICK_RATE_MS );
						(*log).PingReply++;
					}
				}
				else if( pPingReply->type == 3)  					// If the packet is unreachable message
				{
					IsReceived = 1;
					xSerialPrint_P(PSTR(": Destination unreachable"));
					(*log).UnreachableMSG++;
				}
				else if( pPingReply->type == 11)                 	// If the packet is time exceeded message
				{
				        IsReceived = 1;
				        xSerialPrint_P(PSTR(": TTL expired in transit"));
					(*log).TimeExceedMSG++;
				}
				else if( pPingReply->type == 8)					// Send ping reply to a peer
				{
					xSerialPrint_P(PSTR(": Ping Request message"));
					SendPingReply(pPingReply,tempip);
				}
				else                                                            // if the packet is unknown message
				{
					xSerialPrintf_P(PSTR(": Unknown message (type = 0x%02X)"), pPingReply->type);
					(*log).UnknownMSG++;
				}
			}
			else if(getSn_SR(s)==SOCK_CLOSED) 				// if it is occurred to fail to send arp packet
			{
				(*log).ARPErr++;
				close(s);									// close the pinging socket

				setSn_PROTO( s, IP_PROTO_ICMP);             // reopen the pinging socket
				if(socket( s, Sn_MR_IPRAW, 3000, 0) == 0 )
					{
					vPortFree(pPingRequest);
					vPortFree(pPingReply);
					return 0;
					}
				break;
			}
			if((xTaskGetTickCount() >= (xInitialTick + ( time / portTICK_RATE_MS ))) && (IsReceived == 0))					// If it is not received packet from the specified peer during waiting ping-reply packet.
			{
				(*log).Loss++;
				xSerialPrint_P(PSTR("Request timed out\r\n"));
			}

		}
	}

	/* Release pinging socket */
	setSn_PROTO(s,0);
	close(s);
	vPortFree(pPingRequest);
	vPortFree(pPingReply);
	return 1;
}
Exemplo n.º 17
0
/**
 @brief	parse http request from a peer
 */
void parse_http_request(
	HTTP_REQUEST *request, 	/**< request to be returned */
	uint8_t *buffer			/**< pointer to be parsed */
	)
{
	uint8_t *nexttok;
	nexttok = (uint8_t *)strtok((char *)buffer," ");
	if(!nexttok)
	{
		request->METHOD = METHOD_ERR;
		return;
	}
	if 	(!strcmp_P((const char *)nexttok, PSTR("GET")) || !strcmp_P((const char *)nexttok, PSTR("get")))
	{
		request->METHOD = METHOD_GET;
		nexttok = (uint8_t *)strtok(NULL," ");
#ifdef HTTP_DEBUG
		xSerialPrint_P(PSTR("METHOD_GET "));
#endif
	}
	else if (!strcmp_P((const char *)nexttok, PSTR("HEAD")) || !strcmp_P((const char *)nexttok, PSTR("head")))
	{
		request->METHOD = METHOD_HEAD;
		nexttok = (uint8_t *)strtok(NULL," ");
#ifdef HTTP_DEBUG
		xSerialPrint_P(PSTR("METHOD_HEAD "));
#endif

	}
	else if (!strcmp_P((const char *)nexttok, PSTR("POST")) || !strcmp_P((const char *)nexttok, PSTR("post")))
	{
		nexttok = (uint8_t *)strtok((char *)NULL,"\0");
		request->METHOD = METHOD_POST;
#ifdef HTTP_DEBUG
		xSerialPrint_P(PSTR("METHOD_POST "));
#endif
	}
	else
	{
		request->METHOD = METHOD_ERR;
#ifdef HTTP_DEBUG
		xSerialPrint_P(PSTR("METHOD_ERR "));
#endif
	}

	if(!nexttok)
	{
		request->METHOD = METHOD_ERR;
#ifdef HTTP_DEBUG
		xSerialPrint_P(PSTR("METHOD_ERR "));
#endif
		return;
	}

	strcpy((char *)request->URI,(const char *)nexttok);

#ifdef HTTP_DEBUG
	{
		uint16_t i;
		xSerialPrint_P(PSTR("\nhttp_request->URI: "));
		for(i=0; i < strlen((const char *)request->URI);i++)
			xSerialPrintf_P(PSTR("%c"),request->URI[i]);
		xSerialPrint_P(PSTR(""));
	}
#endif

}