/*!
    \file    main.c
    \brief   led spark with systick, USART print and key example

    \version 2024-02-22, V2.1.0, firmware for GD32E23x
*/
#include "main.h"
#include <stdio.h>
#include "gd32e23x.h"
#include "systick.h"
#include "gd32e23x_libopt.h"
#include "rs485.h"
#include "led.h"
#include "i2c.h"
#include "ldc1612.h"
#include "tmp112.h"

uint32_t g_temperature_uint32;
uint32_t g_eddy_current_value_uint32;

void watchdog_init(void) {
    /* Enable the LSI clock */
    rcu_osci_on(RCU_IRC40K);
    rcu_osci_stab_wait(RCU_IRC40K);

    /* Configure FWDGT counter clock: 40KHz(IRC40K) / 64 = 0.625 KHz */
    fwdgt_config(625, FWDGT_PSC_DIV64); // Set timeout to 1 seconds (625 / 0.625 KHz)

    /* Enable FWDGT */
    fwdgt_enable();
}

void reset_mcu(void) {
    /* Enable the write access to the FWDGT_CTL register */
    FWDGT_CTL = FWDGT_WRITEACCESS_ENABLE;

    /* Configure FWDGT to trigger a system reset */
    fwdgt_config(50, FWDGT_PSC_DIV4);

    /* Reload the counter to trigger the reset */
    fwdgt_counter_reload();
}

/*!
    \brief      main function
    \param[in]  none
    \param[out] none
    \retval     none
*/
int main(void) {
    setbuf(stdout, NULL);
    /* configure systick */
    systick_config();
    /* configure USART */
    rs485_config();
    /* configure LED */
    led_config();
    /* configure I2C */
    i2c_gpio_config();
    i2c_config();

    // ldc1612_iic_get_sensor_infomation();
    /* configure LDC1612 */
    ldc1612_single_ch0_config();

    /* Initialize watchdog */
    watchdog_init();

    while (1) {
        delay_ms(99);
        fwdgt_counter_reload();
    }
}

/* retarget the C library printf function to the USART */
int _write(int fd, char *pBuffer, int size) {
    for (int i = 0; i < size; i++) {
        usart_data_transmit(USART0, (uint8_t) pBuffer[i]);
        while (RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    }
    return size;
}
