/*
 * tim_device.hpp
 *
 *  Created on: 28 нояб. 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. *
 *-----------------------------------------------------------------
 * реализация менеджера таймера на ВЕ94Т
 */

#ifndef HAL_MDR32F9QX_TIM_DEVICE_HPP_
#define HAL_MDR32F9QX_TIM_DEVICE_HPP_

#include <timer_hal.hpp>
#include <mcu_tim.h>
#include <mcu_nvic.h>

class TIMER_Device
        : public TIM_Device
{
public:
    //typedef TIM_Device  inherited;
    typedef TIM_TypeDef io_t;
    struct DEV_INIT{
        io_t*               timer;
        u32                 rcc;
        NVIC_InitTypeDef    NVIC_Init;
        // делитель частоты периферии счетчику
        u8                  PCLKDiv;
    };

    TIMER_Device();


    DevResult   connect(const DEV_INIT& mode);
    io_t*       io() const {return iox;}

public:
    DevResult   init();

    DevResult enable(bool onoff){
        TIM_Cmd(iox, (onoff)?ENABLE:DISABLE);
        return DEV_OK;
    };
    bool is_enabled() const{
        return (iox->CNTRL & TIMER_CNTRL_CNT_EN) != 0;
    }

    enum Limits{
          prescale_limit = 0x10000u
        , period_max    = 0xffffu
        , period_limit  = period_max+1
        , width         = 16
        , comp_chanels  = 4
    };

    //  тактирование от системного клока требует прескалера, и мы его используем
    DevResult   cfg_internalCLK(unsigned prescale);
    DevResult   cfg_source(SourceID x);
    DevResult   set_period(unsigned period, timer_mode_t mode);
    // содержимое счетчика
    unsigned    value() const{return iox->CNT;};
    void        value(unsigned x) {iox->CNT = x;};
    // содержимое регистра перезагрузки
    unsigned    period() const {return iox->ARR;};
    void        period(unsigned x) {iox->ARR = x;};

    enum /*CompareModeID*/{
          compMASK = 0x7
        , compUPDATE_ZERO   = 8, compUPDATE_NOW    = 0
    };

    DevResult   set_compare(chanel_id chanel, unsigned value, chanel_mode_t mode);
    // содержимое компаратора
    unsigned    compare(chanel_id chanel) const;
    void        compare(chanel_id chanel, unsigned x);
    DevResult   compare_mode(chanel_id ch, chanel_mode_t mode);

    enum /*IRQId*/{
          irqNONE   = 0
        , irqZERO   = 1
        , irqRELOAD = 2

        // прерывания событий от компараторов
        , irqOC1    = 0x200
        , irqOC2    = 0x400
        , irqOC3    = 0x800
        , irqOC4    = 0x1000
        , irqOC_Msk = 0x1e00, irqOC_Pos = 9
    };
    // \arg mode - набор прерываний IRQId, зависит от локализации к железу
    inline
    DevResult    irq_enable(unsigned mode){
        iox->IE |= mode;
        return DEV_OK;
    };

    inline
    DevResult    irq_disable(unsigned mode){
        iox->IE &= ~mode;
        return DEV_OK;
    }

    // разрешение/запрещение прерывания NVIC таймера
    DevResult    irq_enable(){
        NVIC_EnableIRQ((IRQn_Type)cfg->NVIC_Init.NVIC_IRQChannel);
        return DEV_OK;
    };

    DevResult    irq_disable(){
        NVIC_DisableIRQ((IRQn_Type)cfg->NVIC_Init.NVIC_IRQChannel);
        return DEV_OK;
    };

public:
    // обработчик прерывания. Должен вызываться из процедуры обрботки прерывнаия таймера:
    /*
        TIMER_Device mytimer;
        extern "C" void TIM1_IRQHandler(void)
        {
            mytimer.IRQ();
        }
     *
     */
    void IRQ();
protected:
    io_t*           iox;
    const DEV_INIT* cfg;
    unsigned eval_period_us(unsigned us);
};



#endif /* HAL_MDR32F9QX_TIM_DEVICE_HPP_ */
