#include "sr_config.h"
#include "ring_buff.h"
#include "stdio.h"


#ifdef SR_USE_OS
#include <luat_rtos.h>
luat_rtos_mutex_t bufMutex;

#endif

RingBuff stRingBuff;

uint8_t ringBuff[RINGBUFF_LEN];




//环形FIFO初始为空队列
void RingBuff_Init(void)
{
  stRingBuff.head=0;
  stRingBuff.tail=0;
  stRingBuff.bufflen=0;
  stRingBuff.recflag=0;
  stRingBuff.pre_readlen=0;
  stRingBuff.pbuff = ringBuff;

#ifdef SR_USE_OS
  luat_rtos_mutex_create(bufMutex);
#endif

}

//写成功 return:0
uint8_t Write_RingBuff(uint8_t data)
{
  uint16_t ret=1;

#ifdef SR_USE_OS 
  luat_rtos_mutex_lock(bufMutex, LUAT_WAIT_FOREVER);
#endif

  if(stRingBuff.bufflen>=RINGBUFF_LEN)  //FIFO已满
  { 
   #if DATE_COVERAGE
       stRingBuff.head=(stRingBuff.head+1)%RINGBUFF_LEN;  //覆盖
       stRingBuff.bufflen--;
   #else
     
      ret = 0;   //不覆盖
      goto _end;
   #endif
  }
  stRingBuff.pbuff[stRingBuff.tail]=data;
  stRingBuff.tail=(stRingBuff.tail+1)%RINGBUFF_LEN; //防止非法越界
  stRingBuff.bufflen++;

_end:
#ifdef SR_USE_OS
  luat_rtos_mutex_unlock(bufMutex);
#endif

  return ret; 
}

uint8_t Read_RingBuff(uint8_t *rData)
{
  uint16_t ret=1;

#ifdef SR_USE_OS  
  luat_rtos_mutex_lock(bufMutex, LUAT_WAIT_FOREVER);
#endif

  if(stRingBuff.bufflen==0)  
  {
   ret = 0; //判断FIFO非空
   goto _end;
  }
  
  *rData=stRingBuff.pbuff[stRingBuff.head];
  stRingBuff.head=(stRingBuff.head+1)%RINGBUFF_LEN;
  stRingBuff.bufflen--;

_end:
#ifdef SR_USE_OS
  luat_rtos_mutex_unlock(bufMutex);
#endif

  return ret;
}

uint16_t RingbuffGetDataLen(void)
{
  return stRingBuff.bufflen;
}

void RingBuff_Process(void)
{
  uint16_t i;
  uint8_t rec[100];
  
  if(stRingBuff.recflag)
  {
   if(stRingBuff.recflag++>2) //收到一帧数据
   { 
    stRingBuff.recflag=0;  
    
    stRingBuff.pre_readlen=stRingBuff.bufflen;
    for(i=0;i<stRingBuff.pre_readlen;i++)  Read_RingBuff(&rec[i]);
    rec[i]=0;
    
    for(i=0;i<stRingBuff.pre_readlen;i++) printf("%x ",rec[i]);
    printf("\n");
   }
  }
}



