#include "main.h"
#include "lcd.h"
#include "CS43L22.h"

extern I2C_HandleTypeDef hi2c1;

int CS43L22_run_test(void)
{
	DISPLAY_CLEAR;
	display_write_data_seq("CS43L22 Audio");

	HAL_StatusTypeDef op_result;
	size_t err_count = 0;

	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_4, GPIO_PIN_SET);

	uint8_t data_buffer[2] = {0x0D, 0x01};

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

		if (op_result) {
			err_count++;

			DISPLAY_CLEAR;
			display_write_data_seq("CS43L22 Audio");

			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;
		}
	}

	DISPLAY_CLEAR;
	display_write_data_seq("CS43L22 Audio");

	if (err_count) {
		DISPLAY_SET_CURSOR(1, 1);
		display_write_data_byte('0' + err_count % 10);
		display_write_data_seq(" Errors");

		return 1;
	} else {
		DISPLAY_SET_CURSOR(1, 1);
		display_write_data_seq("OK");

		return 0;
	}
}

void CS43L22_cleanup(void)
{
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_4, GPIO_PIN_RESET);
}
