/*
 * mcu_gpio.h
 *
 *  Created on: 29/01/2021.
*      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
  ------------------------------------------------------------------------
 *      this is RA2L1 for STM SPL compatibily wrapers
 */

#ifndef HAL_RA2L1_MCU_GPIO_H_
#define HAL_RA2L1_MCU_GPIO_H_

#include <stdint.h>
#include <mcu-chip.h>

// FSP generated environment
//#include <bsp_io.h>
//#include "ra/fsp/inc/instances/r_ioport.h"
// import: R_IOPORT_PinCfg
#include "r_ioport.h"
// import: g_ioport_ctrl
#include "common_data.h"

#include <c_compat.h>


#define __GPIO_CAT2(a, b) a##b
#define GPIO_PORT(n)  __GPIO_CAT2(R_PORT, n)

#define GPIO_PORT_IDXSTEP   (R_PORT1_BASE - R_PORT0_BASE)
#define GPIO_PORT_NO(port)  ( ( ((uint8_t*)(port)) - R_PORT0_BASE )/GPIO_PORT_IDXSTEP)
#define GPIO_PORTn(n)       ( (R_PORT0_Type*)( R_PORT0_BASE + ((n)*GPIO_PORT_IDXSTEP) ) )
#define GPIO_PINSn(n)       (GPIO_PORTn(n)->PIDR)
#define GPIO_PORTSn(n)      (GPIO_PORTn(n)->PODR)
#define GPIO_MODEn(n)       (GPIO_PORTn(n)->PDR)

#ifdef __cplusplus
extern "C" {
#endif

typedef R_PORT0_Type             GPIO_TypeDef;
//typedef PORT_InitTypeDef        GPIO_InitTypeDef;
//#define GPIO_StructInit(...)    PORT_StructInit(__VA_ARGS__)
#define GPIO_Init(pin, cfg)       R_IOPORT_PinCfg(&g_ioport_ctrl , pin, cfg)

#define GPIO_SetBits( port, bits_mask )     do { (port)->POSR = (bits_mask); } while(0)
#define GPIO_ResetBits( port, bits_mask )   do { (port)->PORR = (bits_mask); } while(0)
#define GPIO_Bits(port, bits_mask )         ((port)->PODR & (bits_mask))
#define GPIO_ReadInputData(port)            ((port).PIDR)

#define GPIO_SETBIT( port, bit )            GPIO_SetBits(port, (1u<<(bit)))
#define GPIO_CLRBIT( port, bit )            GPIO_ResetBits(port, (1u<<(bit)))
#define GPIO_INVBIT( port, bit )            GPIO_TwistBits(port, (1u<<(bit)))
#define GPIO_GETBIT( port, bit )            ( ((port)->PIDR >> (bit)) & 1u)
#define GPIO_ISBIT( port, bit )             (GPIO_Bits(port, (1u<<(bit))) != 0)
#define GPIO_ISIN( port, bit )              (( ((port)->PIDR >> (bit)) & 1u) != 0 )




#if 1
static inline
void GPIO_WriteBits(GPIO_TypeDef* port, uint16_t data, uint16_t bits_mask)    {
    port->PORR   = (uint16_t)~data & bits_mask;
    port->POSR   = data & bits_mask;
}

static inline
void GPIO_TwistBits(GPIO_TypeDef* port, uint16_t bits_mask) {
    uint16_t x = port->PODR;
    port->PORR   = x & bits_mask;
    port->POSR   = (uint16_t)~x  & bits_mask;
}

static inline
void GPIO_WRBIT( GPIO_TypeDef* port, char bit, char x ){
    port->PORR   = (uint16_t)((~x&1) << bit);
    port->POSR   = (uint16_t)((x&1)<<bit);
}

#else
/// port->PCNTR3 is mulfunction in RA2L
static inline
void GPIO_WriteBits(GPIO_TypeDef* port, uint16_t data, uint16_t bits_mask)    {
    uint32_t mask = (bits_mask <<16) | bits_mask;
    uint32_t pins = (~data<< 16) | data;
    port->PCNTR3 = pins & mask;
}

static inline
void GPIO_TwistBits(GPIO_TypeDef* port, uint16_t bits_mask) {
    uint32_t mask = (bits_mask <<16) | bits_mask;
    uint16_t x = port->PODR;
    uint32_t pins = (~x << 16) | x;
    port->PCNTR3 = pins & mask;
}

static inline
void GPIO_WRBIT( GPIO_TypeDef* port, char bit, char x ){
    uint32_t mask = ((x&1)<<bit) | ((~x&1) << bit);
    port->PCNTR3 = mask;
}
#endif



//* pin operations are for pinName:MCU_PINS enumerated pins
/*!
 * use pin coding scheme [port:8bit][pin:8bit] - same as FSP bsp_io use
 */
#define GPIO_SETPIN( pin )  GPIO_SETBIT( GPIO_PORTn(((pin)>>8)&0xf) , (pin)&0xf )
#define GPIO_CLRPIN( pin )  GPIO_CLRBIT( GPIO_PORTn(((pin)>>8)&0xf) , (pin)&0xf )
#define GPIO_INVPIN( pin )  GPIO_INVBIT( GPIO_PORTn(((pin)>>8)&0xf) , (pin)&0xf )
#define GPIO_WRPIN( pin, x )  GPIO_WRBIT( GPIO_PORTn(((pin)>>8)&0xf) , (pin)&0xf , (x) )
#define GPIO_GETPIN( pin )  GPIO_GETBIT( GPIO_PORTn(((pin)>>8)&0xf) , (pin)&0xf )
#define GPIO_ISPOUT( pin )  GPIO_ISBIT( GPIO_PORTn(((pin)>>8)&0xf) , ((pin)&0xf) )
#define GPIO_ISPIN( pin )   GPIO_ISIN( GPIO_PORTn(((pin)>>8)&0xf) , ((pin)&0xf) )




///////////////////////////////////////////////////////////////////////////////
///              PIN FUNCTION/MODE API

/// PinFunctionSelect and Control reg
typedef R_PFS_PORT_PIN_Type GPIOPinPFSReg;

static inline
GPIOPinPFSReg* GPIO_PinPFS(uint16_t pin){
    return (R_PFS_PORT_PIN_Type*) &( R_PFS->PORT[pin >> 8].PIN[pin &0xf]);
}



// описатель стиля пина, для упрощенного объявления структуры инициализации пина PIN_INIT
enum PinStyle{
    psIn        = IOPORT_CFG_PORT_DIRECTION_INPUT,
    psOut       = IOPORT_CFG_PORT_DIRECTION_OUTPUT,
    psLow       = 0,
    psHigh      = 1,

    psOD        = IOPORT_CFG_NMOS_ENABLE,     //open drain
    psPU        = IOPORT_CFG_PULLUP_ENABLE,   //pull up
    psPullUp    = psPU,
    //psPD      = 0x40, //pull dn not supports
    //psPullDn  = psPD,

    //psINV     = 0x100000, //inverted

    psANALOG    = IOPORT_CFG_ANALOG_ENABLE,   //
    psIRQ       = IOPORT_CFG_IRQ_ENABLE,

    psNONE    = 0,

    // PinFunc field in PinStyle, used bu GPIOFUNC_INIT - mixes pf | ps
    psPF_Pos    = 7,
    psPF_Msk    = 0x1fu << psPF_Pos,
};

struct PIN_INIT{
    uint16_t         pin;
    uint16_t         style; // \sa PinStyle
};
typedef struct PIN_INIT PIN_INIT;

#define PININIT_DEF(p, n, _style) {\
        struct_field(pin) n, struct_field(style) _style\
    }


