/*
 * FreeModbus Libary: CMSIS-RTOS2 Port
 * Copyright (C) 2013 Armink <armink.ztl@gmail.com>
 *
 * 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.60 2013/08/13 15:07:05 Armink $
 *            porttimer.c,v 1.60 2022/07/17          quanghona <lyhonquang@gmail.com> CMSIS-RTOS2 port $
 */

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"
#include "cmsis_os2.h"

/* ----------------------- Modbus includes ----------------------------------*/
#include "FreeRTOS.h"
#include "mbport.h"
#include "timers.h"
#include "tim.h"

// 使用软定时器
// #define  USE_SOFT_TIMER

/* ----------------------- static functions ---------------------------------*/
static TimerHandle_t xTimerId;
static uint32_t ulTimeout;

void prvvTIMERExpiredISR(eMBRTUSlaveObj * pObj);


/* ----------------------- Start implementation -----------------------------*/
BOOL xMBPortTimersInit(USHORT usTim1Timerout50us, TIM_HandleTypeDef def) {
#ifdef USE_SOFT_TIMER
    ulTimeout = 50 * usTim1Timerout50us * osKernelGetTickFreq() / 1000000 + 1;
    xTimerId = osTimerNew(prvvTIMERExpiredISR, osTimerOnce, NULL, NULL);
    return xTimerId != NULL;
#else
    return TRUE;
#endif
}

void vMBPortTimersEnable(eMBRTUSlaveObj * pObj) {
#ifdef USE_SOFT_TIMER
    osTimerStart(xTimerId, ulTimeout);
#else
    __HAL_TIM_CLEAR_IT(&pObj->pTimHandle,TIM_IT_UPDATE);
    __HAL_TIM_ENABLE_IT(&pObj->pTimHandle,TIM_IT_UPDATE);
    __HAL_TIM_SET_COUNTER(&pObj->pTimHandle,0);
    __HAL_TIM_ENABLE(&pObj->pTimHandle);
#endif
}

void vMBPortTimersDisable(eMBRTUSlaveObj * pObj) {
#ifdef USE_SOFT_TIMER

    osTimerStop(xTimerId);
#else
    __HAL_TIM_DISABLE(&pObj->pTimHandle);
__HAL_TIM_SET_COUNTER(&pObj->pTimHandle, 0);
__HAL_TIM_DISABLE_IT(&pObj->pTimHandle, TIM_IT_UPDATE);
__HAL_TIM_CLEAR_IT(&pObj->pTimHandle, TIM_IT_UPDATE);
#endif
}

void prvvTIMERExpiredISR(eMBRTUSlaveObj *obj) {
    (void) pxMBPortCBTimerExpired(obj);
}
