/* Reflow Oven Controller
 *
 * Copyright (C) 2020  Mario Hüttel <mario.huettel@gmx.net>
 *
 * This file is part of the Reflow Oven Controller Project.
 *
 * The reflow oven controller is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * The Reflow Oven Control Firmware is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the reflow oven controller project.
 * If not, see <http://www.gnu.org/licenses/>.
 */

#include <stm-periph/rng.h>
#include <stm-periph/rcc-manager.h>
#include <stm32/stm32f4xx.h>

void random_number_gen_init(bool int_enable)
{
	rcc_manager_enable_clock(&RCC->AHB2ENR, BITMASK_TO_BITNO(RCC_AHB2ENR_RNGEN));
	__DSB();

	random_number_gen_reset(int_enable);
}

void random_number_gen_deinit()
{
	RNG->CR = 0;
	__DSB();
	rcc_manager_disable_clock(&RCC->AHB2ENR, BITMASK_TO_BITNO(RCC_AHB2ENR_RNGEN));
}

void random_number_gen_reset(bool int_en)
{
	RNG->CR = 0;
	__DSB();
	RNG->CR = RNG_CR_RNGEN | (int_en ? RNG_CR_IE : 0U);
}

enum random_number_error random_number_gen_get_number(uint32_t *random_number, bool wait_for_valid_value)
{
	bool value_ready;

	if (!(RNG->CR & RNG_CR_RNGEN))
		return RNG_ERROR_INACT;

	if (RNG->SR & RNG_SR_SEIS || RNG->SR & RNG_SR_CEIS) {
		/* Error detected */
		return RNG_ERROR_INTERNAL_ERROR;
	}

	/* Check if the value is ready. Wait if wait_for_valid_value is true */
	do {
		value_ready = !!(RNG->SR & RNG_SR_DRDY);
	} while (!value_ready && wait_for_valid_value);

	/* If the value is valid, return it */
	if (value_ready && random_number)
		*random_number = RNG->DR;

	/* Return from function with proper status */
	return (value_ready ? RNG_ERROR_OK : RNG_ERROR_NOT_READY);
}
