/*********************************************************************************************************************
* TC264 Opensourec Library TC264 Դ⣩һڹٷ SDK ӿڵĵԴ
* Copyright (c) 2022 SEEKFREE ɿƼ
*
* ļ TC264 Դһ
*
* TC264 Դ 
* Ըᷢ GPLGNU General Public License GNUͨù֤
*  GPL ĵ3棨 GPL3.0ѡģκκİ汾·/޸
*
* Դķϣܷãδκεı֤
* ûԻʺض;ı֤
* ϸμ GPL
*
* ӦյԴͬʱյһ GPL ĸ
* ûУ<https://www.gnu.org/licenses/>
*
* ע
* Դʹ GPL3.0 Դ֤Э Ϊİ汾
* Ӣİ libraries/doc ļµ GPL3_permission_statement.txt ļ
* ֤ libraries ļ ļµ LICENSE ļ
* ӭλʹò ޸ʱ뱣ɿƼİȨ
*
* ļ          zf_device_mt9v03x
* ˾          ɶɿƼ޹˾
* 汾Ϣ          鿴 libraries/doc ļ version ļ 汾˵
*           ADS v1.9.4
* ƽ̨          TC264D
*           https://seekfree.taobao.com/
*
* ޸ļ¼
*                               ע
* 2022-09-15       pudding            first version
* 2023-04-28       pudding            ע˵
********************************************************************************************************************/
/*********************************************************************************************************************
* ߶壺
*                  ------------------------------------
*                  ģܽ             Ƭܽ
*                  TXD                鿴 zf_device_mt9v03x.h  MT9V03X_COF_UART_TX 궨
*                  RXD                鿴 zf_device_mt9v03x.h  MT9V03X_COF_UART_RX 궨
*                  PCLK               鿴 zf_device_mt9v03x.h  MT9V03X_PCLK_PIN 궨
*                  VSY                鿴 zf_device_mt9v03x.h  MT9V03X_VSYNC_PIN 궨
*                  D0-D7              鿴 zf_device_mt9v03x.h  MT9V03X_DATA_PIN 궨 Ӹö忪ʼ˸
*                  VCC                3.3VԴ
*                  GND                Դ
*                  
*                  ------------------------------------
********************************************************************************************************************/

#include "zf_common_interrupt.h"
#include "zf_common_debug.h"
#include "zf_common_fifo.h"
#include "zf_driver_soft_iic.h"
#include "zf_driver_delay.h"
#include "zf_driver_dma.h"
#include "zf_driver_exti.h"
#include "zf_driver_gpio.h"
#include "zf_driver_uart.h"
#include "zf_device_camera.h"
#include "zf_device_config.h"
#include "zf_device_mt9v03x.h"

vuint8  mt9v03x_finish_flag = 0;                            // һͼɼɱ־λ
IFX_ALIGN(4) uint8  mt9v03x_image[MT9V03X_H][MT9V03X_W];    // 4ֽڶ

static  m9v03x_type_enum mt9v03x_type;                      // ͷ
static  uint16    mt9v03x_version = 0x00;                   // ͷ汾


int16   timeout = MT9V03X_INIT_TIMEOUT;                     // 峬ʱʱ

uint8   mt9v03x_lost_flag = 1;                              // ͼʧ־λ
uint8   mt9v03x_dma_int_num;                                // ǰDMAжϴ
uint8   mt9v03x_dma_init_flag;                              // ǷҪ³ʼ
uint8   mt9v03x_link_list_num;

// Ҫõͷ ޸Ĳ
static int16 mt9v03x_set_confing_buffer[MT9V03X_CONFIG_FINISH][2]=
{
    {MT9V03X_INIT,              0},                                             // ͷʼʼ
    {MT9V03X_AUTO_EXP,          MT9V03X_AUTO_EXP_DEF},                          // Զع   Χ1-63 0Ϊر Զع⿪  EXP_TIMEõݽΪعʱ䣬ҲԶعʱ
    {MT9V03X_EXP_TIME,          MT9V03X_EXP_TIME_DEF},                          // عʱ      ͷյԶعʱ䣬ùΪعֵ
    {MT9V03X_FPS,               MT9V03X_FPS_DEF},                               // ͼ֡      ͷյԶFPSΪFPS
    {MT9V03X_SET_COL,           MT9V03X_W},                                     // ͼ    Χ1-752
    {MT9V03X_SET_ROW,           MT9V03X_H},                                     // ͼ    Χ1-480
    {MT9V03X_LR_OFFSET,         MT9V03X_LR_OFFSET_DEF},                         // ͼƫ  ֵ ƫ   ֵ ƫ  Ϊ188 376 752ʱ޷ƫ    ͷƫݺԶƫƣüƫ
    {MT9V03X_UD_OFFSET,         MT9V03X_UD_OFFSET_DEF},                         // ͼƫ  ֵ ƫ   ֵ ƫ  Ϊ120 240 480ʱ޷ƫ    ͷƫݺԶƫƣüƫ
    {MT9V03X_GAIN,              MT9V03X_GAIN_DEF},                              // ͼ      Χ16-64     عʱ̶¸ıͼ̶
    {MT9V03X_PCLK_MODE,         MT9V03X_PCLK_MODE_DEF},                         // ʱģʽ   MT9V034 V2.0Լϰ汾ָ֧
};

