/**
 * @file hv_vos_Semaphore.c
 * @brief vos Semaphore source code
 * @details 
 * @author HiView SoC Software Team
 * @version 0.0.1
 * @date 20230301
 * @copyright Copyright(c),2023-3, Hiview Software. All rights reserved.
 * @par History: 
 * <table>
 * <tr><th>author                     <th>date           <th>description
 * <tr><td>HiView SoC Software Team   <td>20230301       <td>Create and first Version.
 * </table>
**/

#include "hv_vos_Comm.h"
#include "FreeRTOS.h"
#include "semphr.h"


struct _HV_VOS_SEMAPHORE_S
{
    QueueHandle_t handler;
};

HV_VOS_SEMAPHORE_S *Hv_Vos_InitSemaphore(int maxCount, int initialCount)
{

    HV_VOS_SEMAPHORE_S *self = NULL;
    self = HV_MALLOC_OBJECT(HV_VOS_SEMAPHORE_S);
    self->handler = xSemaphoreCreateCounting(maxCount, initialCount); 
    if (self->handler == NULL)
    {
        HV_FREE_OBJECT(self);
        self = NULL;
    }
    return self;
}

BOOL Hv_Vos_AcquireSemaphore(HV_VOS_SEMAPHORE_S *self)
{
    UINT32 ret = xSemaphoreTake(self->handler, portMAX_DELAY);
    return ret == pdPASS;
}


BOOL Hv_Vos_TimedAcquireSemaphore(HV_VOS_SEMAPHORE_S *self,UINT32 timeoutMs)
{
    UINT32 ret = xSemaphoreTake(self->handler, pdMS_TO_TICKS(timeoutMs));
    return ret == pdPASS;
}


BOOL Hv_Vos_ReleaseSemaphore(HV_VOS_SEMAPHORE_S *self)
{    
    return xSemaphoreGive( self->handler ) == pdPASS;
}

BOOL Hv_Vos_ReleaseSemaphoreFromISR(HV_VOS_SEMAPHORE_S *self)
{
    BaseType_t xHigherPriorityTaskWoken = pdHV_FALSE;
    UINT32 ret = xSemaphoreGiveFromISR( self->handler, &xHigherPriorityTaskWoken); 
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
    return  ret== pdPASS;
}


void Hv_Vos_CleanupSemaphore(HV_VOS_SEMAPHORE_S *self)
{
    vSemaphoreDelete(self->handler);
    HV_FREE_OBJECT(self);
}

