Beispiel #1
0
INT8U  OSTmrStateGet (OS_TMR  *ptmr,
                      INT8U   *perr)
{
    INT8U  state;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (0u);
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (0u);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {              /* Validate timer structure                                    */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (0u);
    }
    if (OSIntNesting > 0u) {                           /* See if trying to call from an ISR                           */
        *perr = OS_ERR_TMR_ISR;
        return (0u);
    }
    OSSchedLock();
    state = ptmr->OSTmrState;
    switch (state) {
        case OS_TMR_STATE_UNUSED:
        case OS_TMR_STATE_STOPPED:
        case OS_TMR_STATE_COMPLETED:
        case OS_TMR_STATE_RUNNING:
             *perr = OS_ERR_NONE;
             break;

        default:
             *perr = OS_ERR_TMR_INVALID_STATE;
             break;
    }
    OSSchedUnlock();
    return (state);
}
Beispiel #2
0
void delay_us(u32 us)//函数:微秒延迟
{
    u32 ticks;
	u32 told,tnow,tcnt=0;
	u32 reload = SysTick->LOAD;//LOAD的值
	ticks = us * us_each;//需要的节拍数
	OSSchedLock();//阻止ucos调度,防止打断us延时
	told = SysTick->VAL;//刚进入时的计数器值
	while(1){
	   tnow = SysTick->VAL;
	   if( tnow != told){
	      if( tnow < told) tcnt += told-tnow;//SYSTICK是一个递减的计数器
		  else tcnt += reload - tnow + told;
		  told = tnow;
		  if(tcnt >= ticks) break;//时间超过或等于要延迟的时间,则退出
	   }
	}
	OSSchedUnlock();//开启ucos任务调度
}
Beispiel #3
0
/***********************************************************************************************
 功能:US级延时函数
 形参:US 需要延时多少US
 返回:0
 详解:带操作系统下的延时US
************************************************************************************************/
void DelayUs(uint32_t us)
{  
	uint32_t temp;
	uint32_t told;
	told=SysTick->VAL;								//刚进入时的计数器值
	OSSchedLock();										//阻止ucos调度,防止打断us延时
	SysTick->CTRL&=~(1<<1);   				//关闭SYSTICK中断
	SysTick->LOAD=us*fac_us; 					//时间加载
	SysTick->VAL=0x00;  						  //清空计数器
	SysTick->CTRL|=1<<0	; 						//开始倒数   
	do
	{
		temp=SysTick->CTRL;
	}
	while(temp&0x01&&!(temp&(1<<16))); //等待时间到达   
	SysTick->LOAD=OS_ReloadValue;      //恢复OS 延时值
	SysTick->VAL=told;                 //恢复初值
	SysTick->CTRL|=1<<1;               //开启SYSTICK中断
	OSSchedUnlock();			             //开启ucos调度 								
}
Beispiel #4
0
/**
* @brief	通过USB HID发送条码
*/
static void barcode_hid_send(unsigned char* barcode)
{
	unsigned int	i,code_len;
	unsigned char key_value_report[8];

    code_len = strlen((char const*)barcode);
	OSSchedLock();
	for (i = 0; i < code_len; i++)
	{
		ascii_to_keyreport(barcode[i],key_value_report);

		SendData_To_PC(key_value_report, 3);
		SendData_To_PC("\x00\x00\x00", 3);
	}

	memcpy(key_value_report,"\x00\x00\x28",3);	//换行

	SendData_To_PC(key_value_report, 3);
	SendData_To_PC("\x00\x00\x00", 3);	//弹起
	OSSchedUnlock();
}
Beispiel #5
0
//延时nus
//nus为要延时的us数.		    								   
void delay_us(u32 nus)
{		
	u32 ticks;
	u32 told,tnow,tcnt=0;
	u32 reload=SysTick->LOAD;	//LOAD的值	    	 
	ticks=nus*fac_us; 			//需要的节拍数	  		 
	tcnt=0;
	OSSchedLock();				//阻止ucos调度,防止打断us延时
	told=SysTick->VAL;        	//刚进入时的计数器值
	while(1)
	{
		tnow=SysTick->VAL;	
		if(tnow!=told)
		{	    
			if(tnow<told)tcnt+=told-tnow;//这里注意一下SYSTICK是一个递减的计数器就可以了.
			else tcnt+=reload-tnow+told;	    
			told=tnow;
			if(tcnt>=ticks)break;//时间超过/等于要延迟的时间,则退出.
		}  
	};
	OSSchedUnlock();			//开启ucos调度 									    
}
Beispiel #6
0
static  void  OSTmr_Task (void *p_arg)
{
    INT8U            err;
    OS_TMR          *ptmr;
    OS_TMR          *ptmr_next;
    OS_TMR_CALLBACK  pfnct;
    OS_TMR_WHEEL    *pspoke;
    INT16U           spoke;


    p_arg = p_arg;                                               /* Prevent compiler warning for not using 'p_arg'    */
    for (;;) {
        OSSemPend(OSTmrSemSignal, 0u, &err);                     /* Wait for signal indicating time to update timers  */
        OSSchedLock();
        OSTmrTime++;                                             /* Increment the current time                        */
        spoke  = (INT16U)(OSTmrTime % OS_TMR_CFG_WHEEL_SIZE);    /* Position on current timer wheel entry             */
        pspoke = &OSTmrWheelTbl[spoke];
        ptmr   = pspoke->OSTmrFirst;
        while (ptmr != (OS_TMR *)0) {
            ptmr_next = (OS_TMR *)ptmr->OSTmrNext;               /* Point to next timer to update because current ... */
                                                                 /* ... timer could get unlinked from the wheel.      */
            if (OSTmrTime == ptmr->OSTmrMatch) {                 /* Process each timer that expires                   */
                OSTmr_Unlink(ptmr);                              /* Remove from current wheel spoke                   */
                if (ptmr->OSTmrOpt == OS_TMR_OPT_PERIODIC) {
                    OSTmr_Link(ptmr, OS_TMR_LINK_PERIODIC);      /* Recalculate new position of timer in wheel        */
                } else {
                    ptmr->OSTmrState = OS_TMR_STATE_COMPLETED;   /* Indicate that the timer has completed             */
                }
                pfnct = ptmr->OSTmrCallback;                     /* Execute callback function if available            */
                if (pfnct != (OS_TMR_CALLBACK)0) {
                    (*pfnct)((void *)ptmr, ptmr->OSTmrCallbackArg);
                }
            }
            ptmr = ptmr_next;
        }
        OSSchedUnlock();
    }
}
/*
 * This task is called once a second to update the LCD display with the 
 * current system time.  
 */