// ͷڲȡ ޸Ĳ
static int16 mt9v03x_get_confing_buffer[MT9V03X_CONFIG_FINISH - 1][2]=
{
    {MT9V03X_AUTO_EXP,          0},                                             // Զع
    {MT9V03X_EXP_TIME,          0},                                             // عʱ
    {MT9V03X_FPS,               0},                                             // ͼ֡
    {MT9V03X_SET_COL,           0},                                             // ͼ
    {MT9V03X_SET_ROW,           0},                                             // ͼ
    {MT9V03X_LR_OFFSET,         0},                                             // ͼƫ
    {MT9V03X_UD_OFFSET,         0},                                             // ͼƫ
    {MT9V03X_GAIN,              0},                                             // ͼ
    {MT9V03X_PCLK_MODE,         0},                                             // ʱģʽ PCLKģʽ <  MT9V034 V1.5 Լϰ汾ָ֧ >
};

//-------------------------------------------------------------------------------------------------------------------
//      ͷڲϢ
// ˵     buff            Ϣĵַ
// ز     uint8           1-ʧ 0-ɹ
// ʹʾ     mt9v03x_set_config(mt9v03x_set_confing_buffer);
// עϢ     ڲ
//-------------------------------------------------------------------------------------------------------------------
static uint8 mt9v03x_set_config (int16 buff[MT9V03X_CONFIG_FINISH][2])
{
    uint8 return_state = 1;
    uint8  uart_buffer[4];
    uint16 temp = 0;
    uint16 timeout_count = 0;
    uint32 loop_count = 0;
    uint32 uart_buffer_index = 0;

    switch(mt9v03x_version)
    {
        case 0x0230:    loop_count = MT9V03X_PCLK_MODE;  break;
        default:        loop_count = MT9V03X_GAIN;       break;
    }
    // ò  οֲ
    // ʼͷ³ʼ
    for(; MT9V03X_SET_DATA > loop_count; loop_count --)
    {
        uart_buffer[0] = 0xA5;
        uart_buffer[1] = (uint8)buff[loop_count][0];
        temp = buff[loop_count][1];
        uart_buffer[2] = temp >> 8;
        uart_buffer[3] = (uint8)temp;
        uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

        system_delay_ms(2);
    }

    do
    {
        if(3 <= fifo_used(&camera_receiver_fifo))
        {
            uart_buffer_index = 3;
            fifo_read_buffer(&camera_receiver_fifo, uart_buffer, &uart_buffer_index, FIFO_READ_AND_CLEAN);
            if((0xff == uart_buffer[1]) || (0xff == uart_buffer[2]))
            {
                return_state = 0;
                break;
            }
        }
        system_delay_ms(1);
    }while(MT9V03X_INIT_TIMEOUT > timeout_count ++);
    // ϲֶͷõȫᱣͷ51Ƭeeprom
    // set_exposure_timeõعݲ洢eeprom
    return return_state;
}

