#include "Include.h"

#include "delay.h"
#include "IoControl.h"
#include "Timer.h"
#include "Usart.h"
#include "spi1.h"
#include "w5500.h"
#include "socket.h"
#include "WatchDog.h"

#include "user_queue.h"

uint16_t  usRec_Length;        //接收数据长度    
uint8_t  ucRec_Buffer[1024*10]={0};  //接收数据缓存

extern uint16_t Usart1_ucRx_length;//串口1接收长度
extern uint8_t usart1_rx_done;//串口1接收完成标志
extern uint8_t Usart1_Rx_Buf[USART1_RX_BUFFER_SIZE];//串口1接收数据





int main(void)
{
	parameters_init();
	led_init();
	Tim2Init();
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	ble_usart_init(BLE_USART_BAUDRATE);
	
  spi1.initialize();
  w5500.initialize();
	
	InitQueue(&queue);
	
	WatchDogGpioInit();
  WatchDogEnable();
	while(1)
	{
    switch(getSn_SR(0))                           //获取socket0的状态
		{
			case (SOCK_INIT):                  //TCP工作模式
			{
				listen(0);				          //在TCP模式下监听客户端   
			}break;
													
			case (SOCK_ESTABLISHED):                 //建立链接
			{
				if(getSn_IR(0) & Sn_IR_CON)
				{
					setSn_IR(0, Sn_IR_CON);
				}
				usRec_Length = getSn_RX_RSR(0);        /*已接收数据长度*/
				if(usRec_Length>0)
				{				
					recv(0, ucRec_Buffer, usRec_Length); 
					
					net_received_data_analysis();					
//					send(0, ucRec_Buffer, usRec_Length);	  //自收发																																				 
				}
			}break;
							 
			case (SOCK_CLOSE_WAIT):
			{
				disconnect(0);                            /*断开连接*/   
			}break;
															
			case (SOCK_CLOSED):
			{
				socket(0,Sn_MR_TCP,60000,Sn_MR_ND);       /*打开socket0的60000端口*/   
			}break;	
			default:
				break;
		} 
		if((IINCHIP_READ(PHYCFGR)& LINK)==0)                 
		{
			 disconnect(0);  
			 socket(0,Sn_MR_TCP,60000,Sn_MR_ND);        /*打开socket0的60000端口*/
			 listen(0);	                                /*在TCP模式下监听客户端*/
		}  		
		
		if(1 == usart1_rx_done)    //串口接收到数据，网口发送至客户端
		{
			usart1_rx_done = 0;
			send(0, Usart1_Rx_Buf, Usart1_ucRx_length);
			Usart1_ucRx_length = 0;
		}
		
		FeedDog();	
	}
}