void lcddisplaytime_task(void *pdata)
{
  struct timeval time = {0, 0};
  struct timezone zone = {0, 0};
  struct tm time_struct;
  struct tm *pt_time_struct = &time_struct;
  alt_u8 char_array1[32];
  alt_u8 char_array2[32];
  INT8U  ucos_retcode = OS_NO_ERR;

  OSSemPend(lcd_sem, 0, &ucos_retcode);
    
  while(1)
  {

    OSSchedLock();
    if(gettimeofday(&time, &zone) < 0)
    {
      printf("Error get the time of day %s\n", strerror(errno));
      exit(0);
    }
    OSSchedUnlock();
  
    pt_time_struct = gmtime(&time.tv_sec);

    strftime(char_array1, 32, "%a %b %d,%Y", pt_time_struct);
    printf("DATE: %s\n", char_array1);
    
    strftime(char_array2, 32, "%I:%M:%S %p GMT", pt_time_struct);
    printf("TIME: %s\n", char_array2);

    OSSemPost(lcd_sem);

    OSTimeDlyHMSM(0,0,10,0);
  }
  
}
Beispiel #8
0
CPU_BOOLEAN  OSTmrStart (OS_TMR  *p_tmr,
                         OS_ERR  *p_err)
{
    OS_ERR  err;



#ifdef OS_SAFETY_CRITICAL
    if (p_err == (OS_ERR *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u
    if (OSIntNestingCtr > (OS_NESTING_CTR)0) {              /* See if trying to call from an ISR                      */
       *p_err = OS_ERR_TMR_ISR;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_ARG_CHK_EN > 0u
    if (p_tmr == (OS_TMR *)0) {
       *p_err = OS_ERR_TMR_INVALID;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_OBJ_TYPE_CHK_EN > 0u
    if (p_tmr->Type != OS_OBJ_TYPE_TMR) {                   /* Make sure timer was created                            */
       *p_err = OS_ERR_OBJ_TYPE;
        return (DEF_FALSE);
    }
#endif

    OSSchedLock(&err);
    switch (p_tmr->State) {
        case OS_TMR_STATE_RUNNING:                          /* Restart the timer                                      */
             OS_TmrUnlink(p_tmr);                           /* ... Stop the timer                                     */
             OS_TmrLink(p_tmr, OS_OPT_LINK_DLY);            /* ... Link timer to timer wheel (see Note #1).           */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_NONE;
             return (DEF_TRUE);

        case OS_TMR_STATE_STOPPED:                          /* Start the timer                                        */
        case OS_TMR_STATE_COMPLETED:
             OS_TmrLink(p_tmr, OS_OPT_LINK_DLY);            /* ... Link timer to timer wheel (see Note #1).           */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_NONE;
             return (DEF_TRUE);

        case OS_TMR_STATE_UNUSED:                           /* Timer not created                                      */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INACTIVE;
             return (DEF_FALSE);

        default:
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INVALID_STATE;
             return (DEF_FALSE);
    }
}
Beispiel #9
0
CPU_BOOLEAN  OSTmrStop (OS_TMR  *p_tmr,
                        OS_OPT   opt,
                        void    *p_callback_arg,
                        OS_ERR  *p_err)
{
    OS_TMR_CALLBACK_PTR  p_fnct;
    OS_ERR               err;



#ifdef OS_SAFETY_CRITICAL
    if (p_err == (OS_ERR *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u
    if (OSIntNestingCtr > (OS_NESTING_CTR)0) {                        /* See if trying to call from an ISR            */
       *p_err = OS_ERR_TMR_ISR;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_ARG_CHK_EN > 0u
    if (p_tmr == (OS_TMR *)0) {
       *p_err = OS_ERR_TMR_INVALID;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_OBJ_TYPE_CHK_EN > 0u
    if (p_tmr->Type != OS_OBJ_TYPE_TMR) {                             /* Make sure timer was created                  */
       *p_err = OS_ERR_OBJ_TYPE;
        return (DEF_FALSE);
    }
#endif

    OSSchedLock(&err);
    switch (p_tmr->State) {
        case OS_TMR_STATE_RUNNING:
             OS_TmrUnlink(p_tmr);                                     /* Remove from current wheel spoke              */
            *p_err = OS_ERR_NONE;
             switch (opt) {
                 case OS_OPT_TMR_CALLBACK:
                      p_fnct = p_tmr->CallbackPtr;                         /* Execute callback function ...           */
                      if (p_fnct != (OS_TMR_CALLBACK_PTR)0) {              /* ... if available                        */
                        (*p_fnct)((void *)p_tmr, p_tmr->CallbackPtrArg);   /* Use callback arg when timer was created */
                      } else {
                         *p_err = OS_ERR_TMR_NO_CALLBACK;
                      }
                      break;

                 case OS_OPT_TMR_CALLBACK_ARG:
                      p_fnct = p_tmr->CallbackPtr;                    /* Execute callback function if available ...   */
                      if (p_fnct != (OS_TMR_CALLBACK_PTR)0) {
                        (*p_fnct)((void *)p_tmr, p_callback_arg);     /* .. using the 'callback_arg' provided in call */
                      } else {
                         *p_err = OS_ERR_TMR_NO_CALLBACK;
                      }
                      break;

                 case OS_OPT_TMR_NONE:
                      break;

                 default:
                     OSSchedUnlock(&err);
                    *p_err = OS_ERR_OPT_INVALID;
                     return (DEF_FALSE);
             }
             OSSchedUnlock(&err);
             return (DEF_TRUE);

        case OS_TMR_STATE_COMPLETED:                                  /* Timer has already completed the ONE-SHOT or  */
        case OS_TMR_STATE_STOPPED:                                    /* ... timer has not started yet.               */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_STOPPED;
             return (DEF_TRUE);

        case OS_TMR_STATE_UNUSED:                                     /* Timer was not created                        */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INACTIVE;
             return (DEF_FALSE);

        default:
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INVALID_STATE;
             return (DEF_FALSE);
    }
}
Beispiel #10
0
CPU_BOOLEAN  OSTmrDel (OS_TMR  *p_tmr,
                       OS_ERR  *p_err)
{
    OS_ERR  err;



#ifdef OS_SAFETY_CRITICAL
    if (p_err == (OS_ERR *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u
    if (OSIntNestingCtr > (OS_NESTING_CTR)0) {              /* See if trying to call from an ISR                      */
       *p_err  = OS_ERR_TMR_ISR;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_ARG_CHK_EN > 0u
    if (p_tmr == (OS_TMR *)0) {
       *p_err = OS_ERR_TMR_INVALID;
        return (DEF_FALSE);
    }
#endif

#if OS_CFG_OBJ_TYPE_CHK_EN > 0u
    if (p_tmr->Type != OS_OBJ_TYPE_TMR) {                   /* Make sure timer was created                            */
       *p_err = OS_ERR_OBJ_TYPE;
        return (DEF_FALSE);
    }
#endif

    OSSchedLock(&err);
#if OS_CFG_DBG_EN > 0u
    OS_TmrDbgListRemove(p_tmr);
#endif
    OSTmrQty--;                                             /* One less timer                                         */

    switch (p_tmr->State) {
        case OS_TMR_STATE_RUNNING:
             OS_TmrUnlink(p_tmr);                           /* Remove from current wheel spoke                        */
             OS_TmrClr(p_tmr);
             OSSchedUnlock(&err);
            *p_err = OS_ERR_NONE;
             return (DEF_TRUE);

        case OS_TMR_STATE_STOPPED:                          /* Timer has not started or ...                           */
        case OS_TMR_STATE_COMPLETED:                        /* ... timer has completed the ONE-SHOT time              */
             OS_TmrClr(p_tmr);                              /* Clear timer fields                                     */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_NONE;
             return (DEF_TRUE);

        case OS_TMR_STATE_UNUSED:                           /* Already deleted                                        */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INACTIVE;
             return (DEF_FALSE);

        default:
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INVALID_STATE;
             return (DEF_FALSE);
    }
}
Beispiel #11
0
OS_TICK  OSTmrRemainGet (OS_TMR  *p_tmr,
                         OS_ERR  *p_err)
{
    OS_TICK  remain;
    OS_ERR   err;



#ifdef OS_SAFETY_CRITICAL
    if (p_err == (OS_ERR *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_TICK)0);
    }
#endif

#if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u
    if (OSIntNestingCtr > (OS_NESTING_CTR)0) {              /* See if trying to call from an ISR                      */
       *p_err = OS_ERR_TMR_ISR;
        return ((OS_TICK)0);
    }
#endif

#if OS_CFG_ARG_CHK_EN > 0u
    if (p_tmr == (OS_TMR *)0) {
       *p_err = OS_ERR_TMR_INVALID;
        return ((OS_TICK)0);
    }
#endif

#if OS_CFG_OBJ_TYPE_CHK_EN > 0u
    if (p_tmr->Type != OS_OBJ_TYPE_TMR) {                   /* Make sure timer was created                            */
       *p_err = OS_ERR_OBJ_TYPE;
        return ((OS_TICK)0);
    }
#endif

    OSSchedLock(&err);
    switch (p_tmr->State) {
        case OS_TMR_STATE_RUNNING:
             remain        = p_tmr->Match                   /* Determine how much time is left to timeout             */
                           - OSTmrTickCtr;
             p_tmr->Remain = remain;
             OSSchedUnlock(&err);
            *p_err         = OS_ERR_NONE;
             return (remain);

        case OS_TMR_STATE_STOPPED:                          /* It's assumed that the timer has not started yet        */
             if (p_tmr->Opt == OS_OPT_TMR_PERIODIC) {
                 if (p_tmr->Dly == 0u) {
                     remain = p_tmr->Period;
                 } else {
                     remain = p_tmr->Dly;
                 }
             } else {
                 remain = p_tmr->Dly;
             }
             p_tmr->Remain = remain;
             OSSchedUnlock(&err);
            *p_err         = OS_ERR_NONE;
             return (remain);

        case OS_TMR_STATE_COMPLETED:                        /* Only ONE-SHOT that timed out can be in this state      */
             OSSchedUnlock(&err);
            *p_err = OS_ERR_NONE;
             return ((OS_TICK)0);

        case OS_TMR_STATE_UNUSED:
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INACTIVE;
             return ((OS_TICK)0);

        default:
             OSSchedUnlock(&err);
            *p_err = OS_ERR_TMR_INVALID_STATE;
             return ((OS_TICK)0);
    }
}
ADI_OSAL_STATUS adi_osal_ThreadCreate(ADI_OSAL_THREAD_HANDLE *phThread, const ADI_OSAL_THREAD_ATTR *pThreadAttr)
{
    INT8U    nErr;
    INT8U    nRetValue;
#pragma diag(push)
#pragma diag(suppress:misra_rule_6_3 : "uCOS definition gives a MISRA error, in theory OS_STK should by INT32U and not 'unsigned int'")
    OS_STK   *pStackStart;
    OS_STK   *pStackTop;
#pragma diag(pop)
    uint32_t nStkSize;
    uint32_t nAlignment;
    ADI_OSAL_STATUS eRetStatus;
    ADI_OSAL_THREAD_INFO_PTR hThreadNode;
    uint32_t  nAssignedPrio;
    ADI_OSAL_STATUS eHeapResult;

#pragma diag(push)
#pragma diag(suppress:misra_rule_13_7 : "while checking compile time errors, having boolean operation that result is an invariant is necessary")
    /* check that typecasting pThreadAttr->pStackBase is valid */
    COMPILE_TIME_ASSERT((sizeof(void*)==sizeof(uint32_t)), pointer_size_mismatch);
#pragma diag(pop)

    if (phThread == NULL)
    {
        return(ADI_OSAL_FAILED);
    }

    /* verify that the given structure is not NULL before starting to access the fields */
    if (pThreadAttr == NULL)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_FAILED);
    }

#ifdef OSAL_DEBUG
#pragma diag(push)
#pragma diag(suppress:misra_rule_1_1 : "typecasting is not allowed otherwise, notified compiler team")
    nAlignment = ((uint32_t) (pThreadAttr->pStackBase) & 0x3u);   /* an address is 32-bits on a Blackfin processor */
#pragma diag(pop)
    if((nAlignment) !=0u)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
         return(ADI_OSAL_BAD_STACK_ADDR);
    }

    if (CALLED_FROM_AN_ISR)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_CALLER_ERROR);
    }

    if (pThreadAttr->pThreadFunc == NULL)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_BAD_THREAD_FUNC);
    }

    if ((pThreadAttr->nStackSize == 0u) || ((pThreadAttr->nStackSize & 0x3u) != 0u))
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return (ADI_OSAL_BAD_STACK_SIZE);
    }

    if (strlen(pThreadAttr->szThreadName) > ADI_OSAL_MAX_THREAD_NAME)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return ( ADI_OSAL_BAD_THREAD_NAME);
    }
#endif /* OSAL_DEBUG */

/* It is assumed here that the OS is setup to have its stack to grow downward (OS_STK_GROWTH==1)
    which is the way it is setup in the Blackfin port.
    We also make the assumption that OS_STK is fixed and won't change on the user's machine which is true
    because it's also part of the Blackfin port */
#ifndef __ADSPBLACKFIN__
#warning "the following code makes some assumptions that the code runs on a blackfin because of its stack operations"
#endif
   /*Convert the stack size in bytes to elements of OS_STK */
    nStkSize = pThreadAttr->nStackSize/sizeof(OS_STK);


#pragma diag(push)
#pragma diag(suppress:misra_rule_17_1 : "Allow pointer arithmetic on non-array types")
    pStackStart = (OS_STK*) pThreadAttr->pStackBase;
    pStackTop =   &pStackStart[nStkSize-1u];
#pragma diag(pop)


    /*  OS reserve some priority level for itself. uCOS reserves
        priority level 0,1,2,3.  ADI_OSAL_UCOS_BASE_PRIO is defined to offset
        OS reserved priorities.
    */
    nAssignedPrio= pThreadAttr->nPriority + ADI_OSAL_UCOS_BASE_PRIO;

    PAUSE_PROFILING();
    /* Because the OSAL operates on thread handles rather than priority we need to maintain
       a mapping. This is done via the ADI_OSAL_THREAD_INFO structure.
       Create a object of type ADI_OSAL_THREAD_INFO which will serve as the handle */
       eHeapResult = _adi_osal_MemAlloc((void*) &hThreadNode, sizeof(ADI_OSAL_THREAD_INFO));
    RESUME_PROFILING();
    if (ADI_OSAL_SUCCESS != eHeapResult)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return (ADI_OSAL_MEM_ALLOC_FAILED);
    }
    else
    {
        ADI_OSAL_SLOT_VALUE *pTLSBuffer;

        /* save information about the thread into its structure */
        hThreadNode->nThreadPrio = (uint8_t) nAssignedPrio;

        PAUSE_PROFILING();
#pragma diag(push)
#pragma diag(suppress:misra_rule_11_4 : "typecasting is necessary to convert the local structure type in to a generic void** type required by malloc")
        eHeapResult = _adi_osal_MemAlloc((void**) &pTLSBuffer, sizeof(ADI_OSAL_SLOT_VALUE) * _adi_osal_gnNumSlots);
#pragma diag(pop)
        RESUME_PROFILING();
        if (ADI_OSAL_SUCCESS != eHeapResult )
        {
            *phThread = ADI_OSAL_INVALID_THREAD;
            
            /* Free the previously allocated memory because of a failure case */
            _adi_osal_MemFree(hThreadNode);
            return (ADI_OSAL_MEM_ALLOC_FAILED);
        }
        hThreadNode->pThreadLocalStorageBuffer = pTLSBuffer;
    }

    /* Creating a task  by calling native OS call.*/

    /* The scheduler needs to be locked so that the TaskCreation and the Name assignement
       can be done atomically. It is important because the OSTaskNameSet takes the priority
       as an argument, and the priority could have been changed within the task itself which
       starts right after OSTaskCreateExt is called */
    PAUSE_PROFILING();
    OSSchedLock();
    RESUME_PROFILING();


    PAUSE_PROFILING();
    /* the OSTCBExtPtr TCB entry (pext) is used for storing the pointer to the ADI_OSAL_THREAD_INFO structure so that
       it can be found when given the Thread Priority (uCOS task handle) */
    nRetValue = OSTaskCreateExt (pThreadAttr->pThreadFunc,
                                 pThreadAttr->pParam,
                                 pStackTop,
                                 (INT8U)  (nAssignedPrio & 0xFFu),
                                 (INT16U) nAssignedPrio,
                                 pStackStart,
                                 nStkSize,
                                 (void *)hThreadNode,
                                 (OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR) ) ;
    RESUME_PROFILING();

    switch (nRetValue)
    {
        case  OS_ERR_NONE:
            /* set the Name of the task. Maximum characters in the
              name of the task  allowed is "OS_TASK_NAME_SIZE".
              If it exceeds, it will be truncated to OS_TASK_NAME_SIZE*/
#pragma diag(push)
#pragma diag(suppress:misra_rule_11_4 : "typecasting to the type expexted by uC/OS is necessary, also necessary for the return value")
#pragma diag(suppress:misra_rule_11_5 : "the API between the OSAL and uCOS force a const --> non-const conversion.")
/* converting from a const to non-const variable could be a risk, but since the data is getting 
   copied anyway it's not an issue here.*/
/* Supression since  typecasting "szTaskName" which is char_t to INT8U */
            PAUSE_PROFILING();
            OSTaskNameSet((INT8U) nAssignedPrio,(INT8U*) pThreadAttr->szThreadName, &nErr);
            RESUME_PROFILING();
            if(nErr == OS_ERR_NONE)
            {
                /* The ADI_OSAL_THREAD_INFO structure is used as the thread handle */
               *phThread = (ADI_OSAL_THREAD_HANDLE) hThreadNode;
                eRetStatus = ADI_OSAL_SUCCESS;
            }
            else
            {
                eRetStatus = ADI_OSAL_FAILED;
            }
            break;
#pragma diag(pop)

        /* Priority of the specified task is already exists */
        case  OS_ERR_PRIO_EXIST:
            eRetStatus= ADI_OSAL_PRIORITY_IN_USE;
            break;
        /* Specified priority is out of range */
        case  OS_ERR_PRIO_INVALID:
            eRetStatus = ADI_OSAL_BAD_PRIORITY;
            break;
        /* Not enough memory to create task */
        case  OS_ERR_TASK_NO_MORE_TCB:
            eRetStatus = ADI_OSAL_MEM_ALLOC_FAILED;
            break;
        default:
            eRetStatus = ADI_OSAL_FAILED;
            break;
    }

    PAUSE_PROFILING();
    OSSchedUnlock();
    RESUME_PROFILING();
    
    if(eRetStatus != ADI_OSAL_SUCCESS)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        if (hThreadNode != NULL)
        {
            _adi_osal_MemFree(hThreadNode->pThreadLocalStorageBuffer);
            _adi_osal_MemFree(hThreadNode);
        }
    }

    return(eRetStatus);
}
Beispiel #13
0
OS_TMR  *OSTmrCreate (INT32U           dly,
                      INT32U           period,
                      INT8U            opt,
                      OS_TMR_CALLBACK  callback,
                      void            *callback_arg,
                      INT8U           *pname,
                      INT8U           *perr)
{
    OS_TMR   *ptmr;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_TMR *)0);
    }
