#ifndef __ADC_GPIO_H__
#define __ADC_GPIO_H__

#include "tc_system.h"
#include "tc_thread.h"
#include "com_ttySx.h"


#define MCU_GPIO0_BASE 488   // 24 
#define SOC_GPIO0_BASE 396   // 92
#define SOC_GPIO1_BASE 344   // 52


#define MCU_GPIO0      0
#define SOC_GPIO0      1
#define SOC_GPIO1      2


static uint32_t get_gpio_index(int group, int index)
{
    uint32_t gpio = 0;
    switch(group)
    {
        case MCU_GPIO0:  if(index<0) index=0; if (index>=24) index=23; gpio = MCU_GPIO0_BASE + index; break;
        case SOC_GPIO0:  if(index<0) index=0; if (index>=92) index=91; gpio = SOC_GPIO0_BASE + index; break;
        case SOC_GPIO1:  if(index<0) index=0; if (index>=52) index=51; gpio = SOC_GPIO1_BASE + index; break;
    }
    return gpio;
}

static void config_gpio_free(int group, int index)
{
    uint8_t buff[128];
    uint32_t gpio = get_gpio_index(group, index);
    sprintf(buff, "/sys/class/gpio/gpio%d", gpio);
    if (access(buff, F_OK) == 0)
    {
        sprintf(buff, "echo %d > /sys/class/gpio/unexport", gpio);system(buff);
    }
}

static void config_gpio_out(int group, int index, int default_v)
{
    uint8_t buff[128];
    uint32_t gpio = get_gpio_index(group, index);
    // printf("%s:%d(%s) | gpio=%d, group:%d, index=%d\n", __FILE__, __LINE__, __FUNCTION__, gpio, group, index);
    sprintf(buff, "/sys/class/gpio/gpio%d", gpio);
    if (access(buff, F_OK) != 0)
    {
        sprintf(buff, "echo %d > /sys/class/gpio/export", gpio);system(buff);
    }
    sprintf(buff, "echo out > /sys/class/gpio/gpio%d/direction", gpio);system(buff);
    sprintf(buff, "echo %d > /sys/class/gpio/gpio%d/value", default_v, gpio);system(buff);
}

static void config_gpio_in(int group, int index)
{
    uint8_t buff[128];
    uint32_t gpio = get_gpio_index(group, index);
    // printf("%s:%d(%s) | gpio=%d, group:%d, index=%d\n", __FILE__, __LINE__, __FUNCTION__, gpio, group, index);
    sprintf(buff, "/sys/class/gpio/gpio%d", gpio);
    if (access(buff, F_OK) != 0)
    {
        sprintf(buff, "echo %d > /sys/class/gpio/export", gpio);system(buff);
    }
    sprintf(buff, "echo in > /sys/class/gpio/gpio%d/direction", gpio);system(buff);
}

static int get_gpio_value(int group, int index)
{
    int value;
    uint8_t buff[128];
    uint32_t gpio = get_gpio_index(group, index);
    sprintf(buff, "/sys/class/gpio/gpio%d/value", gpio);
    FILE* fp = fopen(buff, "r");
    fscanf(fp, "%d", &value);
    fclose(fp);
    // printf("%s:%d(%s) | gpio=%d, group:%d, index=%d, value=%d\n", __FILE__, __LINE__, __FUNCTION__, gpio, group, index, value);
    return value;
}

static void set_gpio_value(int group, int index, int value)
{
    uint8_t buff[128];
    uint32_t gpio = get_gpio_index(group, index);
    // printf("%s:%d(%s) | gpio=%d, group:%d, index=%d, value=%d\n", __FILE__, __LINE__, __FUNCTION__, gpio, group, index, value);
    sprintf(buff, "echo %d > /sys/class/gpio/gpio%d/value", value, gpio);system(buff);
}

#endif//__ADC_GPIO_H__
