#include "main.h"
#include "lcd.h"
#include "24AA02E48.h"

extern I2C_HandleTypeDef hi2c1;

void EEPROM_24AA02E48_run_test(void)
{
	DISPLAY_CLEAR;
	display_write_data_seq("24AA02E48 EEPROM");

	HAL_StatusTypeDef op_result;
	size_t err_count = 0;

	// write the Address Pointer register
	uint8_t data_buffer[13];
	data_buffer[12] = '\0';
	data_buffer[0] = 0xF4;

	for (size_t t = 0; t < 5; t++) {
		op_result = HAL_I2C_Master_Transmit(&hi2c1, 0xA0, data_buffer, 1, 2000);

		if (op_result) {
			err_count++;

			DISPLAY_CLEAR;
			display_write_data_seq("24AA02E48 EEPROM");

			DISPLAY_SET_CURSOR(1, 0);
			display_write_data_seq("W ");
			display_write_data_byte('1' + t);
			display_write_data_seq("/5 ");

			switch (op_result) {
			case HAL_OK:
				break;
			case HAL_ERROR:
				display_write_data_seq("ERROR");
				break;
			case HAL_BUSY:
				display_write_data_seq("BUSY");
				break;
			case HAL_TIMEOUT:
				display_write_data_seq("TIMEOUT");
				break;
			}

			HAL_Delay(2000);
		} else {
			break;
		}
	}

	for (size_t t = 0; t < 5; t++) {
		op_result = HAL_I2C_Master_Receive(&hi2c1, 0xA1, data_buffer, 12, 2000);

		if (op_result) {
			err_count++;

			DISPLAY_CLEAR;
			display_write_data_seq("24AA02E48 EEPROM");

			DISPLAY_SET_CURSOR(1, 0);
			display_write_data_seq("R ");
			display_write_data_byte('1' + t);
			display_write_data_seq("/5 ");

			switch (op_result) {
			case HAL_OK:
				break;
			case HAL_ERROR:
				display_write_data_seq("ERROR");
				break;
			case HAL_BUSY:
				display_write_data_seq("BUSY");
				break;
			case HAL_TIMEOUT:
				display_write_data_seq("TIMEOUT");
				break;
			}

			HAL_Delay(2000);
		} else {
			break;
		}
	}

	DISPLAY_CLEAR;
	display_write_data_seq("24AA02E48 EEPROM");

	if (err_count) {
		DISPLAY_SET_CURSOR(1, 0);
		display_write_data_byte('0' + err_count / 10 % 10);
		display_write_data_byte('0' + err_count % 10);
		display_write_data_seq("E ");
		display_write_data_seq((char *) data_buffer);
	} else {
		DISPLAY_SET_CURSOR(1, 1);
		display_write_data_seq("OK ");
		display_write_data_seq((char *) data_buffer);
	}
}
