/*
 * 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 <stdint.h>
#include "led.h"
#include "system.h"
#include "unicore-mx/stm32/gpio.h"
#include "unicore-mx/stm32/rcc.h"

/* A15, G7, B4, G6, C6, C7 */

void uled_init(void)
{
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_GPIOB);
    rcc_periph_clock_enable(RCC_GPIOC);
    rcc_periph_clock_enable(RCC_GPIOG);
    gpio_mode_setup(GPIOA, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LD0);
    gpio_set(GPIOA, LD0);
    gpio_mode_setup(GPIOG, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLDOWN, LD1 | LD3);
    gpio_set(GPIOG, LD1 | LD3);
    gpio_mode_setup(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLDOWN, LD2);
    gpio_set(GPIOB, LD2);
    gpio_mode_setup(GPIOC, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLDOWN, LD4 | LD5);
    gpio_set(GPIOC, LD4 | LD5);
}

void uled_on(int led)
{
    switch(led)
    {
        case 0:
            gpio_set(GPIOA, LD0);
            break;
        case 1:
            gpio_set(GPIOG, LD1);
            break;
        case 2:
            gpio_set(GPIOB, LD2);
            break;
        case 3:
            gpio_set(GPIOG, LD3);
            break;
        case 4:
            gpio_set(GPIOC, LD4);
            break;
        case 5:
            gpio_set(GPIOC, LD5);
            break;
    }
}

void uled_off(int led)
{
    switch(led)
    {
        case 0:
            gpio_clear(GPIOA, LD0);
            break;
        case 1:
            gpio_clear(GPIOG, LD1);
            break;
        case 2:
            gpio_clear(GPIOB, LD2);
            break;
        case 3:
            gpio_clear(GPIOG, LD3);
            break;
        case 4:
            gpio_clear(GPIOC, LD4);
            break;
        case 5:
            gpio_clear(GPIOC, LD5);
            break;
    }
}


void uled_bincount(uint8_t x)
{
    int a,b,c,d;
    a = (x & 0x1);
    b = (x & 0x2) >> 1;
    c = (x & 0x4) >> 2;
    d = (x & 0x8) >> 3;
    if (a)
        gpio_set(GPIOA, LD0);
    else
        gpio_clear(GPIOA, LD0);
    if (b)
        gpio_set(GPIOG, LD1);
    else
        gpio_clear(GPIOG, LD1);
    if (c)
        gpio_set(GPIOB, LD2);
    else
        gpio_clear(GPIOB, LD2);
    if (d)
        gpio_set(GPIOG, LD3);
    else
        gpio_clear(GPIOG, LD3);
}
