#include <cstdio>
#include <hal/drivers/flash.h>
#include <hal/devices.h>
#include <hal/drivers/dac.h>

int cmd_voltage(int argc, char *argv[])
{
	if (argc != 2)
	{
		printf("%s: error, syntax: ADDRESS %s VOLTAGE\n\n", argv[0], argv[0]);
	}
	else
	{
		dac_file dac;
		dac.voltage = -1;

		sscanf(argv[1], "%f", &dac.voltage);

		if (dac.voltage <= configure_file.max_voltage && dac.voltage >= configure_file.min_voltage)
		{
			flash_file * p_flash_file;

			fseek(p_dac, (int) (&dac.voltage) - (int) (&dac), SEEK_SET);
			fwrite(&dac.voltage, sizeof(dac_file::voltage), 1, p_dac);
			fflush(p_dac);

			decltype(p_flash_file->voltage) voltage = dac.voltage;
			fseek(p_flash, (int) (&p_flash_file->voltage) - (int) (p_flash_file), SEEK_SET);
			fwrite(&voltage, sizeof(flash_file::voltage), 1, p_flash);
			fflush(p_flash);

			printf("%s: the voltage is set to: %fV\n\n", argv[0], dac.voltage);
		}
		else
		{
			printf("%s: error, voltage input: %s is not in range: %f~%f\n\n", argv[0], argv[1], configure_file.min_voltage,
			    configure_file.max_voltage);
		}
	}

	fflush(stdout);
}