#endif

#ifdef OS_SAFETY_CRITICAL_IEC61508
    if (OSSafetyCriticalStartFlag == OS_TRUE) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_TMR *)0);
    }
#endif

#if OS_ARG_CHK_EN > 0u
	/* 检查参数 */
    switch (opt) {                                          /* Validate arguments                                     */
		/* 周期定时器的period不能是0 */
        case OS_TMR_OPT_PERIODIC:
             if (period == 0u) {
                 *perr = OS_ERR_TMR_INVALID_PERIOD;
                 return ((OS_TMR *)0);
             }
             break;
		/* 单次定时器的dly不能是0 */
        case OS_TMR_OPT_ONE_SHOT:
             if (dly == 0u) {
                 *perr = OS_ERR_TMR_INVALID_DLY;
                 return ((OS_TMR *)0);
             }
             break;

        default:
             *perr = OS_ERR_TMR_INVALID_OPT;
             return ((OS_TMR *)0);
    }
#endif
    if (OSIntNesting > 0u) {                                /* See if trying to call from an ISR                      */
        *perr  = OS_ERR_TMR_ISR;
        return ((OS_TMR *)0);
    }
	/* 关调度 */
    OSSchedLock();
	/* 从空闲定时器控制块链表中获得一个空闲定时器控制块 */
    ptmr = OSTmr_Alloc();                                   /* Obtain a timer from the free pool                      */
	/* 如果没有空闲定时器控制块,则返回错误信息 */
    if (ptmr == (OS_TMR *)0) {
        OSSchedUnlock();
        *perr = OS_ERR_TMR_NON_AVAIL;
        return ((OS_TMR *)0);
    }
	/* 设置获取到的定时器控制块 */
	/* 创建定时器后,定时器是停止状态 */
    ptmr->OSTmrState       = OS_TMR_STATE_STOPPED;          /* Indicate that timer is not running yet                 */
	/* 设置第一次延时值 */
    ptmr->OSTmrDly         = dly;
	/* 设置周期值 */
    ptmr->OSTmrPeriod      = period;
	/* 设置定时器类型,单次或者周期 */
    ptmr->OSTmrOpt         = opt;
	/* 设置定时器回调函数 */
    ptmr->OSTmrCallback    = callback;
	/* 设置定时器回调函数的参数 */
    ptmr->OSTmrCallbackArg = callback_arg;
#if OS_TMR_CFG_NAME_EN > 0u
    if (pname == (INT8U *)0) {                              /* Is 'pname' a NULL pointer?                             */
        ptmr->OSTmrName    = (INT8U *)(void *)"?";
    } else {
        ptmr->OSTmrName    = pname;
    }
#endif
	/* 允许调度 */
    OSSchedUnlock();
    *perr = OS_ERR_NONE;
    return (ptmr);
}
ADI_OSAL_STATUS adi_osal_ThreadCreate(ADI_OSAL_THREAD_HANDLE *phThread, const ADI_OSAL_THREAD_ATTR *pThreadAttr)
{
    INT8U    nErr;
    INT8U    nRetValue;
#pragma diag(push)
#pragma diag(suppress:misra_rule_6_3 : "uCOS definition gives a MISRA error, in theory OS_STK should by INT32U and not 'unsigned int'")
    OS_STK   *pStackStart;
    OS_STK   *pStackTop;
#pragma diag(pop)
    uint32_t nStkSize;
    ADI_OSAL_STATUS eRetStatus;
    ADI_OSAL_THREAD_INFO_PTR hThreadNode;
    uint32_t  nAssignedPrio;
    ADI_OSAL_STATUS eHeapResult;


#ifdef OSAL_DEBUG
    if (NULL == phThread)
    {
        return(ADI_OSAL_FAILED);
    }

    /* verify that the given structure is not NULL before starting to access the fields */
    if (NULL == pThreadAttr)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_FAILED);
    }

    if ( !_adi_osal_IsMemoryAligned(pThreadAttr->pStackBase) )
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_BAD_STACK_ADDR);
    }

    if (CALLED_FROM_AN_ISR)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_CALLER_ERROR);
    }

    if (NULL == pThreadAttr->pThreadFunc)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return(ADI_OSAL_BAD_THREAD_FUNC);
    }

    if (0u == pThreadAttr->nStackSize)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return (ADI_OSAL_BAD_STACK_SIZE);
    }

    if (!_adi_osal_IsMemoryAligned((void*) pThreadAttr->nStackSize))
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return (ADI_OSAL_BAD_STACK_SIZE);
    }

    if (strlen(pThreadAttr->szThreadName) > ADI_OSAL_MAX_THREAD_NAME)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return ( ADI_OSAL_BAD_THREAD_NAME);
    }