//-------------------------------------------------------------------------------------------------------------------
//      ȡͷڲϢ
// ˵     buff            Ϣĵַ
// ز     uint8           1-ʧ 0-ɹ
// ʹʾ     mt9v03x_get_config(mt9v03x_get_confing_buffer);
// עϢ     ڲ
//-------------------------------------------------------------------------------------------------------------------
static uint8 mt9v03x_get_config (int16 buff[MT9V03X_CONFIG_FINISH - 1][2])
{
    uint8 return_state = 0;
    uint8  uart_buffer[4];
    uint16 temp = 0;
    uint16 timeout_count = 0;
    uint32 loop_count = 0;
    uint32 uart_buffer_index = 0;

    switch(mt9v03x_version)
    {
        case 0x0230:    loop_count = MT9V03X_PCLK_MODE;  break;
        default:        loop_count = MT9V03X_GAIN;       break;
    }

    for(loop_count = loop_count - 1; 1 <= loop_count; loop_count --)
    {
        if((0x0230 > mt9v03x_version) && (MT9V03X_PCLK_MODE == buff[loop_count][0]))
        {
            continue;
        }
        uart_buffer[0] = 0xA5;
        uart_buffer[1] = MT9V03X_GET_STATUS;
        temp = buff[loop_count][0];
        uart_buffer[2] = temp >> 8;
        uart_buffer[3] = (uint8)temp;
        uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

        timeout_count = 0;    
        do
        {
            if(3 <= fifo_used(&camera_receiver_fifo))
            {
                uart_buffer_index = 3;
                fifo_read_buffer(&camera_receiver_fifo, uart_buffer, &uart_buffer_index, FIFO_READ_AND_CLEAN);
                buff[loop_count][1] = uart_buffer[1] << 8 | uart_buffer[2];
                break;
            }
            system_delay_ms(1);
        }while(MT9V03X_INIT_TIMEOUT > timeout_count ++);
        if(MT9V03X_INIT_TIMEOUT < timeout_count)                                // ʱ
        {
            return_state = 1;
            break;
        }
    }
    return return_state;
}


//-------------------------------------------------------------------------------------------------------------------
//        MT9V03XͷͨŻص
//  ˵      void
//  ز      void
//  ʹʾ      mt9v03x_uart_callback();
//-------------------------------------------------------------------------------------------------------------------
static void mt9v03x_uart_handler (void)
{
    uint8 data = 0;
    uart_query_byte(MT9V03X_COF_UART, &data);
    if(0xA5 == data)
    {
        fifo_clear(&camera_receiver_fifo);
    }
    fifo_write_element(&camera_receiver_fifo, data);
}

//-------------------------------------------------------------------------------------------------------------------
//        MT9V03Xͷж
//  ˵      void
//  ز      void
//  ʹʾ      mt9v03x_vsync_handler();
//-------------------------------------------------------------------------------------------------------------------
static void mt9v03x_vsync_handler(void)
{
    exti_flag_clear(MT9V03X_VSYNC_PIN);
    mt9v03x_dma_int_num = 0;
    if(mt9v03x_dma_init_flag )
    {
        mt9v03x_dma_init_flag = 0;
        IfxDma_resetChannel(&MODULE_DMA, MT9V03X_DMA_CH);
        mt9v03x_link_list_num = dma_init(MT9V03X_DMA_CH,
                                         MT9V03X_DATA_ADD,
                                         mt9v03x_image[0],
                                         MT9V03X_PCLK_PIN,
                                         EXTI_TRIGGER_RISING,
                                         MT9V03X_IMAGE_SIZE);           // Ƶ300M ڶΪFALLING
        dma_enable(MT9V03X_DMA_CH);
    }
    else
    {
        if(1 == mt9v03x_link_list_num)
        {
            dma_set_destination(MT9V03X_DMA_CH, mt9v03x_image[0]);      // ûвӴģʽ Ŀĵַ
        }
        dma_enable(MT9V03X_DMA_CH);
    }
    mt9v03x_lost_flag = 1;
}

//-------------------------------------------------------------------------------------------------------------------
//        MT9V03XͷDMAж
//  ˵      void
//  ز      void
//  ʹʾ      mt9v03x_dma_handler();
//-------------------------------------------------------------------------------------------------------------------
static void mt9v03x_dma_handler(void)
{
    clear_dma_flag(MT9V03X_DMA_CH);

    if(IfxDma_getChannelTransactionRequestLost(&MODULE_DMA, MT9V03X_DMA_CH)) // ͼλж
    {
        mt9v03x_finish_flag = 0;
        dma_disable(MT9V03X_DMA_CH);
        IfxDma_clearChannelTransactionRequestLost(&MODULE_DMA, MT9V03X_DMA_CH);
        mt9v03x_dma_init_flag = 1;
    }
    else
    {
        mt9v03x_dma_int_num++;
        if(mt9v03x_dma_int_num >= mt9v03x_link_list_num)
        {
            // ɼ
            // һͼӲɼʼɼʱ3.8MS(50FPS188*120ֱ)
            mt9v03x_dma_int_num = 0;
            mt9v03x_lost_flag   = 0;
            mt9v03x_finish_flag = 1;
            dma_disable(MT9V03X_DMA_CH);
        }
    }
}

