#include "rs485.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_dma.h"

static struct file_config_s file_config;
struct rs485_data_s rs485_data;
uint8_t rs485_buff_tx[RS485_BUFF_TX_LEN] __attribute__((aligned(16)));
uint8_t rs485_buff_rx[RS485_BUFF_RX_LEN];

void file_config_copy(struct file_config_s *dst, struct file_config_s *src)
{
    uint32_t *s, *d;

    s = (uint32_t *)src;
    d = (uint32_t *)dst;
    for (uint32_t i = 0; i < sizeof(struct file_config_s) / 4; i++) {
        *d = *s;
        s++;
        d++;
    }
}

void file_config_get(struct file_config_s *cfg)
{
    uint32_t addr;
    uint32_t *p;

    addr = ADDR_CONFIG;
    for (addr = ADDR_CONFIG; addr < (ADDR_CONFIG + SIZE_CONFIG - sizeof(struct file_config_s)); addr += sizeof(struct file_config_s)) {
        p = (uint32_t *)addr;
        if (addr == p[0]) {
            continue;
        } else if (0xFFFFFFFF == p[0]) {
            file_config_copy(cfg, (struct file_config_s *)(addr - sizeof(struct file_config_s)));
            return;
        } else {
            cfg->baudrate = RS485_DEFAULT_BAUDRATE;
            cfg->parity = RS485_DEFAULT_PARITY;
            cfg->stopbits = RS485_DEFAULT_STOPBITS;
            cfg->addr = RS485_DEFAULT_ADDR;
            return;
        }
    }
}

void rs485_init(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    DMA_InitTypeDef  DMA_InitStructure;
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    /* init struct data */
    file_config_get(&file_config);
    rs485_data.baudrate = file_config.baudrate;
    rs485_data.parity = file_config.parity;
    rs485_data.stopbits = file_config.stopbits;
    rs485_data.addr = file_config.addr;
    rs485_data.rx_len = 0;
    rs485_data.tx_len = 0;
    rs485_data.buff_rx = rs485_buff_rx;
    rs485_data.buff_tx = rs485_buff_tx;
    rs485_data.frame_cnt = 0;

    /* config modbus direction pin */
    GPIO_InitStructure.GPIO_Pin = RS485_PIN_DIR,
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT,
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP,
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz,
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL,
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
    GPIO_Init(RS485_PORT, &GPIO_InitStructure);
    rs485_mode_rx();

    /* config rs485 uart pin */
    GPIO_PinAFConfig(RS485_PORT, GPIO_PinSource9, GPIO_AF_USART1);
    GPIO_PinAFConfig(RS485_PORT, GPIO_PinSource10, GPIO_AF_USART1);
    GPIO_InitStructure.GPIO_Pin = RS485_PIN_TX | RS485_PIN_RX;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(RS485_PORT, &GPIO_InitStructure);
    /* config rs485 uart function */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
    USART_DeInit(USART1);
    USART_OverSampling8Cmd(USART1, ENABLE);
    USART_InitStructure.USART_BaudRate = rs485_data.baudrate;
    /* When using Parity the word length must be configured to 9 bits */
    if (rs485_data.parity == RS485_PARITY_ODD) {
        USART_InitStructure.USART_WordLength = USART_WordLength_9b;
        USART_InitStructure.USART_Parity = USART_Parity_Odd;
    } else if (rs485_data.parity == RS485_PARITY_EVEN) {
        USART_InitStructure.USART_WordLength = USART_WordLength_9b;
        USART_InitStructure.USART_Parity = USART_Parity_Even;
    } else {
        USART_InitStructure.USART_WordLength = USART_WordLength_8b;
        USART_InitStructure.USART_Parity = USART_Parity_No;
    }
    if (rs485_data.stopbits == 2) {
        USART_InitStructure.USART_StopBits = USART_StopBits_2;
    } else {
        USART_InitStructure.USART_StopBits = USART_StopBits_1;
    }
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);
    USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE);
    USART_Cmd(USART1, ENABLE);
    /* Configure DMA controller to manage USART TX request */ 
    DMA_InitStructure.DMA_BufferSize = RS485_BUFF_TX_LEN;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_PeripheralBaseAddr =(uint32_t)(&(USART1->DR));
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_InitStructure.DMA_Channel = DMA_Channel_4;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)rs485_buff_tx;
    DMA_Init(DMA2_Stream7, &DMA_InitStructure);
    /* Configure interrupt for USART1 RX */
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
    USART_ITConfig(USART1, USART_IT_TC, ENABLE);

    /* config TIM4 for modbus recv timeout, 3.5 frame time */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
    if (rs485_data.baudrate >= 19200) {
        TIM_TimeBaseStructure.TIM_Period = 1750;
    } else {
        TIM_TimeBaseStructure.TIM_Period = 1000 * 1000 * 35 / rs485_data.baudrate;
    }
    TIM_TimeBaseStructure.TIM_Prescaler = 84 - 1;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
    /* Prescaler configuration */
    TIM_PrescalerConfig(TIM4, 84 - 1, TIM_PSCReloadMode_Immediate);
    /* TIM4 disable counter, start after reciving every uart data */
    TIM_Cmd(TIM4, DISABLE);
    TIM_ITConfig(TIM4, TIM_IT_Update, DISABLE);
    NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

