/*
 * uart.c
 *
 *  Created on: Jul 19, 2024
 *
 */

#include "uart.h"
#include "ES28.h"

#define SYS_FREQ        12000000U   // 12 MHz HSI (HSI48 divided by 4 by default)
#define APB_CLK         SYS_FREQ    // APB bus runs at the same frequency (no prescaler)
#define UART_BAUD_RATE  9600

// Prototypes of static helper functions defined at the bottom of the file.
// Declaring them here lets uart2_init() call them even though they are defined later.
static void uart_set_baudrate(USART_TypeDef *usartx, uint32_t periphClk, uint32_t baudRate);
static uint16_t compute_uart_bd(uint32_t periphClk, uint32_t baudRate);
void uart2_write(int ch);

// -- Retarget layer ----------------------------------------------------------
// __io_putchar is a WEAK symbol in the ARM C library - the linker uses the
// library's built-in (no-op) version unless we supply a stronger definition.
// Defining it here routes all printf output to uart2_write, with no other
// changes to application code.
int __io_putchar(int ch) {
    uart2_write(ch);
    return ch;
}

// -- uart2_init --------------------------------------------------------------
// Configure USART2 for 9600 baud 8N1, with TX on PA2 and RX on PA3.
// Must be called once before uart2_write(), uart2_read(), or printf().
void uart2_init(void) {

    // Step 1: enable the GPIOA clock.
    //   Without this, all GPIOA register writes are silently discarded -
    //   one of the most common "nothing works" bugs.
    RCC->IOPENR |= RCC_IOPENR_GPIOAEN;

    // Step 2: set PA2 (TX) and PA3 (RX) to Alternate Function mode.
    //   The CMSIS macros encode the bit field position, so we do not need
    //   to count bit positions by hand.  Each pin is configured separately.
    //   Each statement reads the register, clears the pin's field, sets the
    //   new value and writes the result back once, so the pin's mode goes
    //   from the old value directly to the new one and never passes through
    //   input mode.
    GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODE2_Msk)
                 | (GPIO_ALTERNATE << GPIO_MODER_MODE2_Pos);  // PA2

    GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODE3_Msk)
                 | (GPIO_ALTERNATE << GPIO_MODER_MODE3_Pos);  // PA3

    // Step 3: select AF1 (USART2) for PA2 and PA3 in the AFRL register.
    //   AFRL covers pins 0-7; each pin has a 4-bit field.
    //   GPIO_AF1 = 1, which maps to USART2 for both PA2 and PA3.
    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~GPIO_AFRL_AFSEL2_Msk)
                  | (GPIO_AF1 << GPIO_AFRL_AFSEL2_Pos);  // PA2 -> USART2 TX

    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~GPIO_AFRL_AFSEL3_Msk)
                  | (GPIO_AF1 << GPIO_AFRL_AFSEL3_Pos);  // PA3 -> USART2 RX

    // Step 4: enable the USART2 clock (RCC_APBENR1).
    //   No USART2 register can be written until its clock is enabled.
    RCC->APBENR1 |= RCC_APBENR1_USART2EN;

    // Step 5: set the baud rate via a helper function.
    //   uart_set_baudrate calls compute_uart_bd, which divides APB_CLK by
    //   UART_BAUD_RATE (with rounding) to produce the value for BRR.
    uart_set_baudrate(USART2, APB_CLK, UART_BAUD_RATE);

    // Step 6: enable the transmitter (TE) and receiver (RE) first,
    //   then enable the USART module (UE) in a separate write.
    //   UE must come after BRR - BRR can only be written while UE = 0, so
    //   with UE set first the BRR write is ignored and BRR stays 0 (its reset value).
    USART2->CR1 = USART_CR1_RE | USART_CR1_TE;
    USART2->CR1 |= USART_CR1_UE;
}

// -- uart2_write -------------------------------------------------------------
// Transmit one byte.  Polls TXE_TXFNF (Transmit Data Register Empty) until
// the hardware shift register is ready, then writes the byte to TDR.
void uart2_write(int ch) {
    while (!(USART2->ISR & USART_ISR_TXE_TXFNF)) {}
    USART2->TDR = (ch & 0xFF);   // mask to 8 bits
}

// -- uart2_read --------------------------------------------------------------
// Receive one byte.  Polls RXNE_RXFNE (Receive Data Register Not Empty) until
// a complete frame arrives, then reads it from RDR.
// Reading RDR automatically clears the RXNE flag.
int uart2_read(void) {
    while (!(USART2->ISR & USART_ISR_RXNE_RXFNE)) {}
    return (USART2->RDR & 0xFF);
}

// -- Helper functions --------------------------------------------------------
static void uart_set_baudrate(USART_TypeDef *usartx, uint32_t periphClk, uint32_t baudRate) {
    usartx->BRR = compute_uart_bd(periphClk, baudRate);
}

// Compute the BRR divisor using integer rounding:
//   round(periphClk / baudRate) = (periphClk + baudRate/2) / baudRate
// This gives the correct result even when the division is not exact.
static uint16_t compute_uart_bd(uint32_t periphClk, uint32_t baudRate) {
    return ((periphClk + (baudRate / 2U)) / baudRate);
}
