#include "uart_log.h"
#include <stdarg.h>
#include <string.h>
#include <stdio.h>  // 包含<stdio.h>头文件

#define SERIAL_BUFFER_SIZE 256
void USART1_GPIO_Init(void) {
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_USART1EN;
    GPIOA->CRH &= ~(0xF << 4);
    GPIOA->CRH |= (0xB << 4);
    GPIOA->CRH &= ~(0xF << 8);
    GPIOA->CRH |= (0x4 << 8);
}

void USART1_Init(void) {
    USART1->BRR = 0x271;  // 设置波特率为 115200
    USART1->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;
    USART1->CR2 = 0;
    USART1->CR3 = 0;
}

void USART1_SendChar(char ch) {
    while (!(USART1->SR & USART_SR_TXE));
    USART1->DR = (ch & 0xFF);
}

void USART1_SendString(const char *str) {
    while (*str) {
        USART1_SendChar(*str++);
    }
}

void Serial_Init(void) {
    USART1_GPIO_Init();
    USART1_Init();
}

void Serial_Print(const char *str) {
    USART1_SendString(str);
}

void Serial_Write(char ch) {
    USART1_SendChar(ch);
}

void Serial_Printf(const char *format, ...) {
    char buffer[SERIAL_BUFFER_SIZE];
    va_list args;

    va_start(args, format);
    int result = vsnprintf(buffer, SERIAL_BUFFER_SIZE, format, args);
    if (result >= 0) {
        // 如果成功格式化字符串，则发送
        USART1_SendString(buffer);
    } else {
        // 如果失败，则发送错误消息
        USART1_SendString("Format error");
    }
    va_end(args);
}

void Serial_PrintFloat(float num) {
    // 确定符号并取绝对值以处理负数
    int isNegative = num < 0;
    if (isNegative) {
        num = -num;
    }

    // 分离整数部分
    int integerPart = (int)num;

    // 计算小数部分，但转换为整数来避免精度问题
    int fractionalPart = (int)((num - integerPart) * 10000); // 保留四位小数

    // 调整负数输出
    char buffer[64];
    if (isNegative) {
        snprintf(buffer, sizeof(buffer), "-%d.%04d", integerPart, fractionalPart);
    } else {
        snprintf(buffer, sizeof(buffer), "%d.%04d", integerPart, fractionalPart);
    }

    // 去除末尾的零
    char* endPtr = buffer + strlen(buffer) - 1;
    while (*endPtr == '0' && *(endPtr - 1) != '.') {
        *endPtr = '\0';
        endPtr--;
    }

    Serial_Print(buffer);
}

