/*
 * 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);
    RCC_EnableClock_APB(iox);
    return DEV_OK;
}

    //  тактирование от системного клока требует прескалера, и мы его используем
DevResult   TIMER_Device::cfg_internalCLK(unsigned prescale){
    LL_TIM_SetClockSource(iox, LL_TIM_CLOCKSOURCE_INTERNAL);
    LL_TIM_SetPrescaler(iox, prescale );
    return DEV_OK;
}

DevResult   TIMER_Device::cfg_source(SourceID x){
    uint32_t src = LL_TIM_CLOCKSOURCE_INTERNAL;
    switch(x){
    case srcPCLK   :
        LL_TIM_SetClockSource(iox, LL_TIM_CLOCKSOURCE_INTERNAL);
        return DEV_OK;

    case srcTI0 :
    case srcTI1 :
    case srcTI2 :
    case srcTI3 :
        src = (x - srcTI0)<<(POSITION_VAL(LL_TIM_TS_ITR0));
        break;

    case srcIN1EDGE:
    case srcIN1:
    case srcIN2:
        src = (x - srcTI0)<<(POSITION_VAL(LL_TIM_TS_ITR0));
        break;

    default: return DEV_NOT_IMPLEMENTED;
    };//switch(x)

    LL_TIM_SetTriggerInput(iox, src );
    LL_TIM_SetClockSource(iox, LL_TIM_CLOCKSOURCE_EXT_MODE1);
    return DEV_OK;
}

DevResult   TIMER_Device::cfg_trigger(SourceID x){
    uint32_t src = LL_TIM_CLOCKSOURCE_INTERNAL;
    switch(x){    
    case srcTI0 :
    case srcTI1 :
    case srcTI2 :
    case srcTI3 :
        src = (x - srcTI0)<<(POSITION_VAL(LL_TIM_TS_ITR0));        
        break;

    case srcIN1EDGE: src = LL_TIM_TS_TI1F_ED; break;
    case srcIN1:    src = LL_TIM_TS_TI1FP1; break;
    case srcIN2:    src = LL_TIM_TS_TI2FP2; break;

    default: return DEV_NOT_IMPLEMENTED;
    };//switch(x)

    LL_TIM_SetTriggerInput(iox, src );
    return DEV_OK;
}

DevResult TIMER_Device::input_select(chanel_id ch, input_mode_t mode){
    unsigned sel = (mode & icsCH_Msk);
    switch (sel){
        case icsCH1:
            if (ch == 0)
                sel = icsCHSame;
            else if (ch == 1)
                sel = icsCHAlter;
            else
                return DEV_NOT_IMPLEMENTED;
            break;

        case icsCH2:
            if (ch == 1)
                sel = icsCHSame;
            else if (ch == 0)
                sel = icsCHAlter;
            else
                return DEV_NOT_IMPLEMENTED;
            break;

        case icsCH3:
            if (ch == 2)
                sel = icsCHSame;
            else if (ch == 3)
                sel = icsCHAlter;
            else
                return DEV_NOT_IMPLEMENTED;
            break;

        case icsCH4:
            if (ch == 3)
                sel = icsCHSame;
            else if (ch == 2)
                sel = icsCHAlter;
            else
                return DEV_NOT_IMPLEMENTED;
            break;


        default:
            sel = mode & icsSel_Msk;
            break;
    }; //switch (sel)

    u32 chsel = LL_TIM_CHANNEL_CH1 << (ch*4);
    unsigned front = mode & icsFront_Msk;

    LL_TIM_IC_SetPolarity(iox, chsel, front);
    switch (sel){
        case icsNone:       return DEV_OK;
        case icsCHSame:     sel = LL_TIM_ACTIVEINPUT_DIRECTTI; break;
        case icsCHAlter:    sel = LL_TIM_ACTIVEINPUT_INDIRECTTI; break;
        case icsTrigger:    sel = LL_TIM_ACTIVEINPUT_TRC; break;
        default:
            return DEV_NOT_IMPLEMENTED;
    }
    LL_TIM_IC_SetActiveInput(iox, chsel, sel);
    return DEV_OK;
}


DevResult TIMER_Device::cfg_slave(SlaveModeID x){
    uint32_t mode = x;
    LL_TIM_SetSlaveMode(iox, mode);
    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 = LL_TIM_COUNTERMODE_UP;              break;
    case modeDOWN:  m = LL_TIM_COUNTERMODE_DOWN;            break;
    case modeSWEEP: m = LL_TIM_COUNTERMODE_CENTER_UP_DOWN;  break;
    default : return DEV_NOT_IMPLEMENTED;
    };
    LL_TIM_SetCounterMode(iox, m);
    TIM_SetAutoReload(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);

    if ( (mode & compUPDATE_PRELOAD)!= 0 )
        compare_mode_preload(chanel, true );
    compare(chanel, value);

    return compare_mode(chanel, mode);
}

// вкл/выкл  бит OCxPE - preload enable, для соответствующего канала
void TIMER_Device::compare_mode_preload(chanel_id ch, bool onoff){
    //u32 chsel = LL_TIM_CHANNEL_CH1 << (ch*4);
    // LL_TIM_OC_EnablePreload(iox, chsel);

    __IO uint32_t* ioreg = (&iox->CCMR1)+ ch/2;
    ch = ch%2;
    unsigned cmd = TIM_CCMR1_OC1PE << (ch*8);
    if (onoff)
        *ioreg |= cmd;
    else
        *ioreg &= ~cmd;
}

DevResult  TIMER_Device::compare_mode(chanel_id ch, chanel_mode_t mode){
    u32 ref_mode;
    switch( mode & compMASK){
    case compOFF:           ref_mode = LL_TIM_OCMODE_FROZEN; break;
    case compPULSE:         ref_mode = LL_TIM_OCMODE_ACTIVE; break;
    case compPULSENEG:      ref_mode = LL_TIM_OCMODE_INACTIVE; break;
    case compTWIST:         ref_mode = LL_TIM_OCMODE_TOGGLE; break;
    case compFASTPWM:       ref_mode = LL_TIM_OCMODE_PWM1; break;
    case compFASTPWMNEG:    ref_mode = LL_TIM_OCMODE_PWM2; break;
    default: return DEV_NOT_IMPLEMENTED;
    };
    u32 chsel = LL_TIM_CHANNEL_CH1 << (ch*4);
    LL_TIM_OC_SetMode(iox, chsel, ref_mode);
    bool use_preload = ( (mode & compUPDATE_PRELOAD)!= 0 );
    compare_mode_preload(ch, use_preload );
    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){
    TIM_SetCHCompare(iox, chanel, x);
}

void TIMER_Device::IRQ(){
    u32 status = TIM_STATUS(iox);
    status  &= TIM_IE(iox);

    if (on_period != NULL){
        const u32 period_events = LL_TIM_DIER_UIE | LL_TIM_DIER_TIE;
        if ((status & period_events)!= 0)
            on_period(this);
    }
    if (on_compare != NULL){
        const u32 compare_events = LL_TIM_DIER_CC1IE | LL_TIM_DIER_CC3IE
                                 | LL_TIM_DIER_CC3IE | LL_TIM_DIER_CC4IE;
        unsigned events = status & compare_events;
        if (events != 0)
            on_compare(this, events);
    }

    //сброс обработанных событий
    TIM_STATUS(iox) = ~status;
}



//--------------------------------------------------------------------------
#include "mcu_gpio.h"

const GPIOFUNC_INIT     TIM9_IN1_GPIOE = PINFUNC_DEF(GPIOE, GPIO_PIN_5, PORT_FUNC_AF3);
const GPIOFUNC_INIT     TIM9_IN2_GPIOE = PINFUNC_DEF(GPIOE, GPIO_PIN_6, PORT_FUNC_AF3);
const GPIOFUNC_INIT     TIM9_IN1_GPIOA = PINFUNC_DEF(GPIOE, GPIO_PIN_2, PORT_FUNC_AF3);
const GPIOFUNC_INIT     TIM9_IN2_GPIOA = PINFUNC_DEF(GPIOE, GPIO_PIN_3, PORT_FUNC_AF3);