#endif

    /* This code assumes the following
        * The OS is setup to have its stack to grow downward (OS_STK_GROWTH==1)
        * OS_STK is fixed in a per-platform basis and not per-application. This is
          true because it is part of the Micrium port
     */

    /* Convert the stack size in bytes to elements of OS_STK */
    nStkSize = pThreadAttr->nStackSize/sizeof(OS_STK);

#pragma diag(push)
#pragma diag(suppress:misra_rule_17_1 : "Allow pointer arithmetic on non-array types")
    pStackStart = (OS_STK*) pThreadAttr->pStackBase;
    pStackTop =   &pStackStart[nStkSize-1u];
#pragma diag(pop)

    /*  OS reserve some priority level for itself. uCOS reserves
     *  priority level 0,1,2,3.  ADI_OSAL_UCOS_BASE_PRIO is defined to offset
     *  OS reserved priorities.
     */

    nAssignedPrio= pThreadAttr->nPriority + ADI_OSAL_UCOS_BASE_PRIO;

    /* Because the OSAL operates on thread handles rather than priority we need
     * to maintain a mapping. This is done via the ADI_OSAL_THREAD_INFO
     * structure.  Create a object of type ADI_OSAL_THREAD_INFO which will serve
     * as the handle
     */

    eHeapResult = _adi_osal_MemAlloc((void**) &hThreadNode, sizeof(ADI_OSAL_THREAD_INFO));

    if (ADI_OSAL_SUCCESS != eHeapResult)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        return (eHeapResult);
    }

    /* save information about the thread into its structure */
    hThreadNode->nThreadPrio = (ADI_OSAL_PRIORITY) nAssignedPrio;

    /* Creating a task  by calling native OS call.*/

    /* The scheduler needs to be locked so that the TaskCreation and the Name
       assignement can be done atomically. It is important because the
       OSTaskNameSet takes the priority as an argument, and the priority could
       have been changed within the task itself which starts right after
       OSTaskCreateExt is called */

    OSSchedLock();


    /* the OSTCBExtPtr TCB entry (pext) is used for storing the pointer to the
     * ADI_OSAL_THREAD_INFO structure so that
     * it can be found when given the Thread Priority (uCOS task handle)
     */
    nRetValue = OSTaskCreateExt (pThreadAttr->pThreadFunc,
                                 pThreadAttr->pTaskAttrParam,
                                 pStackTop,
                                 (INT8U)  (nAssignedPrio & 0xFFu),
                                 (INT16U) nAssignedPrio,
                                 pStackStart,
                                 nStkSize,
                                 (void *)hThreadNode,
                                 (OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR) ) ;

    switch (nRetValue)
    {
    case  OS_ERR_NONE:
        /* set the Name of the task. Maximum characters in the
          name of the task  allowed is "OS_TASK_NAME_SIZE".
          If it exceeds, it will be truncated to OS_TASK_NAME_SIZE*/
#pragma diag(push)
#pragma diag(suppress:misra_rule_11_4 : "typecasting to the type expexted by uC/OS is necessary, also necessary for the return value")
#pragma diag(suppress:misra_rule_11_5 : "the API between the OSAL and uCOS force a const --> non-const conversion.")

        hThreadNode->nThreadSignature = ADI_OSAL_THREAD_SIGNATURE;

        /* converting from a const to non-const variable could be a risk, but since the
           data is getting copied anyway it's not an issue here.*/
        /* Supression since  typecasting "szTaskName" which is char_t to INT8U */
        OSTaskNameSet((INT8U) nAssignedPrio,
                      (INT8U*) pThreadAttr->szThreadName,
                      &nErr);
        if(nErr == OS_ERR_NONE)
        {
            /* The ADI_OSAL_THREAD_INFO structure is used as the thread handle */
            *phThread = (ADI_OSAL_THREAD_HANDLE) hThreadNode;
            eRetStatus = ADI_OSAL_SUCCESS;
        }
        else
        {
            eRetStatus = ADI_OSAL_FAILED;
        }
        break;
#pragma diag(pop)

#ifdef OSAL_DEBUG
    /* Priority of the specified task is already exists */
    case  OS_ERR_PRIO_EXIST:
        eRetStatus= ADI_OSAL_PRIORITY_IN_USE;
        break;
    /* Specified priority is out of range */
    case  OS_ERR_PRIO_INVALID:
        eRetStatus = ADI_OSAL_BAD_PRIORITY;
        break;
    case  OS_ERR_TASK_CREATE_ISR:
        eRetStatus = ADI_OSAL_CALLER_ERROR;
        break;
    /* Not enough memory to create task */
    case  OS_ERR_TASK_NO_MORE_TCB:
        eRetStatus = ADI_OSAL_MEM_ALLOC_FAILED;
        break;
#endif
    default:
        eRetStatus = ADI_OSAL_FAILED;
        break;
    } /* end of switch */

    OSSchedUnlock();

    if(eRetStatus != ADI_OSAL_SUCCESS)
    {
        *phThread = ADI_OSAL_INVALID_THREAD;
        if (NULL != hThreadNode)
        {
            hThreadNode->nThreadSignature=ADI_OSAL_INVALID_THREAD_SIGNATURE;
            _adi_osal_MemFree(hThreadNode);
        }
    }

    return(eRetStatus);
}
Beispiel #15
0
INT32U  OSTmrRemainGet (OS_TMR  *ptmr,
                        INT8U   *perr)
{
    INT32U  remain;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (0u);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {              /* Validate timer structure                                    */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (0u);
    }
    if (OSIntNesting > 0u) {                           /* See if trying to call from an ISR                           */
        *perr = OS_ERR_TMR_ISR;
        return (0u);
    }
    OSSchedLock();
    switch (ptmr->OSTmrState) {
        case OS_TMR_STATE_RUNNING:
             remain = ptmr->OSTmrMatch - OSTmrTime;    /* Determine how much time is left to timeout                  */
             OSSchedUnlock();
             *perr  = OS_ERR_NONE;
             return (remain);

        case OS_TMR_STATE_STOPPED:                     /* It's assumed that the timer has not started yet             */
             switch (ptmr->OSTmrOpt) {
                 case OS_TMR_OPT_PERIODIC:
                      if (ptmr->OSTmrDly == 0u) {
                          remain = ptmr->OSTmrPeriod;
                      } else {
                          remain = ptmr->OSTmrDly;
                      }
                      OSSchedUnlock();
                      *perr  = OS_ERR_NONE;
                      break;

                 case OS_TMR_OPT_ONE_SHOT:
                 default:
                      remain = ptmr->OSTmrDly;
                      OSSchedUnlock();
                      *perr  = OS_ERR_NONE;
                      break;
             }
             return (remain);

        case OS_TMR_STATE_COMPLETED:                   /* Only ONE-SHOT that timed out can be in this state           */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (0u);

        case OS_TMR_STATE_UNUSED:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INACTIVE;
             return (0u);

        default:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INVALID_STATE;
             return (0u);
    }
}
Beispiel #16
0
/*********************************************************************************************************
** Function name:     	HP_send
** Descriptions:	    EVB通讯
** input parameters:    Chl:选择通道;Head:包头;Sn:序列号;Type:消息类别;Addr:设备地址;Data:数据;
** output parameters:   *ACK:应答包
** Returned value:      1:收到应答;0:未收到应答即通讯失败
*********************************************************************************************************/
uint8 HP_send(uint8 addr,uint8 cmd,uint16 data)
{
	uint8 index = 0,i,ch,len,crc;
	memset((void *)recvbuf,0,sizeof(recvbuf));
	
	sn[addr] = (cmd == HP_PAYOUT) ? sn[addr] + 1: sn[addr]; //更新sn
	
	sendbuf[index++] = 0xED;
	sendbuf[index++] = 0x08; //len
	sendbuf[index++] = sn[addr];
	sendbuf[index++] = cmd;
	sendbuf[index++] = addr;
	sendbuf[index++] = LUINT16(data);
	sendbuf[index++] = HUINT16(data);
	sendbuf[index++] = XorCheck((uint8 *)sendbuf,7);
	
	uart3_clr_buf();
	//发送数据禁止切换任务
	OSSchedLock();
	Uart3PutStr((uint8 *)sendbuf,8);
	OSSchedUnlock();
	
	#ifdef DEBUG_HOPPER
	print_hopper("HP-SEND[%d]:",index);
	for(i = 0;i < index;i++){
		print_hopper("%02x ",sendbuf[i]);
	}
	print_hopper("\r\n");
	#endif
	
	index = 0;
	Timer.hopper_recv_timeout = 100;
	while(Timer.hopper_recv_timeout){ //1000ms内收到ACK,否则超时
		if(Uart3BuffIsNotEmpty() == 1){
			ch = Uart3GetCh();
			if(index == 0){
				if(ch == 0xFD){
					recvbuf[index++] = ch;
				}
			}
			else if(index == 1){
				len = ch;
				recvbuf[index++] = ch;
			}
			else if(index >= (len - 1)){
				recvbuf[index++] = ch;
				crc = XorCheck((uint8 *)recvbuf,len - 1);
				if(crc == ch){
#ifdef DEBUG_HOPPER
					print_hopper("HP-RECV[%d]:",recvbuf[1]);
					for(i = 0;i < recvbuf[1];i++){
						print_hopper("%02x ",recvbuf[i]);
					}
					print_hopper("\r\n");
#endif
					return 1;
				}
			}
			else{
				recvbuf[index++] = ch;
			}
		}
		else{
			msleep(20);
		}
	}
	return 0;
}
Beispiel #17
0
void alt_uCOSIIErrorHandler(INT8U error_code, void *expanded_diagnosis_ptr)
{
   FAULT_LEVEL fault_level;
   
   if(error_code == OS_NO_ERR)
   {
      return;
   }
   
   fault_level = SYSTEM;  
   OSSchedLock();  /* Disable Task Switching but still service other IRQs */
      
   switch (error_code)
   {  
      case OS_PRIO_EXIST:
         fprintf(stderr, "Attempted to assign task priority aready in use.\n");
         break;
      case OS_PRIO_INVALID:
         fprintf(stderr, "Specified task priority higher than allowed max.\n");
         fprintf(stderr, "Task can't be assigned a priority higher than %d\n",
            OS_LOWEST_PRIO);
         break;
      case OS_NO_MORE_TCB:
         fprintf(stderr, "Task Control Blocks have been exhausted\n");
         fprintf(stderr, "Current max number of tasks is %d\n",OS_MAX_TASKS);
         break;
      case OS_MBOX_FULL:
         fault_level = NONE;
         fprintf(stderr, "Attempted Post to Mailbox already holding message\n");
         break;
      case OS_ERR_EVENT_TYPE:
         fault_level = TASK;
         fprintf(stderr, 
"Attempted to access a resource with no match for the required data type.\n");
         break;
      case OS_ERR_PEVENT_NULL:
         fprintf(stderr, "Attempting to access a resource pointing to NULL\n");
         break;
      case OS_ERR_POST_NULL_PTR:
         fault_level = TASK;
         fprintf(stderr, "Attempted to Post a NULL to a resource. \n");
         break;
      case OS_TIMEOUT:
         fault_level = NONE;
         fprintf(stderr, "Resource not received in specified time\n");
         break;
      case OS_ERR_PEND_ISR:
         fprintf(stderr, "Attempting to pend for a resource in an ISR\n");
         break;
      case OS_TASK_DEL_IDLE:
         fprintf(stderr, "Attempted to delete the IDLE task\n");
         break;
      case OS_TASK_DEL_ERR:
         fault_level = NONE;
         fprintf(stderr, "Attempted to delete a task that does not exist\n");
         break;
      case OS_TASK_DEL_ISR:
         fprintf(stderr, "Attempted to delete a task from an ISR\n");
         break;
      case OS_Q_FULL:
         fault_level = NONE;
         fprintf(stderr, "Attempted to post to a full message queue\n");
         break;
      case OS_ERR_NOT_MUTEX_OWNER:
         fault_level = TASK;
         fprintf(stderr, "Attempted to post a mutex not owned by the task\n");
         break;
      case EXPANDED_DIAGNOSIS_CODE:      
         fault_level = SYSTEM;
         printf(
"\n[MicroC/OS-II]: See STDERR for expanded diagnosis translation.");    
         fprintf(stderr, "\n[MicroC/OS-II]: Expanded Diagnosis: %s.", 
                 (char *)expanded_diagnosis_ptr);
         break;           
      default:
         printf("\n[MicroC/OS-II]: (Not a MicroC/OS-II error) See STDERR.\n");    
         fprintf(stderr, "\n[MicroC/OS-II]:");
         fprintf(stderr, "\nError_code %d.\n", error_code);
         perror("\n[MicroC/OS-II]: (Not a MicroC/OS-II error), ERRNO: ");
         break;

   }

   /* Process the error based on the fault level, 
    * reenable scheduler if appropriate. */  
   switch (fault_level) {
      case TASK:
         /* Error can be isolated by killing the task */
         printf("\n[MicroC/OS-II]: See STDERR (FAULT_LEVEL is TASK).");
         fprintf(stderr, "\n[MicroC/OS-II]: FAULT_LEVEL is TASK");
         fprintf(stderr, "\n[MicroC/OS-II]: Task is being deleted.\n");
         OSSchedUnlock(); /* Reenable Task Switching */
         OSTaskDel(OS_PRIO_SELF);
         /* Reinvoke uCOSII error handler in case task deletion fails, in 
          * which case fault_level for this secondary error will be SYSTEM. */
         alt_uCOSIIErrorHandler(error_code, 0);         
         break;
      case SYSTEM:
         /* Total System Failure, Restart Required */
         printf("\n[MicroC/OS-II]: See STDERR (FAULT_LEVEL is SYSTEM).");    
         fprintf(stderr, "\n[MicroC/OS-II]: FAULT_LEVEL is SYSTEM");
         fprintf(stderr, "\n[MicroC/OS-II]: FATAL Error, Restart required.");
         fprintf(stderr, "\n[MicroC/OS-II]: Locking scheduler - endless loop.\n");
         while(1); /* Since scheduler is locked,loop halts all task activity.*/
         break;
      case NONE:
         fprintf(stderr, "\n[MicroC/OS-II]: FAULT_LEVEL is NONE");
         fprintf(stderr, "\n[MicroC/OS-II]: Informational error only, control"); 
         fprintf(stderr, 
            "returned to task to complete processing at application level.\n");
         OSSchedUnlock(); /* Reenable Task Switching */
         return;   
         break;      
      default:
         printf("\n[MicroC/OS-II]: See STDERR (FAULT_LEVEL is Unknown).\n");
         fprintf(stderr, "\n[MicroC/OS-II]: FAULT_LEVEL is unknown!?!\n");
   }
   while(1); /* Correct Program Flow never gets here. */
}
Beispiel #18
0
BOOLEAN  OSTmrStart (OS_TMR   *ptmr,
                     INT8U    *perr)
{
#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (OS_FALSE);
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (OS_FALSE);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {                   /* Validate timer structure                               */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (OS_FALSE);
    }
    if (OSIntNesting > 0u) {                                /* See if trying to call from an ISR                      */
        *perr  = OS_ERR_TMR_ISR;
        return (OS_FALSE);
    }
	/* 调度器加锁 */
    OSSchedLock();
	
    switch (ptmr->OSTmrState) {
		/* 如果当前定时器是正在运行状态,则把定时器从当前分组移除
		 * 更新定时器到时时间后,把定时器重新链接到新的分组,并设置为第一次开始计时
		 */
        case OS_TMR_STATE_RUNNING:                          /* Restart the timer                                      */
             OSTmr_Unlink(ptmr);                            /* ... Stop the timer                                     */
			/* 使用OS_TMR_LINK_DLY选项把定时器链接进新的分组 
			 * 会按照第一次插入定时器,设置Dly或者Period
			 */
             OSTmr_Link(ptmr, OS_TMR_LINK_DLY);             /* ... Link timer to timer wheel                          */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (OS_TRUE);
		
		/* 如果定时器是Stop状态或者单次定时器的COMPLETED状态
		 * 则按照第一次插入定时器,设置Dly或者Period
		 */
        case OS_TMR_STATE_STOPPED:                          /* Start the timer                                        */
        case OS_TMR_STATE_COMPLETED:
             OSTmr_Link(ptmr, OS_TMR_LINK_DLY);             /* ... Link timer to timer wheel                          */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (OS_TRUE);
		
		/* 如果定时器是未使用状态,返回错误信息 */
        case OS_TMR_STATE_UNUSED:                           /* Timer not created                                      */
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INACTIVE;
             return (OS_FALSE);

        default:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INVALID_STATE;
             return (OS_FALSE);
    }
}
Beispiel #19
0
INT32U  OSTmrRemainGet (OS_TMR  *ptmr,
                        INT8U   *perr)
{
    INT32U  remain;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (0u);
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (0u);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {              /* Validate timer structure                                    */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (0u);
    }
    if (OSIntNesting > 0u) {                           /* See if trying to call from an ISR                           */
        *perr = OS_ERR_TMR_ISR;
        return (0u);
    }
	/* 调度器加锁 */
    OSSchedLock();
    switch (ptmr->OSTmrState) {
		/* 如果定时器是正在运行状态,则剩余时间是到时-当时时刻 */
        case OS_TMR_STATE_RUNNING:
             remain = ptmr->OSTmrMatch - OSTmrTime;    /* Determine how much time is left to timeout                  */
             OSSchedUnlock();
             *perr  = OS_ERR_NONE;
             return (remain);
		
		/* 如果定时器是STOPPED状态,说明定时器还没有运行,或者被调用了Stop
		 * 单次定时器运行完成之后是COMPLETED状态
		 * 周期定时器运行之后是OS_TMR_STATE_RUNNING状态
		 */
        case OS_TMR_STATE_STOPPED:                     /* It's assumed that the timer has not started yet             */
             switch (ptmr->OSTmrOpt) {
				 /* 如果是周期定时器,则根据是否设置了第一次运行前的Dly,返回剩余时间 */
                 case OS_TMR_OPT_PERIODIC:
                      if (ptmr->OSTmrDly == 0u) {
                          remain = ptmr->OSTmrPeriod;
                      } else {
                          remain = ptmr->OSTmrDly;
                      }
                      OSSchedUnlock();
                      *perr  = OS_ERR_NONE;
                      break;
				
				/* 如果是单次定时器,定时长度保存在Dly中 */
                 case OS_TMR_OPT_ONE_SHOT:
                 default:
                      remain = ptmr->OSTmrDly;
                      OSSchedUnlock();
                      *perr  = OS_ERR_NONE;
                      break;
             }
             return (remain);
		
		/* 单次定时器完成,剩余时间为0 */
        case OS_TMR_STATE_COMPLETED:                   /* Only ONE-SHOT that timed out can be in this state           */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (0u);
		
		/* 定时器未使用,返回0和错误信息 */
        case OS_TMR_STATE_UNUSED:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INACTIVE;
             return (0u);
		
		/* 定时器状态错误 */
        default:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INVALID_STATE;
             return (0u);
    }
}
Beispiel #20
0
BOOLEAN  OSTmrDel (OS_TMR  *ptmr,
                   INT8U   *perr)
{
#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (OS_FALSE);
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (OS_FALSE);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {                   /* Validate timer structure                               */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (OS_FALSE);
    }
    if (OSIntNesting > 0u) {                                /* See if trying to call from an ISR                      */
        *perr  = OS_ERR_TMR_ISR;
        return (OS_FALSE);
    }
	/* 关调度 */
    OSSchedLock();
	/* 根据定时器的当前状态,使用不同的删除步骤 */
    switch (ptmr->OSTmrState) {
		/* 如果定时器正在运行 */
        case OS_TMR_STATE_RUNNING:
			/* 把定时器控制块从所在的分组链表中移除 */
             OSTmr_Unlink(ptmr);                            /* Remove from current wheel spoke                        */
			/* 释放定时器控制块到空闲定时器控制块链表 */
             OSTmr_Free(ptmr);                              /* Return timer to free list of timers                    */
			/* 允许调度 */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (OS_TRUE);
		
		/* 如果定时器是未运行状态,或者是单次定时器的已完成状态
		 * 直接把定时器控制块释放到空定时器控制块链表
		 */
        case OS_TMR_STATE_STOPPED:                          /* Timer has not started or ...                           */
        case OS_TMR_STATE_COMPLETED:                        /* ... timer has completed the ONE-SHOT time              */
             OSTmr_Free(ptmr);                              /* Return timer to free list of timers                    */
			/* 允许调度 */
             OSSchedUnlock();
             *perr = OS_ERR_NONE;
             return (OS_TRUE);
		
		/* 如果定时器控制块是未使用状态,则返回错误信息 */
        case OS_TMR_STATE_UNUSED:                           /* Already deleted                                        */
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INACTIVE;
             return (OS_FALSE);

        default:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INVALID_STATE;
             return (OS_FALSE);
    }
}
Beispiel #21
0
void alt_SSSErrorHandler(INT8U error_code, 
                         void *expanded_diagnosis_ptr)
{
   FAULT_LEVEL fault_level;
   
   if   (error_code == OS_NO_ERR)
   {
      return;
   }

   fault_level = (error_code == OS_NO_ERR) ? NONE : SYSTEM;
   
   OSSchedLock();  /* Disable Task Switching but still service other IRQs */
   switch (error_code)
   {
      case EXPANDED_DIAGNOSIS_CODE:      
         fault_level = SYSTEM;
         printf("\n[SSS]: See STDERR for expanded diagnosis translation.");    
         fprintf(stderr, "\n[SSS]: %s", (char *)expanded_diagnosis_ptr);
         break;
         
      case OS_Q_FULL:
         fault_level = NONE;
         fprintf(stderr,"\n[SSS]: Attempted to post to a full message queue.");
         break;
      
      default:
         fault_level = SYSTEM;
         printf("\n[SSS]: See STDERR.\n");    
         fprintf(stderr, "\n[SSS]: Error_code %d!", error_code);        
         perror("\n[SSS]:  ERRNO: ");
   }

   /* Process the error based on the fault level, 
    * reenable scheduler if appropriate. */     
   switch (fault_level) 
   {
      case TASK:
         /* Error can be isolated by killing the task */
         printf("\n[SSS]: See STDERR (FAULT_LEVEL is TASK).");
         fprintf(stderr, "\n[SSS]: FAULT_LEVEL is TASK");
         fprintf(stderr, "\n[SSS]: Task is being deleted.\n");
         OSSchedUnlock(); /* Reenable Task Switching */
         OSTaskDel(OS_PRIO_SELF);
         /* Invoke uCOSII error handler in case task deletion fails, in 
          * which case fault_level for this secondary error will be SYSTEM. */
         alt_uCOSIIErrorHandler(error_code, 0);         
         break;
      case SYSTEM:
          /* Total System Failure, Restart Required */
         printf("\n[SSS]: See STDERR (FAULT_LEVEL is SYSTEM).");    
         fprintf(stderr, "\n[SSS]: FAULT_LEVEL is SYSTEM.");
         fprintf(stderr, "\n[SSS]: FATAL Error, Restart required.");
         fprintf(stderr, "\n[SSS]: Locking scheduler - endless loop.\n");
         while(1); /* Since scheduler is locked, loop halts all task activity.*/
         break;
      case NONE:
         fprintf(stderr, "\n[SSS] FAULT_LEVEL is NONE.");
         fprintf(stderr, 
            "\n[SSS] Informational error only, control returned to task to ");
         fprintf(stderr,
            "complete processing at the application level.\n");
         OSSchedUnlock(); /* Reenable Task Switching */ 
         return;         
         break;
      default:
         printf("\n[SSS]: See STDERR (FAULT_LEVEL is Unknown).\n");
         fprintf(stderr, "\n[SSS] FAULT_LEVEL is unknown!?!\n");
   }
   while(1); /* Correct Program Flow never gets here. */
}
Beispiel #22
0
void Simu_Send_Data(void* ps)
{
  INT32S re=0,i,j,k,l,m,nKeyNo;
  INT32S nChDataSize=sizeof(struct tagChData2060)+(_MAX_KEY_PT_CNT+g_nDatalth-1)*sizeof(INT32S);
  float fSign=0;
  char inf[256]={0};
  float fv[50];
  //void* p;
  INT8S p[sizeof(struct tagChData2060)+(_MAX_KEY_PT_CNT+_DEFAULT_DATA_LTH-1)*sizeof(INT32S)];
  INT8S* pData=(INT8S *)g_pOutChData;
  struct tagChData2060*  pchData=0;
  
  INT32S nCurSit[_MAX_JKEY_CHANNEL_CNT]={0};
  INT32S nSpeed[_MAX_JKEY_CHANNEL_CNT];
  INT32S nLth[_MAX_JKEY_CHANNEL_CNT];
  
  PAlertNode pAlert=g_AlertNode;
  
  struct tagChValue *pAv=g_pSimuAlertMeasureValue;	
  
  PTranNode pTran=g_TranNode;
  struct tagChValue chValue;
  
  INT32S nRpmFlag=0;
  
  //p=malloc(sizeof(struct tagChData2060)+(_MAX_KEY_PT_CNT+g_nDatalth-1)*sizeof(INT32S));
  Mem_Clr(p, sizeof(p));
  pchData=(struct tagChData2060*)p;
  
  chValue.nTrigerTime=0;
  chValue.nChNo=0;
  chValue.nRPM=g_nBasicRPM;
  chValue.nAlertFlag=0;
  chValue.nAllMeasureValue=g_fNormalAlp;
  chValue.nAllPhase=0;
  chValue.n1xV=g_fLevel*g_fCof1x;
  chValue.n1xP=0;
  chValue.n2xV=g_fLevel*g_fCof2x;
  chValue.n2xP=0;
  chValue.n05xV=g_fLevel*g_fCofP5x;
  chValue.n05xP=0;
  chValue.nRpmFlag=0;
  i=0;
  do{
    // _log("Start Send SimuData\n");
    for(m=0;;m++)
    {		
      INT32S nChIndex=0;
      CheckSimuData();
      //		OSTimeDly(5);
      if(g_nChValueFlag!=3||g_nChDataFlag!=3)
      {
        //OSTimeDly(g_SendTimeInterval/(1000/OS_TICKS_PER_SEC));
        //OSTimeDly(1);
        OSTimeDly(1 );
        continue;
      }
      OSSchedLock( );//禁止任务切换 
      g_nChValueFlag=0;
      g_nChDataFlag=0;
      if(i==50)
        i=i;
      for(j=0;j<g_nChcnt;j++)
      {
        //	nSign=20*sin(6.2832*(m/100.+nSit[j]/71.));
        fSign=(g_nSit[j]*48.0/g_nChcnt-24.0)*(1+0.3*sin(6.2832*(m/10.)));
        if(g_nChKeyNo[g_nSit[j]]>=_START_KEY_CH)
        {
          nKeyNo=g_nChKeyNo[g_nSit[j]]-_START_KEY_CH;
          nSpeed[nKeyNo]=*g_nKeySpeed[nKeyNo][i];
          g_nCaltKeySpeed[nKeyNo]=nSpeed[nKeyNo];
        }
        else
          nSpeed[nKeyNo]=-1;
        //	if(nSpeed[nKeyNo]>3000)
        //		nSpeed[nKeyNo]=nSpeed[nKeyNo];
        nRpmFlag=0;
        for(k=0;k<g_TranNode[nKeyNo].nEventcnt;k++)
        {
          if(i>= g_TranNode[nKeyNo].nTigerTime[2*k]&&i<= g_TranNode[nKeyNo].nTigerTime[2*k+1])
          {
            nRpmFlag=1;
            break;
          }
        }
        //		CheckSimuData();
        if(i==0)
          i=i;
        if(i==pAlert->nTigerTime)//报警时间
        {
          pAv->nRPM=nSpeed[nKeyNo];
          pAv->nRpmFlag=nRpmFlag;
          //////输出报警通道测量值pAv
          //g_pOutChValue=pAv;
          Mem_Copy(g_pOutChValue+g_nSit[j],pAv,sizeof(struct tagChValue));
          pAv++;
          
        }
        else//非报警通道
        {
          
          chValue.nTrigerTime=i;
          chValue.nChNo=g_nSit[j];
          chValue.nRPM=nSpeed[nKeyNo];
          chValue.nRpmFlag=nRpmFlag;
          //g_pOutChValue=&chValue;
          
          Mem_Copy(g_pOutChValue+g_nSit[j],&chValue,sizeof(struct tagChValue));
          g_pOutChValue[g_nSit[j]].nAllMeasureValue*=(100+fSign)/100.;
          g_pOutChValue[g_nSit[j]].n1xV*=(100+fSign)/100.;
          g_pOutChValue[g_nSit[j]].n2xV*=(100+fSign)/100.;
          g_pOutChValue[g_nSit[j]].n05xV*=(100+fSign)/100.;
          fv[g_nSit[j]]=g_pOutChValue[g_nSit[j]].nAllMeasureValue;
          g_nChValueFlag=1;
          
          ///////输出正常通道测量值chValue
        }
        //		CheckSimuData();
        //读取转速为nSpeed[nKeyNo]下的通道原始数据
        if(i==680)
          i=i;
        memcpy(pchData,((INT8S*)g_pSimuTranPiece)+nSpeed[nKeyNo]*nChDataSize,nChDataSize);
        //Mem_Copy(pchData,((INT8S*)g_pSimuTranPiece)+nSpeed[nKeyNo]*nChDataSize,nChDataSize);
        //	CheckSimuData();
        nLth[nKeyNo]=nChDataSize-(_MAX_KEY_PT_CNT-pchData->nKeycnt)*sizeof(INT32S);
        pchData->nTrigerTime=i;
        pchData->nChNo=g_nSit[j];
        
        if(i==pAlert->nTigerTime&&g_nSit[j]==pAlert->nChNo[nChIndex])//报警通道
        {
          INT32S step;
          INT32S* p32s=&pchData->nKeycnt+1;
          p32s+=pchData->nKeycnt;
          for(step=0;step<g_nDatalth;step++)//修改报警通道原始数据幅值
          {
           // p32s[step]=p32s[step]*pAlert->fCof[nChIndex]*g_12Param.SignalChannel[g_nSit[j]].fSensority;
            //czx
            p32s[step]=p32s[step]*pAlert->fCof[nChIndex];
          }					
          nChIndex++;
        }
        else
        {
          INT32S step;
          INT32S* p32s=(&pchData->nKeycnt)+1;
          p32s+=pchData->nKeycnt;
          
          if(i>600)
            i=i;
          if(g_nSit[j]/2*2==g_nSit[j])
          {
            for(step=0;step<g_nDatalth;step++)//修改报警通道原始数据幅值
            {
              //p32s[step]*=(100+fSign)/100.*g_12Param.SignalChannel[g_nSit[j]].fSensority;
              //czx
              p32s[step]*=(100+fSign)/100.;
            }
          }else
          {
            for(step=0;step<g_nDatalth;step++)//修改报警通道原始数据幅值
            {
              //p32s[step]*=(100-fSign)/100.*g_12Param.SignalChannel[g_nSit[j]].fSensority;
              //czx
              p32s[step]*=(100-fSign)/100.;
            }
            
          }				
          nChIndex++;
        }
        if(i==350)
          i=i;
        //g_pOutChData=pchData;
        Mem_Clr(inf, 256);
        //	sprintf(inf,"Ouput %d Sit\n",g_nCurWriteSit);
        //	_log(inf);
        Mem_Copy(g_pOutChDataArray[g_nSit[j]],pchData,nChDataSize);
        
      }
      if(i==50)
        i=i;
      //输出所有通道数据头
      OutputChValue();//	
      //输出所有通道原始数据
      Simu_Write_ChData(g_nLength,g_nChNo,_MAX_SIGNAL_CHANNEL_CNT,
                        g_nFpgaDynamicChDataOffset,g_nFpgaDynamicKeyDataOffset,g_nFpgaDynamicChDataSampleStep,
                        g_nFpgaTranDataOffset,g_nFpgaTranKeyDataOffset,g_nFpgaTranDataSampleStep);
      for(l=0;l<_MAX_SIGNAL_CHANNEL_CNT/_FPGA_GROUP_CHANNEL_CNT;l++)
        receive_channel_data();
      g_nChValueFlag=3;
      g_nChDataFlag=3;
      //OSTimeDly(g_SendTimeInterval/(1000/OS_TICKS_PER_SEC)/(_MAX_SIGNAL_CHANNEL_CNT/_FPGA_GROUP_CHANNEL_CNT));
      if(i>=pAlert->nTigerTime)
        pAlert++;
      //	_log("Deal Speed Too Slow,Data Will lose\n");
      g_bDataValid=1;
      
      for(l=0;l<_MAX_JKEY_CHANNEL_CNT;l++)
      {
        if(i==g_nTigerTime[l][nCurSit[l]])
        {
          nCurSit[l]++;
        }
      }
      i++;
      if(i==g_nAllcnt)
      {
        i=0;
        //		break;
      }
      
      OSSchedUnlock( );//允许任务切换 
      CheckSimuData();
      sleep_ms(100);
    }
    //_log("End Send SimuData\n");
  }while(1);
  //free(p);	
}
Beispiel #23
0
OS_TMR  *OSTmrCreate (INT32U           dly,
                      INT32U           period,
                      INT8U            opt,
                      OS_TMR_CALLBACK  callback,
                      void            *callback_arg,
                      INT8U           *pname,
                      INT8U           *perr)
{
    OS_TMR   *ptmr;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
    }
