#include "memory.h"
#include "main.h"
#include "MP45DT02.h"
#include "lcd.h"

#define SAMPLE_AMOUNT 256

extern I2S_HandleTypeDef hi2s2;

void MP45DT02_run_test(void)
{
	DISPLAY_CLEAR;
	display_write_data_seq("MP45DT02 Mic");

	uint16_t sample_buffer[SAMPLE_AMOUNT];

	memset(sample_buffer, 0, 2 * SAMPLE_AMOUNT);

	for (size_t t = 0; t < 5; t++) {
		HAL_I2S_Receive(&hi2s2, sample_buffer, SAMPLE_AMOUNT, 1000);

		for (size_t i = 0; i < SAMPLE_AMOUNT / 2; i++)
			if (((uint32_t *) sample_buffer)[i]) {
				DISPLAY_CLEAR;
				display_write_data_seq("MP45DT02 Mic");

				if (!t) {
					DISPLAY_SET_CURSOR(1, 1);
					display_write_data_seq("OK");
				} else {
					DISPLAY_SET_CURSOR(1, 0);
					display_write_data_byte('0' + t);
					display_write_data_seq(" full 0 samples");
				}

				return;
			}

		// if ended up here, then no samples equaled to 1; that is not a good sign
		DISPLAY_CLEAR;
		display_write_data_seq("MP45DT02 Mic");

		DISPLAY_SET_CURSOR(1, 0);
		display_write_data_byte('1' + t);
		display_write_data_seq("/5: no 1 sampled");

		HAL_Delay(1000);
	}

	// t = 5, not a single 1 was recorded; microphone might be broken
	DISPLAY_CLEAR;
	display_write_data_seq("MP45DT02 Mic");

	DISPLAY_SET_CURSOR(1, 0);
	display_write_data_seq("No good samples!");
}