#include "kit_data.h"
#include "table_comm.h"


//APR-CWFH708~H713 单位为Ω -41~126℃
const uint16_t table_ntc1_CWFH708_H713[BSP_NTC_TABLE_LEN] = 
{
    20250, 20249, 19101, 18030, 17029, 16094, 15219, 14400, 13632, 12911,
    12233, 11597, 10998, 10435,  9904,  9404,  8932,  8487,  8067,  7670,
     7295,  6941,  6605,  6288,  5988,  5704,  5434,  5179,  4938,  4708,
     4491,  4285,  4089,  3904,  3728,  3560,  3402,  3251,  3175,  3035,
     2901,  2774,  2654,  2539,  2430,  2326,  2228,  2134,  2045,  1960,
    18792,  1802,  1728,  1659,  1592,  1529,  1469,  1411,  1356,  1304,
    12545,  1206,  1161,  1118,  1077,  1037,  1000,   962,   926,   892,
      859,   828,   798,   769,   742,   706,   681,   657,   634,   612,
      591,   571,   551,   532,   514,   497,   480,   464,   449,   434,
      420,   407,   393,   381,   369,   357,   345,   335,   324,   314,
      304,   295,   286,   277,   268,   260,   252,   245,   238,   230,
      224,   217,   216,   210,   204,   198,   192,   187,   181,   176,
      171,   166,   162,   157,   153,   149,   145,   141,   137,   133,
      130,   126,   123,   119,   116,   113,   110,   107,   105,   102,
       99,    97,    94,    92,    90,    87,    85,    83,    81,    78,
      765,    74,    72,    69,    67,    65,    62,    60,    58,    56,
      538,    51,    49,    47,    44,    42,    40,    37
};



typedef struct
{
    uint16_t rate;
    const uint16_t *table;
}NtcTable;

NtcTable  ntc_table_list[kNtcType_End] = 
{
    {10,  table_ntc1_CWFH708_H713},
};


uint16_t bms_get_linear_temp(int32_t res, NtcType tab)
{
	int32_t left = -1, right = BSP_NTC_TABLE_LEN, mid;
    uint16_t rate = ntc_table_list[tab].rate;
    
    if(tab >= kNtcType_End)
    {
        tab = kNtcType_CWFH708_H713;
    }
    const uint16_t * table = ntc_table_list[tab].table;
    
	while ((left + 1) != right)
	{
		mid = left + ((right - left) >> 1);
		if (table[mid] * rate > res)
		{
			left = mid;
		}
		else if (table[mid] * rate < res)
		{
			right = mid;
		}
		else
		{
			return mid * 10 - 410 + 500;
		}
	}

	if (left == -1)
	{
		return (uint16_t)KIT_NTC_TEMP_OPEN_VALUE;  //-50度
	}
	else if (right == BSP_NTC_TABLE_LEN)
	{
		return (uint16_t)KIT_NTC_TEMP_SHORT_VALUE; //125度
	}
	else
	{
		left = table[right] * rate - table[right - 1] * rate;
		mid = (res - (int32_t)table[right] * rate + left * right) * 10 / left - 410 + 500;
	}
	return mid;
}

NtcType bms_get_temp_table(NtcType tab, uint8_t *buf)
{
    uint32_t addr = 0;
    
    if(tab >= kNtcType_End)
    {
        tab = kNtcType_CWFH708_H713;
    }
    //长度占位
    WRITE_LT_INT16U(buf, addr, 0);
    WRITE_LT_INT16U(buf, addr, tab);
    WRITE_LT_INT16U(buf, addr, ntc_table_list[tab].rate);
    kit_copy_buf(&buf[6], ntc_table_list[tab].table, BSP_NTC_TABLE_LEN * 2);
    addr += BSP_NTC_TABLE_LEN * 2 + 2;
    WRITE_LT_INT16U_BY_CONST_POS(buf, 0, addr);
    
    kit_append_crc16(buf, addr - 2);
    
    return tab;
}