/*
 * rtimer_agt.c
 *
 *  Created on: 16/04/2021.
 *      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. *
  ------------------------------------------------------------------------
    this is implementation of rtimer at AGT0 for ContikiOS
 */

#include "mcu_tim.h"
#include "mcu_nvic.h"
#include <mcu_isr.h>
#include <project-conf.h>
#include <board.h>

//#include "bsp_irq.h"
#include "bsp_api.h"

#include <sys/rtimer.h>
//#include "rtimer-arch-agt.h"
#include "rtimer_agt.h"



/////////////////////////////////////////////////////////////////////////////////////////////////
#if 1
#include <assert.h>
#define ASSERT(...) assert(__VA_ARGS__);
#else
#define ASSERT(...)
#endif



//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <trace_probes.h>

#ifndef trace_rtc_delay
trace_need(rtc_delay);
trace_need(rtc_miss);
#endif



/////////////////////////////////////////////////////////////////////////////////
#define RTIMER_TIMn 0
#define RTIMER_TIM  R_AGT0

#ifndef RTIMER_AGT_PRI
#define RTIMER_AGT_PRI    1
#endif




#ifdef RTIMER_AGT_SCLK_HZ

    #define RTIMER_AGT_DIV  (RTIMER_AGT_SCLK_HZ / RTIMER_AGT_SECOND)

    #if RTIMER_AGT_SCLK_HZ % RTIMER_SECOND
    #error  RTIMER_AGT_SCLK_HZ not careful divides to RTIMER_AGT_SECOND
    #endif

#elif defined(RTIMER_AGT_LCLK_HZ)
    #define RTIMER_AGT_DIV  (RTIMER_AGT_LCLK_HZ / RTIMER_AGT_SECOND)

    #if RTIMER_AGT_LCLK_HZ % RTIMER_SECOND
    #error  RTIMER_AGT_LCLK_HZ not careful divides to RTIMER_AGT_SECOND
    #endif
#elif defined(RTIMER_AGT_CLK_HZ)
    #define RTIMER_AGT_BDIV  (RTIMER_AGT_CLK_HZ / RTIMER_AGT_SECOND)

    #if RTIMER_AGT_CLK_HZ % RTIMER_AGT_SECOND
    #error  RTIMER_AGT_CLK_HZ not careful divides to RTIMER_AGT_SECOND
    #endif
#elif RTIMER_AGT_SECOND == (BSP_STARTUP_PCLKB_HZ/8)
    #define RTIMER_AGT_BDIV  8
#elif RTIMER_AGT_SECOND == (BSP_STARTUP_PCLKB_HZ/2)
#define RTIMER_AGT_BDIV  2
#elif RTIMER_AGT_SECOND == (BSP_STARTUP_PCLKB_HZ)
#define RTIMER_AGT_BDIV  1
#else
    #define RTIMER_AGT_LCLK_HZ BSP_LOCO_FREQ_HZ

    #define RTIMER_AGT_DIV  (RTIMER_AGT_LCLK_HZ / RTIMER_AGT_SECOND)

    #if RTIMER_AGT_LCLK_HZ % RTIMER_SECOND
    #error  RTIMER_AGT_LCLK_HZ not careful divides to RTIMER_AGT_SECOND
    #endif
#endif



void rtimer_agt_init(void){
    TIM_InitTypeDef ini = {
       .mode        = AGT_MODE_TIMER | AGT_SRC_PCLKB,
       .clockdiv    = AGTPrescale1,
    };

#if defined(RTIMER_AGT_BDIV)
    unsigned div = FSYSTICK_HZ / RTIMER_AGT_SECOND;
    ASSERT( (FSYSTICK_HZ % RTIMER_AGT_SECOND) == 0 );
    switch(div){
        case 1: break;
        case 2: ini.mode = AGT_MODE_TIMER | AGT_SRC_PCLKB2; break;
        case 8: ini.mode = AGT_MODE_TIMER | AGT_SRC_PCLKB8; break;
        default:
            ASSERT( 0 );
    }
    div = 1;

#elif defined(RTIMER_AGT_DIV)
    unsigned div = RTIMER_AGT_DIV;
#else
    unsigned div = FSYSTICK_HZ / RTIMER_AGT_SECOND;
    ASSERT( (FSYSTICK_HZ % RTIMER_AGT_SECOND) == 0 );
#endif

    ASSERT( div > 0 );
    // check that is single bit
    ASSERT( IS_POW2(div) );
    uint8_t div2 = ctz(div);
    ASSERT( div2 <= AGTPrescaleTOP );
    ini.clockdiv = div2;


    TIM_Init(RTIMER_TIM, ini);

    const NVIC_InitTypeDef ovf_irqdef = NVIC_DEF( TIMn_IRQ(RTIMER_TIMn), 1, 0, ENABLE);
    nvic_init( ovf_irqdef );

    TIM_IE_enable(RTIMER_TIM, TIM_IE_OCA);
}



///////////////////////////////////////////////////////////////////////////////////////
/**
 * Schedule the call to `rtimer_run_next` at the time t.
 */

#define TRACE_AGT0 1
#if TRACE_AGT0
uint32_t   agtA_start;
uint32_t   agtA_plan;
uint32_t   agtA_end;
#endif

void rtimer_agt_schedule(rtimer_clock_t rt){
    arch_state_t is = gie_disable();

    rtimer_clock_t now = RTIMER_NOW();
    uint32_t t = RTIMER_TO_AGTTICKS( rt - now );

    if (t > AGT_MINIMAL_SAFE_SCHEDULE){
#if TRACE_AGT0
        agtA_start = RTIMER_NOW();
        agtA_plan  = rt;
#endif

        if (t > 4000)
            trace_rtc_miss_twist();

        if (t > 0x10000)
            t = 0x10000;

        TIM_SetAutoReload(RTIMER_TIM, t-1);

        // AGT timer counts down
        R_BSP_IrqClearPending( TIMn_IRQ(RTIMER_TIMn) );
        trace_rtc_delay_on();
        TIM_enable(RTIMER_TIM);
    }
    else {
#ifdef RTIMER_AGT_EXEC0
        RTIMER_AGT_EXEC0();
#else
        rtimer_run_next();
#endif
    }

    gie_restore(is);
}



#ifdef RTIMER_AGT_EXEC0
void RTIMER_AGT_EXEC0( void );
#endif



void rtc_atg0_isr(void){
    TIM_stop(RTIMER_TIM);
#if TRACE_AGT0
    agtA_end = RTIMER_NOW();
    if ( (agtA_end - agtA_plan) > US_TO_RTIMERTICKS(100) ){
        trace_rtc_miss_twist();
    }
#endif

    trace_rtc_delay_off();
    TIM_IF_clear(RTIMER_TIM, TIM_IF_ZERO);

    //IRQn_Type irq = R_FSP_CurrentIrqGet();
    /* Clear pending IRQ to make sure it doesn't fire again after exiting */
    R_BSP_IrqStatusClear(TIMn_IRQ(RTIMER_TIMn));

#ifdef RTIMER_AGT_EXEC0
    RTIMER_AGT_EXEC0();
#else
    rtimer_run_next();
#endif
}
