
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf.h"
#include "nrf_delay.h"
//	#include "PreDefine.h"
#include "UartProcess.h"
//	#include "NodeTypeName.h"

void uart_event_handle(app_uart_evt_t * p_event)
{
	static uint8_t data_array[16];
	static uint8_t index = 0;
	//	uint32_t       err_code;

	switch (p_event->evt_type)
	{
		case APP_UART_DATA_READY:
			UNUSED_VARIABLE(app_uart_get(&data_array[index]));
			index++;
			if ((data_array[index - 1] == '\n') || (data_array[index - 1] == '\r'))
			{				// Host enter pair mode
				data_array[index-1] = 0;
				if (memcmp(data_array, "pair", sizeof("pair")) == 0 )
				{
					printf(Color_RED"\r\n... Pair ...\r\n"Color_NONE);
				#if 0
					if (gNoteType == NodeType_Host)
					{
						Rf_Param_Display();
						gEnterPairingModeFlag = 1;
						gNeedRunEsbInit = 1;							// Main-loop 看到這個 Flag, 就需要執行 Esb Init
						printf(Color_RED"\r\n ... Host Enter Pairing mode ...\r\n"Color_NONE);
					}
					else
					{
						uint8_t			lAddress1[4];
						lAddress1[3] = (uint8_t)(gNodeInfo.MyAddress & 0x000000FF);
						lAddress1[2] = (uint8_t)((gNodeInfo.MyAddress & 0x0000FF00) >> 8);
						lAddress1[1] = (uint8_t)((gNodeInfo.MyAddress & 0x00FF0000) >> 16);
						lAddress1[0] = (uint8_t)((gNodeInfo.MyAddress & 0xFF000000) >> 24);
						PairingProcess_Client(lAddress1);
					}
				#endif
				}
				else if (memcmp(data_array, "reboot", sizeof("reboot")) == 0 )
				{			// System Re-boot
					printf(Color_RED"\r\n... Re-boot ...\r\n"Color_NONE);
					nrf_delay_ms(1000);
					NVIC_SystemReset();
				}
				else if (memcmp(data_array, "default", sizeof("default")) == 0 )
				{			// Reset to default
				#if 0
					printf(Color_RED"\r\n... Reset to default ...\r\n"Color_NONE);
					flash_page_erase(0x7F000);
					nrf_delay_ms(1000);
					NVIC_SystemReset();
				#endif
				}
				else if (memcmp(data_array, "RfInfo", sizeof("RfInfo")) == 0 )
				{			// Get RF Information
				#if 0
					Rf_Param_Display();
				#endif
				}
				index = 0;
			}
			break;
		
		case APP_UART_COMMUNICATION_ERROR:
			APP_ERROR_HANDLER(p_event->data.error_communication);
			break;
		
		case APP_UART_FIFO_ERROR:
			APP_ERROR_HANDLER(p_event->data.error_code);
			break;
		
		default:
			break;
	}
}

void UART_Init(void)
{
	uint32_t err_code;

	const app_uart_comm_params_t comm_params =
	{
		UART_RX,
		UART_TX,
		RTS_PIN_NUMBER,
		CTS_PIN_NUMBER,
		APP_UART_FLOW_CONTROL_DISABLED,
		false,
		UART_BAUDRATE_BAUDRATE_Baud115200
	};

	APP_UART_FIFO_INIT(&comm_params,
			UART_RX_BUF_SIZE,
			UART_TX_BUF_SIZE,
			uart_event_handle,
			APP_IRQ_PRIORITY_LOWEST,
			err_code);
	
	APP_ERROR_CHECK(err_code);
};
