/*
 * tim_device.cpp
 *
 *  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. *
 */

#include <cassert>
#include "tim_device.hpp"
#include "mcu_rcc.h"
#include "cslr.h"
#include <system.h>

#if 1
#define ASSERT_TIM(...) assert(__VA_ARGS__)
#else
#define ASSERT_TIM(...)
#endif

TIMER_Device::TIMER_Device()
:iox(NULL), cfg(NULL)
{}


DevResult  TIMER_Device::connect(const DEV_INIT& mode){
    iox = mode.timer;
    cfg = &mode;
    return init();
}

DevResult  TIMER_Device::init(){
    ASSERT_TIM(cfg!=NULL);
    ASSERT_TIM(iox!=NULL);
    if (cfg->NVIC_Init.NVIC_IRQChannel >= 0)
        NVIC_Init(&cfg->NVIC_Init);
    RST_CLK_PCLKcmd(cfg->rcc , ENABLE);
    TIMER_BRGInit(iox, cfg->PCLKDiv);
    return DEV_OK;
}

    //  тактирование от системного клока требует прескалера, и мы его используем
DevResult   TIMER_Device::cfg_internalCLK(unsigned prescale){
    TIMER_CntEventSourceConfig(iox, TIMER_EvSrc_None);
    TIMER_SetCntPrescaler(iox, (prescale >> (cfg->PCLKDiv)) );
    return DEV_OK;
}

DevResult   TIMER_Device::cfg_source(SourceID x){
    uint32_t src = TIMER_EvSrc_None;
    switch(x){
    case srcPCLK   : src = TIMER_EvSrc_None; break;
    case srcTIMER1 : src = TIMER_EvSrc_TM1; break;
    case srcTIMER2 : src = TIMER_EvSrc_TM2; break;
    case srcTIMER3 : src = TIMER_EvSrc_TM3; break;
    default: return DEV_NOT_IMPLEMENTED;
    }
    TIMER_CntEventSourceConfig(iox, src);
    return DEV_OK;
}

DevResult   TIMER_Device::set_period(unsigned period, unsigned mode){
    ASSERT_TIM(period_limit > period);
    uint32_t m = 0;
    // режимы Up,Dn,Sweep выставляют поля DIR и CNT_MODE
    switch (mode){
    case modeUP:    m = TIMER_CntMode_ClkFixedDir | TIMER_CntDir_Up; break;
    case modeDOWN:  m = TIMER_CntMode_ClkFixedDir | TIMER_CntDir_Dn; break;
    case modeSWEEP: m = TIMER_CntMode_ClkChangeDir; break;
    default : return DEV_NOT_IMPLEMENTED;
    };
    // если тактируемся не от HCLK, а от других событий, надо выбирать режим
    //      тактирования от событий: CntMode_ClkXXX
    const uint32_t TIMER_CntMode_Event = TIMER_CntMode_EvtFixedDir;
    if (CSL_FEXT(iox->CNTRL, TIMER_CNTRL_EVENT_SEL) != TIMER_CNTRL_EVENT_SEL_TIM_CLK )
        m |= TIMER_CntMode_Event;
    const u32  TIMER_MODE_Msk = TIMER_CNTRL_CNT_MODE_Msk | TIMER_CNTRL_DIR;
    iox->CNTRL = (iox->CNTRL & ~TIMER_MODE_Msk) | m;
    TIMER_SetCntAutoreload(iox, period);
    return DEV_OK;
}

DevResult   TIMER_Device::set_compare(unsigned chanel, unsigned value, unsigned mode){
    ASSERT_TIM(period_limit > value);
    ASSERT_TIM(comp_chanels > chanel);

    u32   tmpreg = *(&iox->CH1_CNTRL2 + chanel);
    if ((mode & compUPDATE_ZERO)!= 0)
        tmpreg |= TIMER_CH_CCR_Update_On_CNT_eq_0;
    else
        tmpreg &= ~TIMER_CH_CCR_Update_On_CNT_eq_0;
    *(&iox->CH1_CNTRL2 + chanel) = tmpreg;

    compare(chanel, value);

    return compare_mode(chanel, mode);
}

DevResult  TIMER_Device::compare_mode(chanel_id ch, chanel_mode_t mode){
    u32 ref_mode;
    switch( mode & compMASK){
    case compOFF:           ref_mode = TIMER_CH_CNTRL_OCCM_REF_0; break;
    case compPULSE:         ref_mode = TIMER_CH_CNTRL_OCCM_REF_1_CNT_CCR; break;
    case compPULSENEG:      ref_mode = TIMER_CH_CNTRL_OCCM_REF_0_CNT_CCR; break;
    case compTWIST:         ref_mode = TIMER_CH_CNTRL_OCCM_SW_REF_CNT_CCR; break;
    case compFASTPWM:       ref_mode = TIMER_CH_CNTRL_OCCM_REF_1_DIR_0_CNT_CCR; break;
    case compFASTPWMNEG:    ref_mode = TIMER_CH_CNTRL_OCCM_REF_0_DIR_0_CNT_CCR; break;
    default: return DEV_NOT_IMPLEMENTED;
    };
    CSL_FINS( *(&iox->CH1_CNTRL+ch), TIMER_CH_CNTRL_OCCM, ref_mode);
    return DEV_OK;
}

// содержимое компаратора
unsigned    TIMER_Device::compare(unsigned chanel) const{
    ASSERT_TIM(comp_chanels > chanel);
    return *(&iox->CCR1 + chanel);
}

void        TIMER_Device::compare(unsigned chanel, unsigned x){
    TIMER_SetChnCompare(iox, chanel, x);
}

void TIMER_Device::IRQ(){
    u32 status = (iox->STATUS & iox->IE);

    if (on_period != NULL){
        const u32 period_events = TIMER_STATUS_CNT_ZERO | TIMER_STATUS_CNT_ARR;
        if ((status & period_events)!= 0)
            on_period(this);
    }
    if (on_compare != NULL){
        unsigned events = CSL_FEXT(status, TIMER_STATUS_CCR_REF_EVENT);
        if (events != 0)
            on_compare(this, events);
    }

    //сброс обработанных событий
    iox->STATUS = ~status;
}


