/*************************************************
 Copyright (c) 2019
 All rights reserved.
 File name:     dlt645_port.c
 Description:   DLT645 移植&使用例程文件
 History:
 1. Version:
	Date:       2019-09-19
	Author:     wangjunjie
	Modify:
*************************************************/
#include "dlt645.h"
#include "stm32f2xx.h"
#include "timer.h"
#include "usart.h"
#include "string.h"
#include "gateway_message.h"


dlt645_port_t dlt645_port;
//static dlt645_port_t dlt645_port;

// dlt645 环境结构体
dlt645_t dlt645;

void dlt_callback(UART_HandleTypeDef *husart)
{
	 if(__HAL_UART_GET_FLAG(husart, UART_FLAG_RXNE) && __HAL_UART_GET_IT_SOURCE(husart, UART_IT_RXNE))
	{
		if (dlt645_port.index < DLT_RXSIZE - 1)
		{
				dlt645_port.rxBuf[dlt645_port.index] = husart->Instance->DR;
				dlt645_port.index++;
			}
		else
		{
				uint8_t data = husart->Instance->DR;
		}
	}
	if((dlt645_port.index > 0) && RESET != __HAL_USART_GET_FLAG(&USART_InitStruct_485, USART_FLAG_IDLE))
	{                           
		uint8_t temp;                            
		temp=husart->Instance->SR;             //先读sr再读DR才能清除idle中断
		temp=husart->Instance->DR;
		dlt645_port.done = 1;
	}	
}
/**
 * Name:    dlt645_hw_read
 * Brief:   dlt645 硬件层接收数据
 * Input:
 *  @ctx:   645运行环境
 *  @msg:   接收数据存放地址
 *  @len:   数据最大接收长度
 * Output:  读取数据的长度
 */
static int dlt645_hw_read(dlt645_t *ctx, uint8_t *msg, uint16_t len)
{
	int dataLength = 0;
	int startTime = gettick();
	while (1)
	{
		if (gettick() - startTime > dlt645_port.timeout * 1000 )
			return 0;
		if (dlt645_port.done == 1)
		{
			dataLength = dlt645_port.index;
			memcpy(msg, &(dlt645_port.rxBuf[4]), len-4);
			dataLength = dlt645_port.index-4;
			return dataLength;
		}
	}
}

/**
 * Name:    dlt645_hw_write
 * Brief:   dlt645 硬件层发送数据
 * Input:
 *  @ctx:   645运行环境
 *  @buf:   待发送数据
 *  @len:   发送长度
 * Output:  实际发送的字节数，错误返回-1
 */
static int dlt645_hw_write(dlt645_t *ctx, uint8_t *buf, uint16_t len)
{
	GATEWAY_PARAMS *get;
	get= get_gateway_config_params();
	memset(dlt645_port.rxBuf, 0, DLT_RXSIZE);
	delay_ms(10);
	if(get->comProtocol){ // get->protocol  1:232 0:485
		USART_232_Send(buf,len);
	}else{
		USART_485_Send(buf,len);
	}
	dlt645_port.index = 0;
	dlt645_port.done = 0;
	return len;
}






void dlt645_init(uint32_t timeout)
{
	HAL_GPIO_WritePin(DLT645_CTRL_GPIO,DLT645_CTRL_PIN,GPIO_PIN_SET);
	dlt645_port.timeout = timeout;
	dlt645_port.dlt645_Tx = 0;
	dlt645_port.index = 0;
}

// 645结构体注册
static dlt645_t dlt645 = {
	{0},
	0,
	dlt645_hw_write,
	dlt645_hw_read,
	(void *)&dlt645_port
};
