/*
 * ssp_device.cpp
 *
 *  Created on: 15 нояб. 2018 г.
 *      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. *
 */

#include <cassert>
#include <cslr.h>
#include <mcu_rcc.h>
#include <mcu_ssp.h>
#include <gpio.h>
//#include <os_isr.h>
#include <system.h>
//#include "hw.h"
#include <spi_device.hpp>


#include <trace_probes.h>
#ifndef trace_ssp_wr
trace_need(ssp_wr)
trace_need(ssp_rd)
trace_need(ssp_tx)
trace_need(ssp_wait)
trace_need(ssp_post)
trace_need(ssp_trx)
trace_need(sspio_wait)
#endif

#if 0
#define ASSERT_SSP(...) ASSERT_SSP(__VA_ARGS__)
#else
#define ASSERT_SSP(...)
#endif



SSP_SWMasterProxy::SSP_SWMasterProxy(dev_name name)
:inherited()
, nameddev_t(name)
, cfg(NULL), io(NULL)
, css(name)
, msg(NULL)
, fsck_hz(0)
, ssp_mode(0)
{};

int SSP_SWMasterProxy::init( const SSP_INIT* _cfg){
    cfg = _cfg;
    io = cfg->port;
    ASSERT_SSP(io != NULL);
    css.init(cfg->cspins);
    if( !nvic_is_nan(cfg->nvic) )
        NVIC_Init(&cfg->nvic);

    RCC_EnableClock_SPI( io );
    LL_SPI_Disable(io);
    if(cfg->GPIOPINS){
        gpio_conf_func(cfg->GPIOPINS);
    }
    LL_SPI_SetNSSMode(io, LL_SPI_NSS_SOFT);
    LL_SPI_SetMode(io, LL_SPI_MODE_MASTER);
    LL_SPI_SetStandard(io, LL_SPI_PROTOCOL_MOTOROLA);
    LL_SPI_DisableCRC(io);
    LL_SPI_SetTransferDirection(io, LL_SPI_FULL_DUPLEX);

    LL_SPI_SetBaudRatePrescaler(io, LL_SPI_BAUDRATEPRESCALER_DIV2);
    fsck_hz = SystemCoreClock/2;

    // is supplyed some CS, select 1st by default
    if (css.sel_limit() >= 1)
        css.select(1);

    LL_SPI_Enable(io);
    return init();
}

// SSP_Device
//virtual
int SSP_SWMasterProxy::init(){
    return DEV_OK;
}

//virtual
int SSP_SWMasterProxy::deinit(){
    LL_SPI_Disable(io);
    RCC_DisableClock_SPI( io );
    return DEV_OK;
};

// BUS lock access
//virtual
PTResult SSP_SWMasterProxy::aquire(unsigned cs_id){
    return AS_PTRESULT(cs_select(cs_id));
}

//virtual
int SSP_SWMasterProxy::release(){
    cs_release();
    return DEV_OK;
}

//virtual
DevResult SSP_SWMasterProxy::trx(Message& mesg){
    TRACE_GUARD(ssp, ssp_trx);
    DevResult ok = setup_port(&mesg);
    if (ok != DEV_OK)
        return ok;
    msg = &mesg;
    if (msNB(mesg.mode) == 16)
        transfer16(mesg);
    else if (msNB(mesg.mode) == 8)
        transfer8(mesg);
    else
        ok = errMODE_NOT_SUPP;

    //if (ok == ptOK)
    if ((msg->mode & msCS_HOLD) == 0)
    {
        // транзакция не удерживает линию связи, поэтому освобожу ее
        cs_release();
    }
    return DEV_OK;
}

void SSP_SWMasterProxy::wait_port_empty(){
    //wait while sending active
    while (LL_SPI_IsActiveFlag_BSY(io) != 0)
    {
        wait_fast();
    }
}

void SSP_SWMasterProxy::wait_port_notfull(){
    //wait while sending active
    while (LL_SPI_IsActiveFlag_TXE(io) == 0)
    //while ( (io->SR & SSP_FLAG_TNF) != 0)
    {
        wait_fast();
    }
}