//-------------------------------------------------------------------------------------------------------------------
//      ȡͷ̼汾
// ˵     void
// ز     uint16          0-ȡ N-汾
// ʹʾ     mt9v03x_get_version();                          // øúǰȳʼ
// עϢ
//-------------------------------------------------------------------------------------------------------------------
uint16 mt9v03x_get_version (void)
{
    uint16 temp;
    uint8  uart_buffer[4];
    uint16 timeout_count = 0;
    uint16 return_value = 0;
    uint32 uart_buffer_index = 0;

    uart_buffer[0] = 0xA5;
    uart_buffer[1] = MT9V03X_GET_STATUS;
    temp = MT9V03X_GET_VERSION;
    uart_buffer[2] = temp >> 8;
    uart_buffer[3] = (uint8)temp;
    uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

    do
    {
        if(3 <= fifo_used(&camera_receiver_fifo))
        {
            uart_buffer_index = 3;
            fifo_read_buffer(&camera_receiver_fifo, uart_buffer, &uart_buffer_index, FIFO_READ_AND_CLEAN);
            return_value = uart_buffer[1] << 8 | uart_buffer[2];
            break;
        }
        system_delay_ms(1);
    }while(MT9V03X_INIT_TIMEOUT > timeout_count ++);
    return return_value;
}

//-------------------------------------------------------------------------------------------------------------------
//      ͷعʱ
// ˵     light           趨عʱ
// ز     uint8           1-ʧ 0-ɹ
// ʹʾ     mt9v03x_set_exposure_time(100);                 // øúǰȳʼ
// עϢ     عʱԽͼԽ
//              ͷյݷֱʼFPSعʱõݹ
//              ôͷֵ
//-------------------------------------------------------------------------------------------------------------------
uint8 mt9v03x_set_exposure_time (uint16 light)
{
    uint8 return_state = 0;
    if(MT9V03X_UART == mt9v03x_type)
    {
        set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, mt9v03x_uart_handler);
        uint8  uart_buffer[4];
        uint16 temp = 0;
        uint16 timeout_count = 0;
        uint32 uart_buffer_index = 0;

        uart_buffer[0] = 0xA5;
        uart_buffer[1] = MT9V03X_SET_EXP_TIME;
        temp = light;
        uart_buffer[2] = temp >> 8;
        uart_buffer[3] = (uint8)temp;
        uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

        do
        {
            if(3 <= fifo_used(&camera_receiver_fifo))
            {
                uart_buffer_index = 3;
                fifo_read_buffer(&camera_receiver_fifo, uart_buffer, &uart_buffer_index, FIFO_READ_AND_CLEAN);
                temp = uart_buffer[1] << 8 | uart_buffer[2];
                break;
            }
            system_delay_ms(1);
        }while(MT9V03X_INIT_TIMEOUT > timeout_count ++);
        if((temp != light) || (MT9V03X_INIT_TIMEOUT <= timeout_count))
        {
            return_state = 1;
        }
        set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, NULL);
    }
    else
    {
        return_state = mt9v03x_set_exposure_time_sccb(light);
    }
    return return_state;
}

//-------------------------------------------------------------------------------------------------------------------
//      ͷڲĴд
// ˵     addr            ͷڲĴַ
// ˵     data            Ҫд
// ز     uint8           1-ʧ 0-ɹ
// ʹʾ     mt9v03x_set_reg(addr, data);                    // øúǰȳʼ
// עϢ
//-------------------------------------------------------------------------------------------------------------------
uint8 mt9v03x_set_reg (uint8 addr, uint16 data)
{
    uint8 return_state = 0;
    if(MT9V03X_UART == mt9v03x_type)
    {
        set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, mt9v03x_uart_handler);
        uint8  uart_buffer[4];
        uint16 temp = 0;
        uint16 timeout_count = 0;
        uint32 uart_buffer_index = 0;

        uart_buffer[0] = 0xA5;
        uart_buffer[1] = MT9V03X_SET_ADDR;
        temp = addr;
        uart_buffer[2] = temp >> 8;
        uart_buffer[3] = (uint8)temp;
        uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

        system_delay_ms(10);
        uart_buffer[0] = 0xA5;
        uart_buffer[1] = MT9V03X_SET_DATA;
        temp = data;
        uart_buffer[2] = temp >> 8;
        uart_buffer[3] = (uint8)temp;
        uart_write_buffer(MT9V03X_COF_UART, uart_buffer, 4);

        do
        {
            if(3 <= fifo_used(&camera_receiver_fifo))
            {
                uart_buffer_index = 3;
                fifo_read_buffer(&camera_receiver_fifo, uart_buffer, &uart_buffer_index, FIFO_READ_AND_CLEAN);
                temp = uart_buffer[1] << 8 | uart_buffer[2];
                break;
            }
            system_delay_ms(1);
        }while(MT9V03X_INIT_TIMEOUT > timeout_count ++);
        if((temp != data) || (MT9V03X_INIT_TIMEOUT <= timeout_count))
        {
            return_state = 1;
        }
        set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, NULL);
    }
    else
    {
        return_state = mt9v03x_set_reg_sccb(addr, data);
    }
    return return_state;
}

