#include "ec800m.h"
#include "usart.h"
#include "string.h"
#include "delay.h"


void EC800MPwoerOn(void)
{
	rcu_periph_clock_enable(RCU_GPIOD);
	gpio_init(GPIOD, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_2);
	gpio_bit_set(GPIOD,GPIO_PIN_2);
	Delay_Ms(5000);
	gd_pull_EC800M_pwr_up();
	gd_pull_EC800M_rst_down();
	Delay_Ms(50);
	gd_pull_EC800M_pwr_down();
	Delay_Ms(320);
	gd_pull_EC800M_rst_up();
	Delay_Ms(800);
	gd_pull_EC800M_pwr_up();
}

void EC800MSendCmd(char *buf, uint16_t len)
{
	uint16_t i;
	uint16_t data;
	for (i = 0; i < len; i++)
	{
		data = buf[i];
		usart_data_transmit(COM_EC800, data);
		while (RESET == usart_flag_get(COM_EC800, USART_FLAG_TBE))
			;
	}
}

void EC800MWaitReady()
{
	WaitResponse(RSP_READY, 5000);
}

/*
 *  函数名：bool WaitResponse(char *expectStr, int timeout)
 *  输入参数：expectStr 需要匹配的关键�? timeout超时时间
 *  输出参数：true flase
 *  返回值：�?
 *  函数作用：从UART0_RX_BUF缓冲区中匹配有无对应关键字有关键字则返回true无返回false
 */
bool WaitResponse(char *expectStr, int timeout)
{
	bool timeoutFlag = false;
	if (timeout >= 0)
	{
		timeoutFlag = true;
	}
	// gd_485_send((char *)&UART0_RX_BUF, strlen(UART0_RX_BUF)); 不清楚�?��?�调�?485意义

	while (1)
	{
		Delay_Ms(50);
		if (UART0_RX_STAT > 0)
		{
			UART0_RX_STAT = 0;
			char *p = strstr((char *)&UART0_RX_BUF, expectStr);
			if (p)
			{
				Clear_DMA_Buffer();
				return true;
			}
		}
		timeout -= 50;
		if (timeoutFlag == true && timeout <= 0)
		{
			Clear_DMA_Buffer();
			return false;
		}
	};
}