#endif

#ifdef OS_SAFETY_CRITICAL_IEC61508
    if (OSSafetyCriticalStartFlag == OS_TRUE) {
        OS_SAFETY_CRITICAL_EXCEPTION();
    }
#endif

#if OS_ARG_CHK_EN > 0u
    switch (opt) {                                          /* Validate arguments                                     */
        case OS_TMR_OPT_PERIODIC:
             if (period == 0u) {
                 *perr = OS_ERR_TMR_INVALID_PERIOD;
                 return ((OS_TMR *)0);
             }
             break;

        case OS_TMR_OPT_ONE_SHOT:
             if (dly == 0u) {
                 *perr = OS_ERR_TMR_INVALID_DLY;
                 return ((OS_TMR *)0);
             }
             break;

        default:
             *perr = OS_ERR_TMR_INVALID_OPT;
             return ((OS_TMR *)0);
    }
#endif
    if (OSIntNesting > 0u) {                                /* See if trying to call from an ISR                      */
        *perr  = OS_ERR_TMR_ISR;
        return ((OS_TMR *)0);
    }
    OSSchedLock();
    ptmr = OSTmr_Alloc();                                   /* Obtain a timer from the free pool                      */
    if (ptmr == (OS_TMR *)0) {
        OSSchedUnlock();
        *perr = OS_ERR_TMR_NON_AVAIL;
        return ((OS_TMR *)0);
    }
    ptmr->OSTmrState       = OS_TMR_STATE_STOPPED;          /* Indicate that timer is not running yet                 */
    ptmr->OSTmrDly         = dly;
    ptmr->OSTmrPeriod      = period;
    ptmr->OSTmrOpt         = opt;
    ptmr->OSTmrCallback    = callback;
    ptmr->OSTmrCallbackArg = callback_arg;
