/**************************************************************************
 * Copyright (C) 2017-2017  Unisound
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 **************************************************************************
 *
 * Description : user_gpio.h
 * Author      : yuanshifeng@unisound.com
 * Date        : 2021.03.01
 *
 **************************************************************************/
#ifndef USER_GPIO_H_
#define USER_GPIO_H_

#include "driver/uni_gpio.h"
#include "driver/uni_uart.h"
#include "driver/uni_timer.h"
#include "driver/uni_padmux.h"
#include "lvp_app_core.h"

#define NSEC_PER_SEC 1000000000L    // 纳秒每秒
#define PWM_HZ_MAX   (1000 * 1000)  // max 1MHz (recommand below 40KHz on HB-L)
#define GPIO_PWM_MAX 2

typedef struct {
  uint8_t used;
  uint32_t mapped_gpio_port;
  uint32_t freq;
  uint8_t duty;
  uint8_t inverse;
} pwm_info_t;

typedef struct {
  int timer_id;
  int port;
  int period_ms;
  int times;
  int def_val;
  uint8_t is_top;
} gpio_pulse_t;

typedef enum {
  USER_PIN_NUM_1 = 3,
  USER_PIN_NUM_2 = 4,
  USER_PIN_NUM_6 = 5,
  USER_PIN_NUM_7 = 6,
  USER_PIN_NUM_8 = 7,
  USER_PIN_NUM_9 = 8,
  USER_PIN_NUM_10 = 9,
  USER_PIN_NUM_11 = 10,
  USER_PIN_NUM_12 = 11,
  USER_PIN_NUM_13 = 12,
  USER_PIN_NUM_18 = 0,
  USER_PIN_NUM_19 = 1,
  USER_PIN_NUM_20 = 2,
} UserPinNum;

typedef enum {
  USER_PIN_FUNC_GPIO_PWM = 0,
  USER_PIN_FUNC_UART,
  USER_PIN_FUNC_DAC,
} UserPinFunc;

void user_pin_set_func(UserPinNum user_pin, UserPinFunc user_func);
int user_gpio_set_direction(UserPinNum user_pin, UNI_GPIO_DIRECTION direction);
int user_gpio_set_level(UserPinNum user_pin, UNI_GPIO_LEVEL level);
int user_pwm_init(UserPinNum user_pin, uint32_t freq, uint8_t inverse,
                  uint8_t duty);
int user_pwm_duty_inc(uint32_t pwm_port, uint8_t det_duty);
int user_pwm_duty_dec(uint32_t pwm_port, uint8_t det_duty);
int user_pwm_enable(uint32_t pwm_port, uint8_t duty);
int user_pwm_disable(uint32_t pwm_port);
int user_uart_init(UserPinNum user_pin, uint32_t baudrate, int data_bits, int stop_bits,
                   int parity);
int user_sw_timer_gpio_pulse(int port, int period_ms, int times,
                             uint8_t dev_val);

#endif