enum PinFuncID{
    pfNONE  = 0,
    pfAGT   = 1,
    pfSCI0  = 4, pfSCI2 = pfSCI0, pfSCI4 = pfSCI0, pfSCI6 = pfSCI0,
    pfSCI1  = 5, pfSCI3 = pfSCI1, pfSCI5 = pfSCI1, pfSCI7 = pfSCI1, pfSCI9 = pfSCI1,
    pfSPI   = 6,
    pfIIC   = 7,

    // mark none function, for end of pins list
    pfEND  = 0xf,
};

#define PF_SCIn(n) ( pfSCI0 + ((n)%2) )

// описатель структуры инициализации группы пинов на альтернативную функцию
struct GPIOFUNC_INIT{
    uint16_t            pin;
    uint16_t            style_func; // \sa PinStyle | PinFunc
};
typedef struct GPIOFUNC_INIT GPIOFUNC_INIT;


#define PINFUNC_DEF(p, n, _style, f) {\
        struct_field(pin) n, struct_field(style_func) ( (_style) | ((f) <<psPF_Pos) ) \
    }

#define PINFUNC_PS( gpfstyle )    ((gpfstyle) & ~psPF_Msk)
#define PINFUNC_PF( gpfstyle )    (((gpfstyle) & psPF_Msk) >> psPF_Pos)


///////////////////////////////////////////////////////////////////////////////
///              gpio.h  API

/// @brief config pins array <cfg>[count]
/// @arg count - <cfg> elements num
void gpio_confs(const PIN_INIT* cfg, unsigned count);

/// @brief config pins array <cfg>[count] as periferial function pins
/// @arg count - <cfg> elements num
void gpio_confs_func(const GPIOFUNC_INIT* cfg, unsigned count);

void gpio_conf_func(const GPIOFUNC_INIT* x);

// \return - функция первого пина в pins
enum PinFuncID gpio_func(uint16_t pin);

// @brief inline version of gpio_func
static inline
enum PinFuncID GPIO_FUNC(uint16_t pin){
    GPIOPinPFSReg* pfs = GPIO_PinPFS(pin);
    return (enum PinFuncID)( (pfs->PmnPFS >> IOPORT_PRV_PFS_PSEL_OFFSET) & pfEND);
}


#if BSP_CFG_PFS_PROTECT

void gpio_conf_out(const PIN_INIT x);
void gpio_conf_pin_style(uint16_t pin, unsigned style );

#else



///@brief config periferial pin style
static inline
void gpio_conf_out(const PIN_INIT x){
    GPIOPinPFSReg* pfs = GPIO_PinPFS(x.pin);
    pfs->PmnPFS = x.style;
}

static inline
void gpio_conf_pin_style(uint16_t pin, unsigned style ){
    GPIOPinPFSReg* pfs = GPIO_PinPFS(pin);
    pfs->PmnPFS = style;
}



#endif



#ifdef __cplusplus
}
#endif

#endif /* HAL_MDR32F9QX_MCU_USART_H_ */
