/*
 * 02_flash_read_write_erase.c
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 *
 * Copyright (c) 2026 Georgy Moshkin <https://georgymoshkin.com>
 * All rights reserved.
 *
 */

#include "examples.h"

#ifdef EXAMPLE_02_FLASH_READ_WRITE_ERASE

#ifndef SRC_01_FLASH_READ_WRITE_ERASE_C_
#define SRC_01_FLASH_READ_WRITE_ERASE_C_


#define UART_BUFFER_SIZE 64
__IO uint8_t uartBuffer[UART_BUFFER_SIZE];	// DMA buffer for serial port RX
uint8_t cmdByte; 							// Temporary TX/RX byte variable

void app_boot()
{
	// implement boot logic here
}

void app_init(UART_HandleTypeDef *huartPtr)
{
	// Initialize universal serial port library (uart.h, uart.c)
	COM_Init(0,					// Port number
			huartPtr,			// HAL port handle
			uartBuffer,			// RX buffer array
			UART_BUFFER_SIZE);	// RX buffer size
}


void app_loop()
{
	if (COM_ReadFast(&cmdByte, 1))
		switch(cmdByte)
		{

			// Command 0x01: Read Flash
			case 0x01:
			{
				uint8_t bytes[32];
				flash_region_select(REGION_SETTINGS);
				flash_region_read(bytes);

				// Send response to serial port
				cmdByte=0xA1;
				COM_Write(&cmdByte, 1);
				COM_Write(&bytes, 32);
				break;
			}

			// Command 0x02: Write Flash
			case 0x02:
			{
				uint8_t bytes[32];
				if (COM_Read(&bytes,32))
				{
					flash_region_select(REGION_SETTINGS);
					flash_region_write(&bytes);

					// Send response to serial port
					cmdByte=0xA2;
					COM_Write(&cmdByte,1);
				}

				break;
			}

			// Command 0x03: Erase Flash
			case 0x03:
			{
				flash_region_erase_and_select(REGION_SETTINGS);

				// Send response to serial port
				cmdByte=0xA3;
				COM_Write(&cmdByte, 1);

				break;
			}

		}

}


#endif /* SRC_01_FLASH_READ_WRITE_ERASE_C_ */
#endif /* EXAMPLE_02_FLASH_READ_WRITE_ERASE */
