#include <reflow-controller/hw-version-detect.h>
#include <stm-periph/rcc-manager.h>
#include <stm32/stm32f4xx.h>

#define HW_REV_DETECT_GPIO GPIOE
#define HW_REV_DETECT_RCC_FIELD RCC_AHB1ENR_GPIOEEN
#define HW_REV_DETECT_PIN_LOW (8U)
#define HW_REV_DETECT_PIN_HIGH (15U)

enum hw_revision get_pcb_hardware_version(void)
{
	uint8_t current_pin;
	uint16_t port_bitmask = 0U;
	static enum hw_revision revision = HW_REV_NOT_DETECTED;

	if (revision != HW_REV_NOT_DETECTED)
		return revision;

	rcc_manager_enable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(HW_REV_DETECT_RCC_FIELD));

	/* Setup the pins as input with pull up */
	for (current_pin = HW_REV_DETECT_PIN_LOW; current_pin <= HW_REV_DETECT_PIN_HIGH; current_pin++) {
		HW_REV_DETECT_GPIO->MODER &= MODER_DELETE(current_pin);
		HW_REV_DETECT_GPIO->PUPDR &= PUPDR_DELETE(current_pin);
		HW_REV_DETECT_GPIO->PUPDR |= PULLUP(current_pin);
	}

	/* Loop again and read in the pin mask */
	for (current_pin = HW_REV_DETECT_PIN_LOW; current_pin <= HW_REV_DETECT_PIN_HIGH; current_pin++) {
		port_bitmask >>= 1;
		port_bitmask |= (HW_REV_DETECT_GPIO->IDR & (1 << current_pin)) ? 0x0 : 0x80;
	}

	switch (port_bitmask) {
	case 0U:
		revision = HW_REV_V1_2;
		break;
	case 1U:
		revision = HW_REV_V1_3;
		break;
	default:
		revision = HW_REV_ERROR;
	}

	rcc_manager_disable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(HW_REV_DETECT_RCC_FIELD));

	return revision;
}