void SSP_SWMasterProxy::drop_port_rx(){
    while (LL_SPI_IsActiveFlag_RXNE(io))
        LL_SPI_ReceiveData8(io);
}

void SSP_SWMasterProxy::transfer8(Message& mesg){
    typedef u8 word_t;
    word_t* dst = (word_t*)mesg.dst;
    const word_t* src = (const word_t*)mesg.src;
    // clear RXNE
    LL_SPI_ReceiveData8(io);
    for (unsigned len = mesg.word_count; len > 0; len--){
        // wait tx buffer
        while (!LL_SPI_IsActiveFlag_TXE(io));
        word_t tmp = 0;
        if (src != NULL)
            tmp = *src++;
        LL_SPI_TransmitData8(io, tmp);
        // wait for rx receives
        // wait for tx sent
        while (!LL_SPI_IsActiveFlag_TXE(io));
        // wait for rx receives
        // FIX: somehow rxme flag is loose. possiby debugger can affect it
        //      therefore need to limit reading
        for (int i = clk_limit ; !LL_SPI_IsActiveFlag_RXNE(io);)
        {
            if (LL_SPI_IsActiveFlag_BSY(io))
                continue;
            if (i>0)
                i--;
            else
                break;
        }

        tmp = LL_SPI_ReceiveData8(io);
        if (dst != NULL)
            *dst++ = tmp;
    }
}

void SSP_SWMasterProxy::transfer16(Message& mesg){
    typedef u16 word_t;
    word_t* dst = (word_t*)mesg.dst;
    const word_t* src = (const word_t*)mesg.src;
    // clear RXNE
    LL_SPI_ReceiveData16(io);
    for (unsigned len = mesg.word_count; len > 0; len--){
        // wait tx buffer
        while (!LL_SPI_IsActiveFlag_TXE(io));
        word_t tmp = 0;
        if (src != NULL)
            tmp = *src++;
        LL_SPI_TransmitData16(io, tmp);

        // wait for tx sent
        while (!LL_SPI_IsActiveFlag_TXE(io));
        // wait for rx receives
        // FIX: somehow rxme flag is loose. possiby debugger can affect it
        //      therefore need to limit reading
        for (int i = clk_limit; !LL_SPI_IsActiveFlag_RXNE(io); )
        {
            if (LL_SPI_IsActiveFlag_BSY(io))
                continue;
            if (i>0)
                i--;
            else
                break;
            //wait_fast();
        }
        tmp = LL_SPI_ReceiveData16(io);
        if (dst != NULL)
            *dst++ = tmp;
    }
}


DevResult SSP_SWMasterProxy::setup_mode(unsigned mode){
    const unsigned mode_mask = msCPOL | msCPHA | msENDIAN | msNB_Msk;
    if ( (ssp_mode& mode_mask) == (mode & mode_mask))
        return DEV_OK;

    uint32_t    tmpreg = 0;
    /* SSPx CR0 Configuration */
    bool is_clkhi = ((mode & msCPOL) == msCLKHI );
    if (is_clkhi)
        tmpreg |= LL_SPI_POLARITY_HIGH;
    else
        tmpreg |= LL_SPI_POLARITY_LOW;

    bool is_clkfall = ((mode & msCPHA) == msCLKFALL);
    if ( is_clkfall == is_clkhi )
        tmpreg |= LL_SPI_PHASE_1EDGE;
    else
        tmpreg |= LL_SPI_PHASE_2EDGE;

    if ((mode & msENDIAN) != msMSB_FIRST){
        tmpreg |= SPI_CR1_LSBFIRST;
    }

    ASSERT_SSP(io != NULL);
    unsigned tmpcr = io->CR1;
    tmpcr &= ~(SPI_CR1_CPOL | SPI_CR1_CPHA
                | SPI_CR1_DFF
                | SPI_CR1_LSBFIRST
                );
    tmpreg |= tmpcr;

    unsigned NB = CSL_FEXT(mode, msNB);
    if (NB != 0){
        if (NB  == 8)
            MODIFY_REG(tmpreg, SPI_CR1_DFF, LL_SPI_DATAWIDTH_8BIT);
        else if (NB == 16)
            MODIFY_REG(tmpreg, SPI_CR1_DFF, LL_SPI_DATAWIDTH_16BIT);
        else
            return errMODE_NOT_SUPP;
    }

    LL_SPI_Disable(io);
    io->CR1 = tmpreg;

    return DEV_OK;
}

