/*
 * r_sci_uart_buf.h
 *
 *  Created on: 2/02/2021 г.
 *      Author: 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. *
 * ----------------------------------------------------------------------
 * драйвер буфера УАРТа, на базе интерфейса r_sci_uart
 */

#ifndef BSP_R_SCI_UART_BUF_H_
#define BSP_R_SCI_UART_BUF_H_

// FSP generated sources
#include "r_uart_api.h"
// contiki lib
#include <lib/ringbuf16index.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/////////////////////////////////////////////////////////////////////////////////////////
/// API


struct uartbuf_cfg_t;
typedef struct uartbuf_cfg_t uartbuf_cfg_t;

/** UART control block.  Allocate an instance specific control block to pass into the UART API calls.
 * @par Implemented as
 * - sci_uart_instance_ctrl_t
 */
//typedef void uartbuf_ctrl_t;
typedef uartbuf_cfg_t uartbuf_ctrl_t;

/// @brief return character for uartbuf_on_recv_t special values < 0:
enum{
    UARTBUF_EVENT_TX_COMPLETE   = -UART_EVENT_TX_COMPLETE,
    UARTBUF_EVENT_RX_COMPLETE   = -UART_EVENT_RX_COMPLETE,
    UARTBUF_EVENT_EMPTY         = -UART_EVENT_TX_DATA_EMPTY,
    UARTBUF_EVENT_FULL          = UARTBUF_EVENT_EMPTY -1,

    UARTBUF_EVENT_ERR           = (~0xff) ,
    UARTBUF_EVENT_BREAK_DETECT  = UARTBUF_EVENT_ERR | UART_EVENT_BREAK_DETECT,
    UARTBUF_EVENT_ERR_PARITY    = UARTBUF_EVENT_ERR | UART_EVENT_ERR_PARITY,
    UARTBUF_EVENT_ERR_FRAMING   = UARTBUF_EVENT_ERR | UART_EVENT_ERR_FRAMING,
    UARTBUF_EVENT_ERR_OVERFLOW  = UARTBUF_EVENT_ERR | UART_EVENT_ERR_OVERFLOW,

    ///< самое нижнее событие
    UARTBUF_EVENT_TOTAL         = UARTBUF_EVENT_ERR,
};

typedef void (* uartbuf_on_recv_t)(void* self, uartbuf_ctrl_t* uctrl, int x);
typedef void (* uartbuf_on_sent_t)(void* self, uartbuf_ctrl_t* uctrl, int event);

struct uartbuf_cfg_t{
    volatile
    struct ringbuf16index   txbuf;
    uint8_t*                txstore;

    volatile
    struct ringbuf16index   rxbuf;
    uint8_t*                rxstore;

    uart_ctrl_t      * uart_ctrl;         ///< Pointer to the control structure for this instance
    uart_cfg_t const * uart_cfg;          ///< Pointer to the configuration structure for this instance

    /* Configuration for UART Event processing */
    uartbuf_on_recv_t   on_recv;
    uartbuf_on_sent_t   on_sent;
    void* p_context;                      ///< User defined context passed into callback function

    transfer_info_t *   tx_dma;
    transfer_info_t *   rx_dma;

    volatile unsigned   posted;           ///< amount of bytes posted to tx
    ///< counts recv errors. clears on rxbuf empty - on drop
    volatile
    unsigned            rx_err_cnt;
};

///////////////////////////////////////////////////////////////////////////////////
/// locals

/*struct uartbuf_instance_ctrl_t {

};*/

typedef struct uartbuf_cfg_t uartbuf_instance_ctrl_t;


static inline
int R_SCI_UARTBUF_avail(uartbuf_ctrl_t * const p_ctrl){
    return ringbuf16index_elements((struct ringbuf16index*)&p_ctrl->rxbuf);
}

static inline
int R_SCI_UARTBUF_empty(uartbuf_ctrl_t * const p_ctrl){
    return ringbuf16index_empty((struct ringbuf16index*)&p_ctrl->rxbuf);
}

static inline
int R_SCI_UARTBUF_full(uartbuf_ctrl_t * const p_ctrl){
    return ringbuf16index_full((struct ringbuf16index*)&p_ctrl->txbuf);
}

static inline
uint8_t* R_SCI_UARTBUF_touch(uartbuf_ctrl_t * const p_ctrl, unsigned  idx){
    return &(p_ctrl->rxstore[ (p_ctrl->rxbuf.get_ptr+idx) & p_ctrl->rxbuf.mask ]);
}


fsp_err_t R_SCI_UARTBUF_Open(uartbuf_ctrl_t * const p_ctrl, uartbuf_cfg_t const * const p_cfg);

/// @brief nonblock read from buf
/// @return >= 0 - loaded data amount
/// @arg  p_dest == NULL - just drop <bytes> from buffer
int R_SCI_UARTBUF_Read(uartbuf_ctrl_t * const p_ctrl, void* p_dest, unsigned bytes);

/// @brief view received data in buf
/// @return >= 0 - avail data amount
/// @arg  p_head - pointer to receiver buffer head
///             == NULL - just return amount of data string in buffer, like R_SCI_UARTBUF_avail
int R_SCI_UARTBUF_Head(uartbuf_ctrl_t * const p_ctrl, void** p_head);

/// @brief nonblock write to buf
/// @return >= 0 - writen data amount
int R_SCI_UARTBUF_Write(uartbuf_ctrl_t * const p_ctrl, void const* p_src, unsigned bytes);

int R_SCI_UARTBUF_Putc(uartbuf_ctrl_t * const p_ctrl, uint8_t x);

/// @return UARTBUF_EVENT_EMPTY - no chars
int R_SCI_UARTBUF_Getc(uartbuf_ctrl_t * const p_ctrl);

fsp_err_t R_SCI_UARTBUF_Close(uartbuf_ctrl_t * const p_ctrl);

/// @brief test write uart free
/// @return - true tx empty, and free
bool R_SCI_UARTBUF_Flush(uartbuf_ctrl_t * const p_ctrl);

fsp_err_t R_SCI_UARTBUF_Drop(uartbuf_ctrl_t * const p_ctrl, uart_dir_t communication_to_abort);

fsp_err_t R_SCI_UARTBUF_CallbackSet(uartbuf_ctrl_t * const p_ctrl, void* const p_context
                                , uartbuf_on_recv_t on_recv, uartbuf_on_sent_t on_sent
                                );
enum {
    ///< callback on receive fails only
    UARTBUF_EVMODE_RX_FAILS = 0,
    ///< enable callback on receive chars
    // UARTBUF_EVMODE_RX_CHAR  = 1 ,
};
typedef unsigned UARTBufEventMode;

fsp_err_t R_SCI_UARTBUF_CallbackMode(uartbuf_ctrl_t * const p_ctrl, UARTBufEventMode mode);


/// @brief останов/перезахват УАРТа для обмена. Буферы остаются целы и доступны для обмена.
/// @return - буферр захвачен, ДМА настроены. передача в останове, и может быть запущена
///     Read/Write/Go
/// @arg  p_uart_over == NULL - останавливает текущую передачу и выключает порт
///                   == uart - назначает новый уарт, настраивает его и запускает обмен
fsp_err_t R_SCI_UARTBUF_Over(uartbuf_ctrl_t * p_ctrl, uart_ctrl_t * p_uart_over);

/// @brief starts transmition, if it hungs after Over or occasionaly
/// @return >= 0 - writen data amount
void R_SCI_UARTBUF_Go(uartbuf_ctrl_t * const p_ctrl);


#ifdef __cplusplus
}
#endif

#endif /* BSP_R_SCI_UART_BUF_H_ */
