/*
 * bsp_TFT.c
 *
 *  Created on: 2025年4月9日
 *      Author: 22332
 */
#include "cola_init.h"
#include "cola_device.h"
#include "drv_master_iic.h"
#include "bsp_register_map.h"
#include <stdio.h>
#include <stdlib.h>

#define I2C_TX_BUFFER_LENGTH                   (5U)
#define I2C_RX_BUFFER_LENGTH                   (5U)

static cola_device_t g_tft_iic;
static uint8_t slave_address = RM5T500A_Slave_Address;

uint32_t merge_four_bytes(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
{
    return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
}


// 记录合并后数据中1的位置
int* record_one_positions(uint32_t merged_data, int* size)
{
    int max_positions = 32; // 32位数据中最多有32个1
    int* positions = (int*)malloc(max_positions * sizeof(int));
    if (positions == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return NULL;
    }
    *size = 0; // 初始化记录位置的数组大小

    for (int i = 0; i < 32; i++) {
        if (merged_data & (1 << i)) {
            positions[*size] = i;
            (*size)++;
        }
    }

    return positions;
}

static int bsp_iic_tft_read(cola_device_t *dev, int pos,void *buffer, int size)
{
	bool bACK = false;
	#if 0
    uint8_t *transmitBuffer = (uint8_t *)buffer;
    // 从I2C总线接收数据
    bsp_ctrl_read_polling(slave_address,transmitBuffer, size);

    // 将接收到的数据合并到一块并检查错误位置
   uint32_t merged_data = merge_four_bytes(transmitBuffer[0],transmitBuffer[1], transmitBuffer[2], transmitBuffer[3]);

    int Size;
    int* positions = record_one_positions(merged_data, &Size);
    buffer = positions;
    if (positions != NULL)
    {
        printf("Positions of is: ");
        for (int i = 0; i < Size; i++)
        {
           printf("%d ", positions[i]);
        }
        printf("\n");
        free(positions); // 释放分配的内存
    }
    return 0;
	#else
    int bEnPairRead = (pos > 0xFF)?true:false;
    if(bEnPairRead)
    	bACK = bsp_ctrl_read_pair_register(slave_address,pos&0xFFFF,buffer,size);
    else
    	bACK = bsp_ctrl_read_register(slave_address,pos&0xFF,buffer,size);
	return bACK;
	#endif
}

static int  bsp_iic_tft_write(cola_device_t *dev, int pos, const void *buffer, int size)
{
    //uint8_t *transmitBuffer = (uint8_t *)buffer;
   // bsp_ctrl_wirte_polling(slave_address, transmitBuffer, size);
	uint8_t *data = (uint8_t *)buffer;
	uint8_t buf[8];
	if(size > 7)
	size = 7;
	buf[0] = (uint8_t)pos;
	for(int i=0; i<size; i++)
		buf[1+i] = (uint8_t)data[i];
    return bsp_ctrl_write_register(slave_address,buf,1+size);
}


static struct cola_device_ops tft_iic_Ops =
{
    .read   = bsp_iic_tft_read,
    .write  = bsp_iic_tft_write,
};

static void bsp_tft_iic_configuration(void)
{
    g_tft_iic.name = "TFT_IIC";
    g_tft_iic.dops = &tft_iic_Ops;
    cola_device_register(&g_tft_iic);
}
register_initcall(bsp_tft_iic_configuration);