void rs485_timer_restart(void)
{
    TIM_ITConfig(TIM4, TIM_IT_Update, DISABLE);
    TIM_SetCounter(TIM4, 0);
    TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
    TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
    TIM_Cmd(TIM4, ENABLE);
}

void rs485_timer_stop(void)
{
    TIM_Cmd(TIM4, DISABLE);
    TIM_ITConfig(TIM4, TIM_IT_Update, DISABLE);
    TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
}

void rs485_mode_tx(void)
{
    GPIO_SetBits(RS485_PORT, RS485_PIN_DIR);
}

void rs485_mode_rx(void)
{
    GPIO_ResetBits(RS485_PORT, RS485_PIN_DIR);
}

void rs485_rx_start(void)
{
    /* clear PE, FE, NE, ORE and IDLE flags, reference USART_ClearFlag function */
    USART_GetITStatus(USART1, USART_IT_RXNE);
    USART_ReceiveData(USART1);
    USART_ClearFlag(USART1, USART_FLAG_RXNE);
    /* enable USART receive interrupt */
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}

void rs485_rx_stop(void)
{
    USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
    USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}

void rs485_send_data(uint16_t len)
{
    rs485_mode_tx();
    DMA_SetCurrDataCounter(DMA2_Stream7, len);
    USART_ClearITPendingBit(USART1, USART_IT_TC);
    DMA_Cmd(DMA2_Stream7, ENABLE);
}

void USART1_IRQHandler(void)
{
    if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
        rs485_timer_restart();
        if (rs485_data.rx_len < RS485_BUFF_RX_LEN) {
            rs485_buff_rx[rs485_data.rx_len++] = USART_ReceiveData(USART1);
        } else {
            /* exception, has recevered too much data, drop */
            rs485_data.rx_len = 0;
        }
    }
    /* one tx frame complete */
    if (USART_GetITStatus(USART1, USART_IT_TC) != RESET) {
        USART_ClearITPendingBit(USART1, USART_IT_TC);
        DMA_ClearFlag(DMA2_Stream7, DMA_FLAG_TCIF7);
        rs485_data.rx_len = 0;
        rs485_mode_rx();
        rs485_rx_start();
    }
}

void TIM4_IRQHandler(void)
{
    rs485_timer_stop();
    if (rs485_data.buff_rx[0] == rs485_data.addr && rs485_data.rx_len > 3) {
        /* one completed frame, need processing */
        rs485_rx_stop();
        rs485_data.frame_cnt++;
    } else {
        /* address not match, drop */
        rs485_data.rx_len = 0;
    }
}