//-------------------------------------------------------------------------------------------------------------------
//      MT9V03X ͷʼ
// ˵     void
// ز     uint8           1-ʧ 0-ɹ
// ʹʾ     zf_log(mt9v03x_init(), "mt9v03x init error");
// עϢ
//-------------------------------------------------------------------------------------------------------------------
uint8 mt9v03x_init (void)
{
    uint8 return_state = 0;
    soft_iic_info_struct mt9v03x_iic_struct;
    do
    {
        system_delay_ms(200);
        // ȳSCCBͨѶ
        mt9v03x_type = MT9V03X_SCCB;
        set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, NULL);
        soft_iic_init(&mt9v03x_iic_struct, 0, MT9V03X_COF_IIC_DELAY, MT9V03X_COF_IIC_SCL, MT9V03X_COF_IIC_SDA);
        if(mt9v03x_set_config_sccb(&mt9v03x_iic_struct, mt9v03x_set_confing_buffer))
        {
            // SCCBͨѶʧܣԴͨѶ
            mt9v03x_type = MT9V03X_UART;
            set_camera_type(CAMERA_GRAYSCALE, mt9v03x_vsync_handler, mt9v03x_dma_handler, mt9v03x_uart_handler);
            camera_fifo_init();

            // ʼ ͷ
            uart_init(MT9V03X_COF_UART, MT9V03X_COF_BAUR, MT9V03X_COF_UART_RX, MT9V03X_COF_UART_TX);
            uart_rx_interrupt(MT9V03X_COF_UART, 1);
            fifo_clear(&camera_receiver_fifo);
            // ȴͷϵʼɹ ʽ֣ʱͨȡõķʽ ѡһ
            // system_delay_ms(1000);                                               // ʱʽ

            // if(mt9v03x_get_config(mt9v03x_get_confing_buffer))
            // {
            //     // ˶Ϣ ʾλ
            //     // ôǴͨųʱ˳
            //     // һ½û ûܾǻ
            //     zf_log(0, "MT9V03X get config error.");
            //     set_camera_type(NO_CAMERE, NULL, NULL, NULL);
            //     return_state = 1;
            //     break;
            // }
            mt9v03x_version = mt9v03x_get_version();                                // ȡõķʽ

            if(mt9v03x_set_config(mt9v03x_set_confing_buffer))
            {
                // ˶Ϣ ʾλ
                // ôǴͨųʱ˳
                // һ½û ûܾǻ
                zf_log(0, "MT9V03X set config error.");
                uart_rx_interrupt(MT9V03X_COF_UART, 0);
                set_camera_type(NO_CAMERE, NULL, NULL, NULL);
                return_state = 1;
                break;
            }

            // ȡñڲ鿴Ƿȷ
            if(mt9v03x_get_config(mt9v03x_get_confing_buffer))
            {
                // ˶Ϣ ʾλ
                // ôǴͨųʱ˳
                // һ½û ûܾǻ
                zf_log(0, "MT9V03X get config error.");
                uart_rx_interrupt(MT9V03X_COF_UART, 0);
                set_camera_type(NO_CAMERE, NULL, NULL, NULL);
                return_state = 1;
                break;
            }
        }
        mt9v03x_link_list_num = camera_init(MT9V03X_DATA_ADD, mt9v03x_image[0], MT9V03X_IMAGE_SIZE);
    }while(0);
    return return_state;
}

