/*
 * FreeModbus Libary: BARE Port
 * Copyright (C) 2006 Christian Walter <wolti@sil.at>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * File: $Id: porttimer.c,v 1.1 2015/12/02 21:57:35 mrisi Exp $
 */

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"
#include "sys_defs.h"

/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"

/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortTimersInit( USHORT usTim1Timerout50us )
{
   double usec_timeout;
   double usec_per_tick;

   /* you should never have a timeout less than a millisecond */
   if ( usTim1Timerout50us < 20)
      return FALSE;

   /* make sure the timeout timer is disabled */
   vMBPortTimersDisable();

   /* calculate the timeout and usec per tick */
   usec_timeout = 50.0 * usTim1Timerout50us;
   usec_per_tick = 1000000.0 / ((double)(FCY));

   /* set timer1 control reg to defaults */
   T1CON = 0x0000;
   /* load the timer1 period register */
   PR1 = (unsigned int)(usec_timeout / usec_per_tick);;  
   /* clear timer1 counts */
   TMR1 = 0;

   /* enable the timer interrupt*/
   _T1IF = 0;
   _T1IE = 1;

   return TRUE;
}


inline void
vMBPortTimersEnable(  )
{
   /* clear timer count */
   TMR1 = 0;

   /* start timer */
   _TON = 1;
}

inline void
vMBPortTimersDisable(  )
{
   ENTER_CRITICAL_SECTION();

   /* stop timer */
   _TON = 0;

   /* clear interrupt flag just in case
   it fired in this critical section */
   _T1IF = 0;

   EXIT_CRITICAL_SECTION();
}

/* Create an ISR which is called whenever the timer has expired. This function
 * must then call pxMBPortCBTimerExpired( ) to notify the protocol stack that
 * the timer has expired.
 */

void __attribute__ ((interrupt,no_auto_psv)) _T1Interrupt(void)
{
   /* clear int flag */
   _T1IF = 0;
   /* notify the stack the timer has expired */
#if 1
   pxMBPortCBTimerExpired();
#else
   /* toggle blinky for timer testing purposes*/
   if ( _LATB5 )
   {
       Nop();
       _LATB5 = 0;
   }
   else
   {
       Nop();
       _LATB5 = 1;
   }
#endif
}

