/*
 * ssp_device.hpp
 *
 *  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. *
 */

#ifndef HAL_STM32F4_SPI_DEVICE_HPP_
#define HAL_STM32F4_SPI_DEVICE_HPP_


#include <ssp_hal.hpp>
#include "gpiosw_device.hpp"
#include <mcu_ssp.h>
#include <mcu_gpio.h>
#include <mcu_nvic.h>


// этот прокси делает блокирующую запись/чтение в порт СПИ данных сообщения
//  без поддержки буферирования на прерываниях, или ДМА.
class SSP_SWMasterProxy
        : public SSP_Device
        , public HAL_Device
{
public:
    typedef SSP_Device inherited;
    typedef HAL_Device nameddev_t;

    typedef PIN_INIT CSPIN_INIT;
    struct SSP_INIT {
        SSP_TypeDef*            port;
        const GPIOFUNC_INIT*    GPIOPINS;
        NVIC_InitTypeDef        nvic;
        const CSPIN_INIT*       cspins;
    };

    SSP_SWMasterProxy(dev_name name);

    int init( const SSP_INIT* cfg);

    // SSP_Device
    virtual DevResult init();
    virtual DevResult deinit();

    virtual DevResult trx(Message& msg);

    // BUS lock access
    virtual PTResult aquire(unsigned cs_id);
    virtual DevResult release();

public:
    // настройка порта под параметры внеочередная !!! - эти методы нельзя
    //      вызывать на работающем порте. нужно убедиться что порт неактивен
    DevResult setup_mode(unsigned mode);
    DevResult setup_byte();
    DevResult setup_word();
    DevResult setup_port(const Message* msg);

    //return > 0  - возвращает точное установленное значение
    //       <= 0  - код ошибки DevResult
    int setup_freq(unsigned fhz);

    // это прямое управление линиями селектора чипа.
    DevResult cs_select(unsigned csid);
    DevResult cs_select();
    void      cs_release(){
        css.select(css.selNONE);
    }

protected:
    const SSP_INIT*     cfg;
    SSP_TypeDef*        io;
    GPIOSwitch_Device   css;
    //ExclusiveCheck      access;
    Message*            msg;
    // актуальная частота SCK
    unsigned            fsck_hz;
    // актуальный режим порта
    u32                 ssp_mode;
    // максимальная длительность поллинга приема байта
    uint_fast16_t       clk_limit;

    void transfer8(Message& mesg);
    void transfer16(Message& mesg);
    void wait_port_empty();
    void wait_port_notfull();
    void drop_port_rx();

};



extern const GPIOFUNC_INIT     SSP1B_GPIO;
extern const GPIOFUNC_INIT     SSP2B_GPIO;

#endif /* HAL_MDR32F9QX_SSP_DEVICE_HPP_ */