DevResult SSP_SWMasterProxy::setup_byte(){
    ASSERT_SSP(io != NULL);
    MODIFY_REG(io->CR1, SPI_CR1_DFF, LL_SPI_DATAWIDTH_8BIT);
    return DEV_OK;
}

DevResult SSP_SWMasterProxy::setup_word(){
    ASSERT_SSP(io != NULL);
    MODIFY_REG(io->CR1, SPI_CR1_DFF, LL_SPI_DATAWIDTH_16BIT);
    return DEV_OK;
}


DevResult SSP_SWMasterProxy::setup_port(const Message* msg){
    ASSERT_SSP(io != NULL);

    DevResult ok = setup_mode(msg->mode);
    if (ok != DEV_OK)
        return ok;

    unsigned cs = CSL_FEXT(msg->mode, msCS);
    if (cs == CSL_FEXT(msCS_KEEP, msCS))
        cs =  CSL_FEXT(ssp_mode, msCS);
    int selected = css.selected();
    if (selected != cs)
    {
        if (selected != css.selNONE){
            // переключение линии требует завершения текущей операции на
            //  текущей линии
            wait_port_empty();
        }
        ok = css.select(cs);
    }
    ssp_mode = msg->mode;
    if (msg->freq != speedKEEP){
        setup_freq(msg->freq);
    }
    return ok;
}


DevResult SSP_SWMasterProxy::cs_select(unsigned csid){
    CSL_FINS(ssp_mode, msCS, csid);
    return css.select(csid);
}

DevResult SSP_SWMasterProxy::cs_select(){
    return css.select( CSL_FEXT(ssp_mode, msCS) );
}

int SSP_SWMasterProxy::setup_freq(unsigned fhz){
    if (fhz == speedKEEP)
        return fsck_hz;
    if (fsck_hz == fhz)
        return fsck_hz;

    unsigned fssp = sys_clocks_value.PCLK1_Frequency /2;
    if ( APBCLK_BIT(io) >= APB2CLK)
        fssp = sys_clocks_value.PCLK2_Frequency /2;

    enum {
          brp2      = LL_SPI_BAUDRATEPRESCALER_DIV2
        , brpDIV2   = LL_SPI_BAUDRATEPRESCALER_DIV4
        , brpMAX    = LL_SPI_BAUDRATEPRESCALER_DIV256
    };
    unsigned brp = brp2;
    clk_limit    = 1;
    for (; brp < brpMAX; brp+= brpDIV2 , fssp = fssp >> 1)
    {
        if (fhz > fssp)
            break;
        clk_limit = clk_limit<<1;
    }

    LL_SPI_SetBaudRatePrescaler(io, brp );
    fsck_hz = fssp;
    return fsck_hz;
}




//  chip specific perifery
#ifdef STM32F446xx
const GPIOFUNC_INIT SSP1B_GPIO = {
     struct_field(GPIO_PORT) GPIOB
   , struct_field(GPIO_PINS) (GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5)
   , struct_field(GPIO_FUNC) PORT_FUNC_AF5
};

const GPIOFUNC_INIT SSP2B_GPIO = {
     struct_field(GPIO_PORT) GPIOB
   , struct_field(GPIO_PINS) (GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15)
   , struct_field(GPIO_FUNC) PORT_FUNC_AF5
};
#elif STM32L152xx
const GPIOFUNC_INIT SSP2B_GPIO = {
     struct_field(GPIO_PORT) GPIOB
   , struct_field(GPIO_PINS) (GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15)
   , struct_field(GPIO_FUNC) PORT_FUNC_AF5
};
#endif