#if OS_TMR_CFG_NAME_EN > 0u
    ptmr->OSTmrName        = pname;
#endif
    OSSchedUnlock();
    *perr = OS_ERR_NONE;
    return (ptmr);
}
/*!
  ****************************************************************************
    @brief Allocates a thread slot and returns the slot number

    This function allocates the slot (i.e memory location of a word size ) 
    from the thread local storage buffer and returns the slot number.

    @param[out] pnThreadSlotKey       - Pointer to return the slot number if a
                                        free slot is found.  Must be populated
                                        with ADI_OSAL_TLS_UNALLOCATED.  If a
                                        valid slot is already present in the
                                        supplied address this API returns
                                        success.

    @param[in] pTerminateCallbackFunc - Pointer to a function that gets called 
                                        when the slot is freed.  Can be NULL
                                        if the callback function is not
                                        required.

    @return ADI_OSAL_SUCCESS       - If the function successfully allocated the 
                                     slot.
    @return ADI_OSAL_FAILED        - If the function failed to allocate the 
                                     slot.
    @return ADI_OSAL_CALLER_ERROR  - If the function is invoked from an invalid 
                                     location (i.e an ISR)

    Note:
     "pnThreadSlotKey"  will be set to  ADI_OSAL_INVALID_THREAD_SLOT   if
      there are no free slots.
  @ingroup thread local storage
*****************************************************************************/
ADI_OSAL_STATUS
adi_osal_ThreadSlotAcquire(ADI_OSAL_TLS_SLOT_KEY     *pnThreadSlotKey,
                           ADI_OSAL_TLS_CALLBACK_PTR pTerminateCallbackFunc)
{
    OS_TLS_ID nSlotIndex;
    uint32_t nSlotBit;

    INT8U nErr;
    ADI_OSAL_STATUS  eRetStatus = ADI_OSAL_FAILED;

    /*!
        @internal
        @var _adi_osal_gTLSUsedSlots
             Word used in the management of allocated TLS slots.
             Bits are used to represent the status of the slot. Bit 0 corresponds
             to slot number 0 and slot number 30 corresponds bit number 30.
             A slot is free if the corresponding bit is clear and a
             slot is acquired if the corresponding bit is set. Initially all
             the slot bits are clear.
        @endinternal
    */
    static uint32_t _adi_osal_gTLSUsedSlots = 0u;

#ifdef OSAL_DEBUG
    if (CALLED_FROM_AN_ISR)
    {
        return (ADI_OSAL_CALLER_ERROR);
    }
#endif /* OSAL_DEBUG */

    /* Lock the scheduler - as a task may be deleted while a callback is being
     * installed.  */
    OSSchedLock();

    /* If the passed-in slot number has already been allocated, then we return
     * successfully.  We check that -
     *  - It has the correct TLS signature
     *  - The slot has been (and is still) allocated.
     */
    if(IsValidTLSKey(*pnThreadSlotKey))
    {
        /* Extract the slot number from the TLS key, and convert to a bit
         * position */
        nSlotBit = 1ul << (*pnThreadSlotKey & TLS_MASK_NUM);

        if(0u != (_adi_osal_gTLSUsedSlots & nSlotBit))
        {
            /* The slot has previously been allocated using the supplied
             * address */
            OSSchedUnlock();
            return(ADI_OSAL_SUCCESS);
        }
    }
    /* Before we allocate a slot, the address to be written-to must have
     * an "unallocated" key.
     */
    if(*pnThreadSlotKey != ADI_OSAL_TLS_UNALLOCATED)
    {
        OSSchedUnlock();
        *pnThreadSlotKey = ADI_OSAL_INVALID_THREAD_SLOT;
        return(eRetStatus);
    }

    nSlotIndex = OS_TLS_GetID(&nErr);

    /* If the callback is NULL we don't put anything in the slot to save us
     * from calling the OSAL function
     */
    if ((nErr == OS_ERR_NONE) && (NULL != pTerminateCallbackFunc))
    {
        OS_TLS_SetDestruct(nSlotIndex,
                           _adi_osal_TLSCallback,
                           &nErr);
    }

    /* there was an error either allocating the slot or installing the 
     * callback 
     */
    if (nErr != OS_ERR_NONE)
    {
       *pnThreadSlotKey = ADI_OSAL_INVALID_THREAD_SLOT;
        OSSchedUnlock();
       return(eRetStatus);
    }

    /* everything went well so we record the used slot and we finish */

    _adi_osal_gaTLSCallbacks[nSlotIndex] = pTerminateCallbackFunc;
        nSlotBit = ((uint32_t) 1 << (nSlotIndex));
    /*
     * Set the context switch-sensitive globals
     * before breaking and releasing the scheduler lock :
     * - set the bit in the TLS available slot word.
     * - set the callback function, NULL pointers will not be called.
     */
    _adi_osal_gTLSUsedSlots      |= nSlotBit;

    OSSchedUnlock();

    *pnThreadSlotKey = (nSlotIndex | TLS_SIGNATURE);
    return (ADI_OSAL_SUCCESS);
}
Beispiel #25
0
BOOLEAN  OSTmrStop (OS_TMR  *ptmr,
                    INT8U    opt,
                    void    *callback_arg,
                    INT8U   *perr)
{
    OS_TMR_CALLBACK  pfnct;


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
    }
