/*
 * true's GAT Nametag
 * Rushed SUPERCON 8 EDITION
 * main MCU firmware
 * 2024 true
 *
 * much of this code is copied from true's DC29 Whiskey Pirates badge,
 * which was in turn copied from the original GAT Nametag.
 *
 * The GAT Nametag used an 8-bit 8051 core MCU.
 * DC29 minibadge used a RISC-V core, and code was hastily ported.
 * this is why things like the menu system are so convoluted;
 *
 * the main MCU is responsible for the following:
 * - rendering OLED UI
 * - rendering LED programs
 * - storing fonts
 * - communicating with I2C devices, including:
 *   - oled display, accelerometer
 *   - eeprom, sub MCU, RGBLED controller
 * - implementing USB interface
 * - implementing BLE (maybe)
 *
 */

#include <hw/ch32sub.h>
#include "CH59x_common.h"

#include "comm/i2c.h"

#include "hw/gat/gat_gpio.h"

#include "led/rgbled.h"

#include "misc/accel.h"

#include "global.h"
#include "port_intr.h"
#include "user_config.h"



const uint8_t vers[] = "241013.01";

uint8_t cpu_use = 0;
uint8_t cpu_max = 0;

uint32_t uptime = 0;
uint16_t uptime_hour;
uint8_t  uptime_min;
uint8_t  uptime_sec;

uint32_t idle_time_menu;
uint32_t idle_time_still;
uint8_t  idle_go_sleep;



void ch59x_xtal_conf()
{
    HSECFG_Current(HSE_RCur_125);
    HSECFG_Capacitance(HSECap_14p);
}

int main()
{
    // configure clock
    ch59x_xtal_conf();
    SetSysClock(SYSCLK_FREQ_USEI2C);

    // enable DC-DC converter; brings significant power saving
    PWR_DCDCCfg(ENABLE);

    // get i2c initialized since most stuff will need it
    i2c_init();

    // read the user config
    uconf_load();

    // initialize aux MCU
    ch32sub_init();
    // and enable RGBLED controller hardware pin so the controller can wake up
    ch32sub_rgb_hwen(1);

    // initialize accelerometer
    accel_init();

    // initialize RGBLED controller
    rgbled_init();

    // configure GAT aux GPIOs, get gat ID
    gat_gpio_init();
    // configure GAT i2c slave
    // not yet implemented

    // configure port-based interrupts (used for ch32sub interrupt)
    port_intr_init();

    // note that system clock speed is decreased after every use of I2C

    while(1) {
        // only care about aux MCU when all other processing is done
        ch32sub_process();

        // sleep when we're doing nothing
        __WFI();
    }
}
