/*
 * Copyright (C) 2023 Daniele Lacamera <root@danielinux.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "unicore-mx/cm3/systick.h"
#include <unicore-mx/stm32/gpio.h>
#include <unicore-mx/cm3/nvic.h>
#include <stdlib.h>
#include <stdint.h>
#include "system.h"
#include "systick.h"
#include "button.h"
#include "stm32f7_ltdc.h"
#include "ui.h"
#include "timer.h"
#include "led.h"
#include "adc.h"
#include "unicore-mx/stm32/rcc.h"
#define SCB_CPACR *((volatile uint32_t *)(0xE000ED88))

void sdram_init(void);

void logging_setup(void);
void kspserial_setup(void);
void main_deck_setup(void);

extern int f7_mpu_enable(void);

static void fpu_init(void)
{
    SCB_CPACR |= (0x3 << 20) | (0x03 << 22);
}

void hardware_setup(void)
{
    f7_mpu_enable();
    fpu_init();
    rcc_clock_setup_hse_3v3(&rcc_hse_25mhz_3v3);
    nvic_set_priority(NVIC_SYSTICK_IRQ, 0);
    systick_enable();
    rcc_periph_clock_enable(RCC_TIM2);
    rcc_periph_clock_enable(RCC_I2C1);
    sdram_init();
    uled_init();
    ltdc_init();
    ltdc_blank();
    ft5336_Init(TS_I2C_ADDR);
    touchscreen_enable();
}

void main(void) {
    int i;
    uint8_t zeros[16] = {0};
    hardware_setup();
    while (jiffies < 800) {
        WFI();
    }
    for (i = 0; i < 6; i++)
        uled_off(i);
    ui_setup();
    input_setup();
    main_deck_setup();
    kspserial_setup();
    main_loop();
}