#endif

#if OS_ARG_CHK_EN > 0u
    if (ptmr == (OS_TMR *)0) {
        *perr = OS_ERR_TMR_INVALID;
        return (OS_FALSE);
    }
#endif
    if (ptmr->OSTmrType != OS_TMR_TYPE) {                         /* Validate timer structure                         */
        *perr = OS_ERR_TMR_INVALID_TYPE;
        return (OS_FALSE);
    }
    if (OSIntNesting > 0u) {                                      /* See if trying to call from an ISR                */
        *perr  = OS_ERR_TMR_ISR;
        return (OS_FALSE);
    }
    OSSchedLock();
    switch (ptmr->OSTmrState) {
        case OS_TMR_STATE_RUNNING:
             OSTmr_Unlink(ptmr);                                  /* Remove from current wheel spoke                  */
             *perr = OS_ERR_NONE;
             switch (opt) {
                 case OS_TMR_OPT_CALLBACK:
                      pfnct = ptmr->OSTmrCallback;                /* Execute callback function if available ...       */
                      if (pfnct != (OS_TMR_CALLBACK)0) {
                          (*pfnct)((void *)ptmr, ptmr->OSTmrCallbackArg);  /* Use callback arg when timer was created */
                      } else {
                          *perr = OS_ERR_TMR_NO_CALLBACK;
                      }
                      break;

                 case OS_TMR_OPT_CALLBACK_ARG:
                      pfnct = ptmr->OSTmrCallback;                /* Execute callback function if available ...       */
                      if (pfnct != (OS_TMR_CALLBACK)0) {
                          (*pfnct)((void *)ptmr, callback_arg);   /* ... using the 'callback_arg' provided in call    */
                      } else {
                          *perr = OS_ERR_TMR_NO_CALLBACK;
                      }
                      break;

                 case OS_TMR_OPT_NONE:
                      break;

                 default:
                     *perr = OS_ERR_TMR_INVALID_OPT;
                     break;
             }
             OSSchedUnlock();
             return (OS_TRUE);

        case OS_TMR_STATE_COMPLETED:                              /* Timer has already completed the ONE-SHOT or ...  */
        case OS_TMR_STATE_STOPPED:                                /* ... timer has not started yet.                   */
             OSSchedUnlock();
             *perr = OS_ERR_TMR_STOPPED;
             return (OS_TRUE);

        case OS_TMR_STATE_UNUSED:                                 /* Timer was not created                            */
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INACTIVE;
             return (OS_FALSE);

        default:
             OSSchedUnlock();
             *perr = OS_ERR_TMR_INVALID_STATE;
             return (OS_FALSE);
    }
}
Beispiel #26
0
void  OS_TmrTask (void  *p_arg)
{
    CPU_BOOLEAN          done;
    OS_ERR               err;
    OS_TMR_CALLBACK_PTR  p_fnct;
    OS_TMR_SPOKE        *p_spoke;
    OS_TMR              *p_tmr;
    OS_TMR              *p_tmr_next;
    OS_TMR_SPOKE_IX      spoke;
    CPU_TS               ts;
    CPU_TS               ts_start;
    CPU_TS               ts_end;



    p_arg = p_arg;                                               /* Not using 'p_arg', prevent compiler warning       */
    while (DEF_ON) {
        (void)OSTaskSemPend((OS_TICK )0,                         /* Wait for signal indicating time to update tmrs    */
                            (OS_OPT  )OS_OPT_PEND_BLOCKING,
                            (CPU_TS *)&ts,
                            (OS_ERR *)&err);

        OSSchedLock(&err);
        ts_start = OS_TS_GET();
        OSTmrTickCtr++;                                          /* Increment the current time                        */
        spoke    = (OS_TMR_SPOKE_IX)(OSTmrTickCtr % OSCfg_TmrWheelSize);
        p_spoke  = &OSCfg_TmrWheel[spoke];
        p_tmr    = p_spoke->FirstPtr;
        done     = DEF_FALSE;
        while (done == DEF_FALSE) {
            if (p_tmr != (OS_TMR *)0) {
                p_tmr_next = (OS_TMR *)p_tmr->NextPtr;           /* Point to next tmr to update because current ...   */
                                                                 /* ... timer could get unlinked from the wheel.      */
                if (OSTmrTickCtr == p_tmr->Match) {              /* Process each timer that expires                   */
                    OS_TmrUnlink(p_tmr);                         /* Remove from current wheel spoke                   */
                    if (p_tmr->Opt == OS_OPT_TMR_PERIODIC) {
                        OS_TmrLink(p_tmr,
                                   OS_OPT_LINK_PERIODIC);        /* Recalculate new position of timer in wheel        */
                    } else {
                        p_tmr->State = OS_TMR_STATE_COMPLETED;   /* Indicate that the timer has completed             */
                    }
                    p_fnct = p_tmr->CallbackPtr;                 /* Execute callback function if available            */
                    if (p_fnct != (OS_TMR_CALLBACK_PTR)0) {
                        (*p_fnct)((void *)p_tmr,
                                  p_tmr->CallbackPtrArg);
                    }
                    p_tmr = p_tmr_next;                          /* See if next timer matches                         */
                } else {
                    done  = DEF_TRUE;
                }
            } else {
                done = DEF_TRUE;
            }
        }
        ts_end = OS_TS_GET() - ts_start;                         /* Measure execution time of timer task              */
        OSSchedUnlock(&err);
        if (OSTmrTaskTimeMax < ts_end) {
            OSTmrTaskTimeMax = ts_end;
        }
    }
}
Beispiel #27
0
/*
* This function is used to re-allow rescheduling.
*/
extern  void taskUnlock(void)
{
    OSSchedUnlock();
}
Beispiel #28
0
void print_string(CHAR *fmt, ...)
{
    va_list v_list;
    INT32S ret;

	if(print_output_type & PRINT_OUTPUT_USB)
	{

#if _OPERATING_SYSTEM != _OS_NONE	// Soft Protect for critical section
		OSSchedLock();
#endif
		/* redirect print_string to usb_logger_buf, write operation */
		va_start(v_list, fmt);
		ret = vsnprintf(logger_write_ptr, USB_LOGGER_BUF_SIZE, fmt, v_list);
		if(ret < 0)
		{
			return;
		}
	    //vsprintf(usb_logger_buf, fmt, v_list);
	    va_end(v_list);
	    
	     
	    /* Update write pointer */
	    if(logger_write_ptr < (usb_logger_buf + USB_LOGGER_BUF_TOTAL_SIZE - USB_LOGGER_BUF_SIZE ))
	    	logger_write_ptr += USB_LOGGER_BUF_SIZE;
	    else
	    	logger_write_ptr = usb_logger_buf;
	    
	    /* Check if write ptr is equal to read ptr, if yes update read ptr */
	    if(logger_write_ptr == logger_read_ptr)
	    {
	    	if(logger_read_ptr < (usb_logger_buf + USB_LOGGER_BUF_TOTAL_SIZE - USB_LOGGER_BUF_SIZE ))
	    		logger_read_ptr += USB_LOGGER_BUF_SIZE;
	    	else
	    		logger_read_ptr = usb_logger_buf;
		}   
	    
	    //loggerwritecnt = (logger_write_ptr - usb_logger_buf) >> 9;
	    //loggerreadcnt = (logger_read_ptr - usb_logger_buf) >> 9;		
#if _OPERATING_SYSTEM != _OS_NONE			//exit critical section
		OSSchedUnlock();
#endif
	}
	
	if(print_output_type & PRINT_OUTPUT_UART)
	{
		CHAR *pt;
	    va_start(v_list, fmt);
	    ret = vsnprintf(print_buf, PRINT_BUF_SIZE, fmt, v_list);
		if(ret < 0)
		{
			return;
		}
	    //vsprintf(print_buf, fmt, v_list);
	    va_end(v_list);
	
	    print_buf[PRINT_BUF_SIZE-1] = 0;
	    pt = print_buf;
	    while (*pt) {
			SEND_DATA(*pt);
			pt++;
		}
	}	
}