Esempio n. 1
0
Bool		bfqAllocBuffer		( BufferQueue_Handle queue, Ptr * buffer, Uns timeout )
{
	BufferQueue_Frame * frame;
	
	// wait until an empty buffer is available, timeout
	// if necessary.
	if (! SEM_pend(&(queue->semEmptyBuffers), timeout) )
	{
		return FALSE;
	}
	
	// double check
	if ( QUE_empty(&(queue->queEmptyBuffers)) )
		return FALSE;
		
	// Get the frame from the queue and double check it	
	frame = QUE_get((Ptr)&(queue->queEmptyBuffers));
	if ((Ptr)frame == (Ptr)&(queue->queEmptyBuffers))
		return FALSE;
	
	// Copy the pointer
	*buffer = frame->Buffer;
	
	// put the frame to the empty frames queue
	QUE_put( &(queue->queEmptyFrames), frame);	
	
	return TRUE;
}
void FollowUpMonitor()
{
	int i;

	while(true)
	{
		// Check on each follow up item
		for(i = 0; i < NUM_FOLLOW_UP_ITEMS; i++)
		{
			// If the item is active, take care of it
			if(globals.followUpMonitor.followUpItems[i].active == true)
			{
				// Decrement the counter
				globals.followUpMonitor.followUpItems[i].followUpCounter--;

				// If the counter has zeroed out, call the callback function
				if(globals.followUpMonitor.followUpItems[i].followUpCounter == 0)
				{
					// Call the callback function
					(*globals.followUpMonitor.followUpItems[i].callbackFunction)(globals.followUpMonitor.followUpItems[i].callbackFunctionParameters,i);

					// If the item doesn't expire, reset its counter, otherwise deactivate it so it can be used later
					if(globals.followUpMonitor.followUpItems[i].doesNotExpire)
						globals.followUpMonitor.followUpItems[i].followUpCounter = globals.followUpMonitor.followUpItems[i].timeToFollowUp;
					else
						globals.followUpMonitor.followUpItems[i].active = false;
				}
			}
		}
		SEM_pend(&FollowUpMonitorSem,SYS_FOREVER);
	}
}
Esempio n. 3
0
/*
 *  ======== DPI_close ========
 */
Static Int DPI_close(DEV_Handle dev)
{
    PipeObj         *pipe = (PipeObj *)dev->object;
    SPipeObj        *sPipe = pipe->sPipe;

    MEM_free(0, pipe, sizeof(PipeObj));
    
    SEM_pend(mutex, SYS_FOREVER);

    sPipe->device[dev->mode] = NULL;
    sPipe->readySem[dev->mode] = NULL;
             
    if (sPipe->device[DEV_INPUT] == NULL &&
                sPipe->device[DEV_OUTPUT] == NULL) {
        /* delete all shared pipe sub-objects */
        SEM_delete(sPipe->dataSem);
        SEM_delete(sPipe->freeSem);

        /* remove sPipe obj from sPipeList */
        QUE_remove(&sPipe->link);
        
        /* delete sPipe object itself */
        MEM_free(0, sPipe, sizeof (SPipeObj));
    }

    SEM_post(mutex);

    return (SYS_OK);
}
/**
* \brief   EDMA3 OS Semaphore Take
*
*      This function takes a semaphore token if available.
*      If a semaphore is unavailable, it blocks currently
*      running thread in wait (for specified duration) for
*      a free semaphore.
* \param   hSem [IN] is the handle of the specified semaphore
* \param   mSecTimeout [IN] is wait time in milliseconds
* \return  EDMA3_DRV_Result if successful else a suitable error code
*/
EDMA3_DRV_Result edma3OsSemTake(EDMA3_OS_Sem_Handle hSem, int mSecTimeout)
{
#if 0  //wj
  EDMA3_DRV_Result semTakeResult = EDMA3_DRV_SOK;
  unsigned short semPendResult;
  
  if(NULL == hSem)
  {
    semTakeResult = EDMA3_DRV_E_INVALID_PARAM;
  }
  else
  {
    if (TSK_self() != (TSK_Handle)&KNL_dummy)
    {
      semPendResult = SEM_pend(hSem, mSecTimeout);
      if (semPendResult == FALSE)
      {
        semTakeResult = EDMA3_DRV_E_SEMAPHORE;
      }
    }
  }
  
  return semTakeResult;
#else
  return 0;
#endif
}
Esempio n. 5
0
/* ARGSUSED */
Int smain(Int argc, Char * argv[])
{
    TSK_Handle tsk;
    TSK_Attrs attrs = TSK_ATTRS;
    Int i;

    GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_ENTER, "_smain> Enter \n");

    done = SEM_create(0, NULL);
    mutex = SEM_create(1, NULL);

    if ((done == NULL) || (mutex == NULL)) {

        SYS_abort("Sem create failed \n");
    }

/*
 * Do I care about this ? 
 */
    attrs.stackseg = EXTMEM_HEAP;

/*
 * Use a bigger stack size when printing out trace 
 */
    attrs.stacksize = 0x1000;

    for (i = 0; i < NUMTASKS; i++) {

        attrs.priority = attrsTable[i].priority;
        tsk = TSK_create((Fxn)rmanTask, &attrs, 
                                (Arg)(attrsTable[i].scratchId),
                                (Arg)(&(attrsTable[i].id)),
                                (Arg)(attrsTable[i].priority),
                (Arg)(i +1),
                (Arg)(attrsTable[i].yieldFlag));
        if (tsk == NULL) {

            GT_1trace(ti_sdo_fc_rman_examples_hdvicp, GT_7CLASS, "_rman> " 
                "Task #%d create failed \n",i);

            SYS_abort("TSK_create() of task %d failed\n",i+1); 
        }
    }

    for (i=0; i < NUMTASKS; i++) {
        SEM_pend(done, SYS_FOREVER);
    }

    GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_4CLASS, "_smain> "
    "TEST PASSED \n");

    SEM_delete(mutex);
    SEM_delete(done);

    GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_ENTER, "_smain> Exit \n");

    return 0;
}
Esempio n. 6
0
/******************************************************************************
 * Fifo_get
 ******************************************************************************/
Int Fifo_get(Fifo_Handle hFifo, Ptr ptrPtr)
{
    Int flush;
    Fifo_Elem * elem;
    Ptr * p = (Ptr *)ptrPtr;

    assert(hFifo);
    assert(ptrPtr);

    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    flush = hFifo->flush;
    SEM_post(&hFifo->mutex);

    /* If pipe is already flushed, do not block */
    if (flush) {
        return Dmai_EFLUSH;
    }

    /* Wait for element from other thread */
    SEM_pend(&hFifo->sem, SYS_FOREVER);
   
    /* Handle flushed fifo */
    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    flush = hFifo->flush;
    if (flush) {
        hFifo->flush = FALSE;
    }
    SEM_post(&hFifo->mutex);
    if (flush) {
        return Dmai_EFLUSH;
    }
    
    /* Get an element from the Fifo queue */
    elem = (Fifo_Elem *)QUE_get(&hFifo->queue);
    *p = elem->ptr;
    if (BUF_free(hFifo->hBufPool, elem) != TRUE) {
        return Dmai_EFAIL;
    }    

    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    hFifo->numBufs--;
    SEM_post(&hFifo->mutex);

    return Dmai_EOK;
}
Esempio n. 7
0
/*
 *  ======== Sem_pend ========
 */
Int Sem_pend(Sem_Handle sem, UInt32 timeout)
{
    Int     status = Sem_EOK;

    if (SEM_pend((SEM_Handle)sem, timeout) == FALSE) {
        status = Sem_ETIMEOUT;
    }

    return (status);
}
Esempio n. 8
0
void TSK_SCI_C(void)
{
	while(1)
	{
		if(SEM_pend(&SEM_SCICComm, SYS_FOREVER) == 1)  //SCI通信100ms进一次
		{
			Scic_Parsing();
		}
	}
}
Esempio n. 9
0
/*
 *  ======== DPI_reclaim ========
 */
Static Int DPI_reclaim(DEV_Handle dev)
{
    PipeObj         *pipe = (PipeObj *)dev->object;

    if (SEM_pend(pipe->fromSem, dev->timeout)) {
        return (SYS_OK);
    }
    else {
        return (SYS_ETIMEOUT);
    }
}
Esempio n. 10
0
/******************************************************************************
 * Fifo_getNumEntries
 ******************************************************************************/
Int Fifo_getNumEntries(Fifo_Handle hFifo)
{
    Int numEntries;

    assert(hFifo);

    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    numEntries = hFifo->numBufs;
    SEM_post(&hFifo->mutex);

    return numEntries;
}
Esempio n. 11
0
/******************************************************************************
 * Fifo_flush
 ******************************************************************************/
Int Fifo_flush(Fifo_Handle hFifo)
{
    assert(hFifo);

    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    hFifo->flush = TRUE;
    SEM_post(&hFifo->mutex);

    /* Make sure any Fifo_get() calls are unblocked */
    SEM_post(&hFifo->sem);

    return Dmai_EOK;
}
Esempio n. 12
0
/*
 *  ======== DIO_tskIdle ========
 *  DIO_tskIdle() puts the device back to the state it was in just after
 *  DIO_open() was called.
 */
Int DIO_tskIdle(DEV_Handle device, Bool flush)
{
    DIO_Handle dio = (DIO_Handle)device->object;
    Uns         pendCount = 0;
    DEV_Frame   localFrame;
    Int         status;

    localFrame.status = IOM_PENDING;

    if (device->mode == DEV_INPUT || flush) {
        localFrame.cmd = IOM_ABORT;
    }
    else {
        localFrame.cmd = IOM_FLUSH;
    }

    status = dio->fxns->mdSubmitChan(dio->chanp, &localFrame);

    if (status == IOM_PENDING) {
        for (;;) {
            if (SEM_pend(dio->context.sems.complete, device->timeout)) {
                /*
                 * Break out of the for loop when the local abort/flush
                 * frame status shows that it is complete.
                 */
                if (localFrame.status == IOM_COMPLETED) {
                    break;
                }
                else {
                    /* keep track of data frame completions */
                    pendCount++;
                }
            }
            else {
                return (SYS_ETIMEOUT);
            }
        }

        /* 
         * Update complete semaphore so it corresponds to number of frames
         * on the 'todevice' queue.  'for' loop above may have made the 
         * complete sem count inconsistent.
         */
        while (pendCount--) {
            SEM_post(dio->context.sems.complete);
        }
    }

    return (SYS_OK);
}
Esempio n. 13
0
/*
 *  ======== DIO_tskReclaim ========
 */
Int DIO_tskReclaim(DEV_Handle device)
{
    DIO_Handle  dio = (DIO_Handle)device->object;

    /*
     * Wait here if there are no buffers on the device->fromdevice
     * queue.
     */
    if (SEM_pend(dio->context.sems.complete, device->timeout)) {
        return (SYS_OK);
    }
    else {
        return (SYS_ETIMEOUT);
    }
}
void SPITest()
{
#if defined(IS_ROUTER)
    Uint16 flit[NUM_CHARACTERS_IN_FLIT] = {
        0xCA5F, 0xCA5F, 0xCA5F, 0xCA5F, 0xCA5F,
        0xCA5F, 0xCA5F, 0xCA5F, 0xCA5F
    };
    Uint32 numTransmitsInGroup, numGroups = 0, numTransmits = 0;

    TSK_sleep(2000);
    while(numTransmits < 500000)
    {
        numTransmitsInGroup = 0;
        while(numTransmitsInGroup < 5000)
        {
            if(gpioDataRegisters.GPBDAT.bit.SWITCH1)
            {
                while(globals.processing.outboundFlitQueFull[PORTA]);
                EnqueOutboundFlit(flit,PORTA);
            }
            if(gpioDataRegisters.GPBDAT.bit.SWITCH2)
            {
                while(globals.processing.outboundFlitQueFull[PORTB]);
                EnqueOutboundFlit(flit,PORTB);
            }
            if(gpioDataRegisters.GPADAT.bit.SWITCH3)
            {
                while(globals.processing.outboundFlitQueFull[PORTC]);
                EnqueOutboundFlit(flit,PORTC);
            }
            if(gpioDataRegisters.GPADAT.bit.SWITCH4)
            {
                while(globals.processing.outboundFlitQueFull[PORTD]);
                EnqueOutboundFlit(flit,PORTD);
            }
            numTransmits++;
            numTransmitsInGroup++;
        }
        numGroups++;
        SetSevenSegmentDisplay(numGroups);
    }

    SEM_pend(&TestServiceSem,SYS_FOREVER);
#endif
}
void TestService(Void)
{
    // Wait for the system to finish initializing itself
    SEM_pend(&TestServiceSem,SYS_FOREVER);

    // Run the selected test

#if TEST == TEST_SPI
    SPITest();
#elif TEST == TEST_PROTOCOL
    //ProtocolTest1();
    //ProtocolTest2();
#elif TEST == TEST_MPI
    ProtocolTest3();
    //MPITest();
#endif

}
Esempio n. 16
0
File: task.c Progetto: Imara90/ESLab
Int Task_execute (Task_TransferInfo * info)
{
    int sum;

    //wait for semaphore
	SEM_pend (&(info->notifySemObj), SYS_FOREVER);

	//invalidate cache
    BCACHE_inv ((Ptr)buf, length, TRUE) ;

	//call the functionality to be performed by dsp
    sum = sum_dsp();
    
	//notify that we are done
    NOTIFY_notify(ID_GPP,MPCSXFER_IPS_ID,MPCSXFER_IPS_EVENTNO,(Uint32)0);
	//notify the result
    NOTIFY_notify(ID_GPP,MPCSXFER_IPS_ID,MPCSXFER_IPS_EVENTNO,(Uint32)sum);

    return SYS_OK;
}
// Spectrum Display Task code
void SpectrumDisplayTask(void)
{
	// display the play audio message
	print_playaudio();

	while (1)
	{
		// wait on bufferIn ready semaphore
		SEM_pend(&SEM_BufferInReady, SYS_FOREVER);
		// compute and display the bargraph
		if (DemoSwitchFlag)
		{
			calculate_FFT(bufferIn, 256);
			// clear the bufferInIdx to 0
			bufferInIdx = 0;
		}else
		{
			print_playaudio();
		}		
	}
}
Esempio n. 18
0
/* Perform Playback (Tx) audio algorithm processing */
void PbAudioAlgTsk(void)
{
    Int16 status;
    Int16 *pbOutBuf;
    Uint16 tempInBlk;

    while (1)
    {
        SEM_pend(&SEM_PbAudioAlg, SYS_FOREVER);

        /* Select AER output buffer */
        HWI_disable();
        pbOutBuf = ping_pong_i2sTxBuf + (!tx_buf_sel)*i2sTxBuffSz;
        HWI_enable();

        if ((usb_play_mode == TRUE) && (rdy_to_consume_asrc_output == TRUE))
        {
            /* Combine ASRC output */
            SWI_disable();
            tempInBlk = asrcOutputFifoInBlk;
            SWI_enable();
            status = combineAsrcOutput(asrcOutputFifo, 
                asrcOutputFifoBlkNumSamps, 
                tempInBlk, 
                &asrcOutputFifoOutBlk, 
                &asrcOutputFifoOutBlkSampCnt, 
                ASRC_NUM_CH_STEREO, 
                tempPbOutBuf, 
                i2sTxBuffSz>>1);
            if (status == CMBASRC_FIFO_UND)
            {
                asrcOutputFifoOutError++;
                LOG_printf(&trace, "ERROR: ASRC output FIFO UNDERFLOW");
                //LOG_printf(&trace, "%04x %d", (asrcOutputFifoInBlk<<8) | asrcOutputFifoOutBlk, asrcOutputFifoOutBlkSampCnt); // debug
            }
        }
        else if (usb_play_mode == TRUE)
Esempio n. 19
0
Bool		bfqGetBuffer		( BufferQueue_Handle queue, Ptr * buffer, Uns timeout )
{
	BufferQueue_Frame * frame;
	
	// wait until a full buffer is available, timeout
	// if necessary.
	if (! SEM_pend(&(queue->semFullBuffers), timeout) )
	{
		return FALSE;
	}
	
	// Get the frame from the queue and double check it
	assertLog(! QUE_empty(&(queue->queFullBuffers)));
	frame = QUE_get(&(queue->queFullBuffers));
	assertLog((Ptr)frame != (Ptr)&(queue->queFullBuffers));
	
	// put the frame to the empty frames queue
	QUE_put( &(queue->queEmptyFrames), frame);
	
	// Copy the pointer
	*buffer = frame->Buffer;
	
	return TRUE;
}
Esempio n. 20
0
/******************************************************************************
 * Fifo_put
 ******************************************************************************/
Int Fifo_put(Fifo_Handle hFifo, Ptr ptr)
{
    Fifo_Elem * elem;
    
    assert(hFifo);
    assert(ptr);

    SEM_pend(&hFifo->mutex, SYS_FOREVER);
    hFifo->numBufs++;
    SEM_post(&hFifo->mutex);

    elem = BUF_alloc(hFifo->hBufPool);
    if (elem == NULL) {
        Dmai_err0("Failed to allocate space for Fifo Object\n");
        return Dmai_EFAIL;
    }
    elem->ptr = ptr;
    
    /* Putting an element on the queue with ptr as payload */
    QUE_put(&hFifo->queue, (QUE_Elem *)elem);
    SEM_post(&hFifo->sem);
    
    return Dmai_EOK;
}
void MPITest()
{
    int rank, numNodes;
    Uint16 sendBuf[1], *receiveBuf;
    Uint16 i, j;
    MPI_Status status;
    Uint32 startTime;
    double elapsedTime;

    SEM_pend(&TestServiceSem,SYS_FOREVER);

    // Generate the x data
    for(i = 0; i < 14; i++)
    {
        for(j = 0; j < 25; j++)
            xglobal[i * 50 + j] = (j / 4);
        for(j = 0; j < 25; j++)
            xglobal[i * 50 + j + 25] = 6 - (j / 4);
    }

    // Generate the y data
    for(i = 0; i < 28; i++)
    {
        for(j = 0; j < 25; j++)
            yglobal[i * 25 + j] = j / 2;
    }

    // Initialize MPI
    MPI_Init(NULL,NULL);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    globals.processing.sevenSegmentUpperDigit = SEVENSEG_1DASH;

    // Distribute the number of nodes to use
    if(rank == 0)
    {
        numNodes = (gpioDataRegisters.GPBDAT.bit.SWITCH1 << 3) + (gpioDataRegisters.GPBDAT.bit.SWITCH2 << 2) +
                   (gpioDataRegisters.GPADAT.bit.SWITCH3 << 1) + (gpioDataRegisters.GPADAT.bit.SWITCH4);
        sendBuf[0] = numNodes;
        for(i = 1; i <= 6; i++)
            MPI_Send(sendBuf,1,MPI_SHORT,i,0,MPI_COMM_WORLD);
    }
    else
    {
        MPI_Recv((void**)(&receiveBuf),1,MPI_SHORT,0,0,MPI_COMM_WORLD,&status);
        numNodes = receiveBuf[0];
        MemFree(receiveBuf);
    }
    MPI_Barrier(MPI_COMM_WORLD);

    // If this node is participating in the convolution
    if(rank < numNodes)
    {
        globals.processing.sevenSegmentUpperDigit = SEVENSEG_2DASH;

        startTime = timer0Registers.TIM.all;
        Convolution(xglobal,yglobal,100,100,resultglobal,numNodes);
        elapsedTime = TimeDifference(startTime, timer0Registers.TIM.all);

        // Finalize MPI
        if(rank == 0)
        {
            globals.processing.sevenSegmentLowerDigit = SEVENSEG_FINAL;
            globals.processing.sevenSegmentUpperDigit = SEVENSEG_FINAL;
        }
        else
            globals.processing.sevenSegmentUpperDigit = SEVENSEG_3DASH;
    }
    else
    {
        globals.processing.sevenSegmentUpperDigit = SEVENSEG_FINAL;
    }
    SEM_pend(&TestServiceSem,SYS_FOREVER);
}
Esempio n. 22
0
/*
 *  ======== DPI_open ========
 */
Static Int DPI_open(DEV_Handle dev, String name)
{
    PipeObj         *pipe;
    SPipeObj        *sPipe, *tmpPipe;

    /* decode and validate devid */
    if (dev->devid < 0) {
        dev->devid = atoi(name);
    }

    SEM_pend(mutex, SYS_FOREVER);

    /* search pipe list for previously opened pipe with same id */
    sPipe = MEM_ILLEGAL;
    if (!QUE_empty(sPipeList)) {
        tmpPipe = (SPipeObj *)QUE_head(sPipeList);
        do {
            if (tmpPipe->id == dev->devid) {
                sPipe = tmpPipe;
                break;
            }
            tmpPipe = (SPipeObj *)QUE_next((&tmpPipe->link));
        } while (tmpPipe != (SPipeObj *)sPipeList);
    }

    if (sPipe == MEM_ILLEGAL) {
        /*
         * Allocate and initialize SPipeObj on first open.
         */
        sPipe = mkSPipe(dev);
        if (sPipe == MEM_ILLEGAL) {
            SEM_post(mutex);
            return SYS_EALLOC;
        }
        QUE_put(sPipeList, &sPipe->link);
    }
    else {      /* sPipe found on list */
        if (sPipe->device[dev->mode] != NULL) {
            /*
             * Only one input and one output allowed
             */
            SEM_post(mutex);
            return SYS_EBUSY;
        }
    }
    sPipe->device[dev->mode] = dev;
    SEM_post(mutex);

    pipe = MEM_alloc(0, sizeof (PipeObj), 0);
    if (pipe == MEM_ILLEGAL) {
        /*
         * We need to undo work done by mkSPipe() if first open.
         * Also need to undo changes to sPipeList queue.
         */
        QUE_remove(&sPipe->link);
        rmSPipe(sPipe);
        return SYS_EALLOC;
    }

    /*
     * Criss-cross SEM handles so both sides are referencing
     * the same physical objects.
     */
    if (dev->mode == DEV_INPUT) {
        pipe->fromSem = sPipe->dataSem;
        pipe->toSem = sPipe->freeSem;
    }
    else {
        pipe->toSem = sPipe->dataSem;
        pipe->fromSem = sPipe->freeSem;
    }

    /*
     * Point things around.
     */
    pipe->sPipe = sPipe;
    dev->object = (Ptr)pipe;

    return (SYS_OK);
}
void ProtocolTest3()
{
#if PROFILE_TEST_SERVICE == true
    double executionTime;
    Uint32 startTime;
#endif
    struct Packet newPacket;
    Uns interruptStatus;
    Uint16 x[100], i, j, destination;
    double executionTime = 0;
    double avgTime[9] = {0,0,0,0,0,0,0,0,0};
    double minTime[9] = {DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX};
    double maxTime[9] = {DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN};
    Uint32 startTime = 0;
    Uint32 numSamples;

    SEM_pend(&TestServiceSem,SYS_FOREVER);

    for(i = 0; i < 100; i++)
        x[i] = i;

    if(globals.protocol.address == 1)
    {
        globals.processing.sevenSegmentUpperDigit = SEVENSEG_1DASH;

        destination = (gpioDataRegisters.GPBDAT.bit.SWITCH1 << 3) + (gpioDataRegisters.GPBDAT.bit.SWITCH2 << 2) +
                      (gpioDataRegisters.GPADAT.bit.SWITCH3 << 1) + (gpioDataRegisters.GPADAT.bit.SWITCH4);

        interruptStatus = HWI_disable();
        numSamples = 0;
        for(j = 0; j < 100; j++)
        {
            startTime = timer0Registers.TIM.all;
            GenerateRoutingPath(globals.protocol.address, 1, &newPacket);
            executionTime = TimeDifference(startTime, timer0Registers.TIM.all);
            avgTime[1] = (avgTime[1] * numSamples) + executionTime;
            numSamples++;
            avgTime[1] /= numSamples;
            if(executionTime < minTime[1])
                minTime[1] = executionTime;
            else if(executionTime > maxTime[1])
                maxTime[1] = executionTime;
        }
        for(i = 3; i <= 8; i++)
        {
            numSamples = 0;
            for(j = 0; j < 100; j++)
            {
                startTime = timer0Registers.TIM.all;
                GenerateRoutingPath(globals.protocol.address, i, &newPacket);
                executionTime = TimeDifference(startTime, timer0Registers.TIM.all);
                avgTime[i] = (avgTime[i] * numSamples) + executionTime;
                numSamples++;
                avgTime[i] /= numSamples;
                if(executionTime < minTime[i])
                    minTime[i] = executionTime;
                else if(executionTime > maxTime[i])
                    maxTime[i] = executionTime;
            }
        }
        HWI_restore(interruptStatus);
        asm(" NOP");

        for(i = 0; i < 100; i++)
        {
            for(j = 0; j < 50; j++)
            {
                InitializePacket(&newPacket, PACKET_ID_UNDEFINED);

                // Create the data transfer packet
                newPacket.a.communicationType = COMM_TYPE_UNICAST;
                newPacket.transmissionInfo.destination = 7;
                newPacket.b.command = COMMAND_DATA_TRANSFER;
                newPacket.b.packetSequenceStep = SEQUENCE_DATA_TRANSFER_REQUEST_TRANSFER;

                // Set the data
                newPacket.dataBuffer = x;
                newPacket.dataBufferInfo.dataBufferLength = 10;

                SendDataPacket(&newPacket);

                InitializePacket(&newPacket, PACKET_ID_UNDEFINED);

                // Create the data transfer packet
                newPacket.a.communicationType = COMM_TYPE_UNICAST;
                newPacket.transmissionInfo.destination = 8;
                newPacket.b.command = COMMAND_DATA_TRANSFER;
                newPacket.b.packetSequenceStep = SEQUENCE_DATA_TRANSFER_REQUEST_TRANSFER;

                // Set the data
                newPacket.dataBuffer = x;
                newPacket.dataBufferInfo.dataBufferLength = 10;

                SendDataPacket(&newPacket);

                while(globals.statistics.packet.numDataTransfersSucceeded + globals.statistics.packet.numDataTransfersExpired +
                        globals.statistics.packet.numDataTransfersFailed < globals.statistics.packet.numDataTransfersSetup);

            }
            if(globals.processing.sevenSegmentUpperDigit == SEVENSEG_2DASH)
                globals.processing.sevenSegmentUpperDigit = SEVENSEG_1DASH;
            else
                globals.processing.sevenSegmentUpperDigit = SEVENSEG_2DASH;
        }
        globals.processing.sevenSegmentUpperDigit = SEVENSEG_3DASH;
    }
}
Esempio n. 24
0
void CClassification::EnterTask()
{
#ifndef _WINDOWS // ------- Don't compile on windows -----

	Uint32 unIntervalTicks;
	
	Bool bLed2 = FALSE;
	ledLight( 2, FALSE );
	
	// Initialize the conveyor device driver and register the trigger semaphore.
	convInit( );
	SEM_new( &m_semTrigger, 0 );
	
	convRegisterSemTrigger( &m_semTrigger, &m_bTrigger );	
	
	// Reset statstics
	GetStats( NULL, TRUE );

	// Initialize the high res timer
	timeInit();
	
	// Pre-calculate the maximum wait time for the semaphore.
	unIntervalTicks = hlpMsToTicks( 1000 * MAXWAIT_SECONDS );
	
	// Open the interlink UART channel and configure it.
	m_hPPUSerial = serOpen( INTERLINK_UART_CHAN, sizeof( ClassificationTable ) *4 );
	assertLog( m_hPPUSerial != NULL );
	serConfigChannel( m_hPPUSerial, 115000, FALSE, FALSE, FALSE );	
	
	// Initialize the jet controller
	TSK_sleep( 2000 );
	CJetControl::Instance()->Init();
	
	// Start watchdog and set it to twice the time of our maximum interval.
	m_unWatchId = CWatchdog::Instance()->AddToWatch( "Classification", MAXWAIT_SECONDS * 2 );
	CWatchdog::Instance()->EnableWatch( m_unWatchId, TRUE );
	
	while( 1 )
	{
			
		// Wait for a trigger signal, timeout at some time to reset watchdog
		if ( SEM_pend( &m_semTrigger, unIntervalTicks ) )
		{
			// Succesfully received a trigger
			ledLight( 2, bLed2 );
			bLed2 = !bLed2;			
						
			// Get the trigger time as exact as possible.
			Uint32 unCurTime = convGetLastTriggerTime();
						
			// Increment our trigger counter.
			m_unCurrentTriggerPulse++;
			// dbgLog( "Entering Trigger %d", m_unCurrentTriggerPulse );
			
			// Store that trigger in the stats. This increments the number of possible potatoes by the number
			// of lanes.
			m_sClassificationStats.unNumPossible += m_nNumLanes;
			
			// See if we're in service mode and handle it.
			if ( m_csmServiceMode != CSM_NORMAL )
			{
				if (   (m_csmServiceMode == CSM_ADJUST_SMALL_EJECTION_PARAMS )
					|| (m_csmServiceMode == CSM_ADJUST_MEDIUM_EJECTION_PARAMS )
					|| (m_csmServiceMode == CSM_ADJUST_LARGE_EJECTION_PARAMS ) )
					ServiceGenParamAdjustCommands( unCurTime );
			}
			else
			{		
				// If not in service mode, see if we've got any due ejections to make and generate
				// the commands for it.
				EjectionTable * pTable;
				
				// See if any ejections are due and generate the jetcontrol commands, which are then
				// sent to the jet control.
				pTable = GetDueEjectionTable();
				if ( pTable != NULL )
				{
					// Generate ejection commands, but only if we're in classification mode.
					if ( m_eOperationMode == OP_CLASSIFICATION )
					{
						GenerateEjectionCommands( pTable, unCurTime );
					}
					ReleaseEjectionTable( pTable );
				}
							
				// Now we have to classify the potatoes and create the ejection table for the current
				// line. Only build the table if we've got a reference to the global potato table
				if ( m_pPotatoTable != NULL )
				{												
					// Build the local classification table (i.e. the per-frame classification)
					BuildTable( &m_LocalClassificationTable,  m_pPotatoTable );
					
					// Only exchange tables if we're in classification mode.
					if ( m_eOperationMode == OP_CLASSIFICATION )
					{					
						// Exchange the table with the other DSP
						if ( ExchangeTables( &m_LocalClassificationTable, &m_ForeignClassificationTable ) == TRUE )
						{
							MergeTables( &m_LocalClassificationTable, &m_ForeignClassificationTable );
						}
					}
						
					// Classify the potatoes using a new ejection table. This, we'll
					// have to do even in calibration mode, because of the statistics
					// for the GUI.
					pTable = GetNewEjectionTable( m_nNumTriggerPulsesDelay );
					if ( pTable != NULL )
					{
						ClassifyPotatoes( & m_LocalClassificationTable, &m_ForeignClassificationTable, pTable );
					}	
					
				} // if potatoobject table accessible
				
			} // if not in servicemode
			
		} // if trigger occured
		
		else
		{
			// Clean the objects list from time to time, if we don't receive trigger signals for
			// a long time. This prevents the number of objects from growing to big.
			CleanObjects( m_pPotatoTable );	
			
			// Check for service operation
			if ( m_csmServiceMode == CSM_CHECK_JETS )
				ServiceGenJetCheckCommands();	
						
		}
		
		// See if any of the strictness values changed and apply it to the properties
		if (   m_propSplitStrictness.HasChanged()
			|| m_propShapeStrictness.HasChanged()
			|| m_propGreenStrictness.HasChanged()
			|| m_propColorStrictness.HasChanged() )
		{
			ApplyStrictness();		
		}
		
		// Signal the watchdog.
		CWatchdog::Instance()->SignalAlive( m_unWatchId );	
		
	} // while(1)

#endif // ------------------------------------------------

}
/**
 * \function 	SendLiveStreamDataPort
 * \brief    	使用TCP/IP协议实现H.264子码流的网络传输
 * \			默认作为服务器端,Port = 61001		
 * \note		除了TCP/IP的传输方式外,智能相机系统还支持H.264视频流的RTSP方式传输,其传输过程已被封装在系统内部,默认TCP/IP传输的优先级高于RTSP传输的优先级
**/	
void SendLiveStreamDataPort_Another()
{
	SOCKET	sockThis, sockAccept;
	struct	sockaddr_in addrThis, addrAccept;
	int		nAddrLen;
	int		nVideoWidth = 1600, nVideoHeight = 1216;
	int 	i;
	int		isValidLink = 1;

	fdOpenSession( TaskSelf() );

	do
	{
		g_pBuffsLiveStream_Another = MEM_alloc(extHeap, g_nMaxBuffsNumLiveStream_Another*sizeof(DataPoolItem), 256);
	}while(g_pBuffsLiveStream_Another == 0);
	
	memset(g_pBuffsLiveStream_Another, 0, g_nMaxBuffsNumLiveStream_Another*sizeof(DataPoolItem));
	for (i = 0; i < g_nMaxBuffsNumLiveStream_Another; i++)
	{
		do
		{
			g_pBuffsLiveStream_Another[i].pBuf = MEM_alloc(extHeap, g_nMaxFrameSizeLiveStream_Another, 256);
		}while(g_pBuffsLiveStream_Another[i].pBuf == 0);	
	}

	sockThis = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( sockThis == INVALID_SOCKET )
	{
		Roseek_Reset();//如果创建侦听对象失败,重启相机
	}

	bzero( &addrAccept, sizeof(addrAccept) );
	nAddrLen = sizeof(addrAccept);
	bzero( &addrThis, sizeof(addrThis) );
	addrThis.sin_len	= sizeof( addrThis );
	addrThis.sin_family	= AF_INET;
	addrThis.sin_addr.s_addr = INADDR_ANY;
	addrThis.sin_port	= htons( 61001 );
	//sockFconListen绑定
	if ( bind( sockThis, (PSA) &addrThis, sizeof(addrThis) ) < 0 )
	{
		Roseek_Reset();//如果绑定失败,重启相机
	}
	//sockFconListen开始监听,同一时刻仅支持一个连接
	if ( listen( sockThis, 1) < 0 ){
		Roseek_Reset();//如果侦听失败,重启相机
	}
	//迭代循环
	while( 1 )
	{
		sockAccept = INVALID_SOCKET;
		do
		{
			sockAccept = accept( sockThis, (PSA)&addrAccept, &nAddrLen );
			if( sockAccept == INVALID_SOCKET)
			{
				break;
			}
			
			sock_setTimeout(sockAccept, SO_RCVTIMEO, 3000);
     	sock_setTimeout(sockAccept, SO_SNDTIMEO, 3000);

			g_bIsLiveStreamClientConnect_Another = TRUE;
			g_IsUsedByTCPSend_Another = TRUE;
			if (SafeSend(sockAccept, (Uint8*)&nVideoWidth, 4) != 4)
			{
				break;
			}
			if (SafeSend(sockAccept, (Uint8*)&nVideoHeight, 4) != 4)
			{
				break;
			}

			while( 1 )
			{
				if(isEncStop && g_nNumHasDataLSBuffs_Another <= 1)
				{
					Roseek_Start_Enc();
					isEncStop = 0;
					LOG_printf( &trace, "Roseek_Start_Enc!!!");
				}

				//等待信号灯同步
				isValidLink = 1;
				while (!SEM_pend( &sem_LiveStreamDataReady_Another, 5000))
				{
					int nRet;
					struct timeval tvTimeOut;
					fd_set fsVal;
					FD_ZERO(&fsVal);
					FD_SET(sockAccept, &fsVal);
					tvTimeOut.tv_sec = 0;
					tvTimeOut.tv_usec = 100;
					nRet = fdSelect(0, 0, &fsVal, 0, &tvTimeOut);
					if (0 == nRet || -1 == nRet)
					{
						isValidLink = 0;
						break;
					}
				}
				//SEM_pend( &sem_LiveStreamDataReady_Another, SYS_FOREVER );

				if (!isValidLink)
				{
					break;
				}
				
				//判断上传哪个缓冲区内容
				
				if (g_nNumHasDataLSBuffs_Another <= 0)
				{
					continue;
				}

				if (!isEncStop && (g_nNumHasDataLSBuffs_Another >= (g_nMaxBuffsNumLiveStream_Another-3)))
				{
					Roseek_Stop_Enc();
					isEncStop = 1;
					LOG_printf( &trace, "Roseek_Stop_Enc!!!");
				}

				if (g_nNumHasDataLSBuffs_Another >= (g_nMaxBuffsNumLiveStream_Another-1) && (g_pBuffsLiveStream_Another[g_nReadPosLSBuffs_Another].pBuf[8]&0x1F) != 7)
				{
					LOG_printf( &trace, "this frame not send!!!");
				}
				else
				{
					nDataLen = *(Uint32*)(g_pBuffsLiveStream_Another[g_nReadPosLSBuffs_Another].pBuf) + 4;
					if((nSendlen = SafeSend( sockAccept, g_pBuffsLiveStream_Another[g_nReadPosLSBuffs_Another].pBuf, nDataLen)) != nDataLen)
					{
							LOG_printf( &trace, "send error!!!");
							break;
					}
				}			
				
				g_nReadPosLSBuffs_Another = (++g_nReadPosLSBuffs_Another)%g_nMaxBuffsNumLiveStream_Another;
				g_nNumHasDataLSBuffs_Another--;
				
			}
		}while(0);
		
		if (sockAccept != INVALID_SOCKET)
		{
			fdClose(sockAccept);
			sockAccept = INVALID_SOCKET;
		}
		
		g_IsUsedByTCPSend_Another = FALSE;
		g_bIsLiveStreamClientConnect_Another = FALSE;
		SEM_reset( &sem_LiveStreamDataReady_Another, 0 );
		g_nNumHasDataLSBuffs_Another = 0;
		g_nReadPosLSBuffs_Another = 0;
		g_nWritePosLSBuffs_Another = 0;

		if(isEncStop)
		{
			Roseek_Start_Enc();
			isEncStop = 0;
			LOG_printf( &trace, "Roseek_Start_Enc!!!");
		}
	}//迭代循环
}
Esempio n. 26
0
File: task.c Progetto: Imara90/ESLab
Int Task_create (Task_TransferInfo ** infoPtr)
{
    Int status    = SYS_OK ;
    Task_TransferInfo * info = NULL ;

    /* Allocate Task_TransferInfo structure that will be initialized
     * and passed to other phases of the application */
    if (status == SYS_OK) 
	{
        *infoPtr = MEM_calloc (DSPLINK_SEGID,
                               sizeof (Task_TransferInfo),
                               0) ; /* No alignment restriction */
        if (*infoPtr == NULL) 
		{
            status = SYS_EALLOC ;
        }
        else 
		{
            info = *infoPtr ;
        }
    }

    /* Fill up the transfer info structure */
    if (status == SYS_OK) 
	{
        info->dataBuf       = NULL ; /* Set through notification callback. */
        info->bufferSize    = MPCSXFER_BufferSize ;
        SEM_new (&(info->notifySemObj), 0) ;
    }

    /*
     *  Register notification for the event callback to get control and data
     *  buffer pointers from the GPP-side.
     */
    if (status == SYS_OK) 
	{
        status = NOTIFY_register (ID_GPP,
                                  MPCSXFER_IPS_ID,
                                  MPCSXFER_IPS_EVENTNO,
                                  (FnNotifyCbck) Task_notify,
                                  info) ;
        if (status != SYS_OK) 
		{
            return status;
        }
    }

    /*
     *  Send notification to the GPP-side that the application has completed its
     *  setup and is ready for further execution.
     */
    if (status == SYS_OK) 
	{
        status = NOTIFY_notify (ID_GPP,
                                MPCSXFER_IPS_ID,
                                MPCSXFER_IPS_EVENTNO,
                                (Uint32) 0) ; /* No payload to be sent. */
        if (status != SYS_OK) 
		{
            return status;
        }
    }

    /*
     *  Wait for the event callback from the GPP-side to post the semaphore
     *  indicating receipt of the data buffer pointer and image width and height.
     */
    SEM_pend (&(info->notifySemObj), SYS_FOREVER) ;
    SEM_pend (&(info->notifySemObj), SYS_FOREVER) ;

    return status ;
}
Esempio n. 27
0
/* Perform Record (Rx) audio algorithm processing */
void RecAudioAlgTsk(void)
{
    Uint16 *ptrRxLeft;
    Int16 codec_input_sample_count;
    Uint16 i;
#ifdef ENABLE_STEREO_RECORD
    Uint16 *ptrRxRight;
#endif

    while (1)
    {
        SEM_pend(&SEM_DmaRxLeftComplete, SYS_FOREVER);
#ifdef ENABLE_STEREO_RECORD
        SEM_pend(&SEM_DmaRxRightComplete, SYS_FOREVER);
#endif

        /* Get pointer to ping/pong buffer */
        ptrRxLeft = &ping_pong_i2sRxLeftBuf[0];
        if (left_rx_buf_sel == 0x1) /* check ping or pong buffer */
        {
            /* this buffer has data to be processed */
            ptrRxLeft += I2S_RXBUFF_SZ;
        }
        left_rx_buf_sel ^= 0x1; /* update ping/pong */

#ifdef ENABLE_STEREO_RECORD
        /* Get pointer to right ping/pong buffer */
        ptrRxRight = &ping_pong_i2sRxRightBuf[0];
        if (right_rx_buf_sel == 0x1) /* check ping or pong buffer */
        {
            /* this buffer has data to be processed */
            ptrRxRight+= I2S_RXBUFF_SZ;
        }
        right_rx_buf_sel ^= 0x1; /* update ping/pong */
#endif

        /* Get data from ping/pong buffers */
        for (i = 0; i < RXBUFF_SZ_ADCSAMPS; i++)
        {
            // NOTE: since we need datapack to be disabled on I2S tx, we need it disabled on I2S rx therefore
            // we get 2 words per DMA transfer so the offset into DMA buffers has to be twice as big
            recInLeftBuf[i] = *ptrRxLeft;
            ptrRxLeft += 2;

            #if defined(SAMPLE_RATE_RX_16kHz) && defined(SAMPLE_RATE_I2S_48kHz)
            // DMA operates at 48KHz but sample rate is
            // set to 16kHz so store every third sample
            ptrRxLeft += 4;
            #endif

#ifdef ENABLE_STEREO_RECORD
            recInRightBuf[i] = *ptrRxRight;
            ptrRxRight += 2;

            #if defined(SAMPLE_RATE_RX_16kHz) && defined(SAMPLE_RATE_I2S_48kHz)
            // DMA operates at 48KHz but sample rate is
            // set to 16kHz so store every third sample
            ptrRxRight += 4;
            #endif
#endif
        }

        /*                                 */
        /* Insert Record audio algorithm here */
        /*                                    */
        //memcpy(recOutLeftBuf, recInLeftBuf, RXBUFF_SZ_ADCSAMPS); /* dummy */

#ifdef ENABLE_STEREO_RECORD
        //memcpy(recOutRightBuf, recInRightBuf, RXBUFF_SZ_ADCSAMPS); /* dummy */
#endif

        /* Store data in circular buffer */
        if (h_usb_int_tcount > 1) /* wait for IN tokens from Host */
        {
            /* Compute number of samples in circular buffer */
            codec_input_sample_count = codec_input_buffer_input_index - codec_input_buffer_output_index;
            if (codec_input_sample_count < 0)
            {
                codec_input_sample_count += CODEC_INPUT_BUFFER_SIZE;
            }

            /* Check for overflow */
            if (codec_input_sample_count > (CODEC_INPUT_BUFFER_SIZE-CODEC_INPUT_BUFFER_FRAME_SZ-2))
            {
                codec_input_buffer_overflow++;
                LOG_printf(&trace, "ERROR: codec input buffer OVERFLOW: %d\n", codec_input_sample_count);
            }

            for (i = 0; i < RXBUFF_SZ_ADCSAMPS; i++)
            {
                //codec_input_buffer[codec_input_buffer_input_index++] = recOutLeftBuf[i];
                codec_input_buffer[codec_input_buffer_input_index++] = 0; //recInLeftBuf[i];

#ifdef ENABLE_STEREO_RECORD
                //codec_input_buffer[codec_input_buffer_input_index++] = recOutRightBuf[i];
                codec_input_buffer[codec_input_buffer_input_index++] = recInRightBuf[i];
#endif

                if (codec_input_buffer_input_index >= CODEC_INPUT_BUFFER_SIZE)
                {
                    codec_input_buffer_input_index = 0;
                }
            }
        }
    }
}
Esempio n. 28
0
Int rmanTask(Arg scratchId, Arg resourceId,  Arg priority, Arg taskId, 
        Arg yieldFlag)
{

    Int i;
    IALG_Fxns * algFxns = &DUMALG_TI_IALG;
    IRES_Fxns * resFxns = &DUMALG_TI_IRES;
    IDUMALG_Handle dumHandle = NULL; 
    IDUMALG_Params params;

    GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_ENTER, "_rmanTask> Enter \n");

    params.size = sizeof(IDUMALG_Params);

    GT_4trace(ti_sdo_fc_rman_examples_hdvicp, GT_4CLASS, "_rmanTask> "
            "Task #%d: ScratchId %d, Priority %d Yield %d\n",taskId, scratchId,
            priority, yieldFlag);

    params.yieldFlag  = yieldFlag;
    params.taskId = taskId; 

    for (i = 0; i < NUM_RESOURCES; i++) {
        params.hdvicp[i] = *((IRES_HDVICP_RequestType *)resourceId + i);
        GT_1trace(ti_sdo_fc_rman_examples_hdvicp, GT_4CLASS, "_rmanTask> "
        "Requesting resource %d (2 => ANY)\n",(Int)params.hdvicp[i]);
    }
    /*
     * Create an instance of the algorithm using "algFxns" 
     */
    SEM_pend(mutex, SYS_FOREVER);
    dumHandle = (IDUMALG_Handle)DSKT2_createAlg((Int)scratchId, 
            (IALG_Fxns *)algFxns, NULL,(IALG_Params *)&params);
    if (dumHandle == NULL) {
        GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_7CLASS, "_rmanTask> "
                "Alg creation failed\n");
        return -1;
    } 
    SEM_post(mutex);
    /* Assign resources to the algorithm */
    if (IRES_OK != RMAN_assignResources((IALG_Handle)dumHandle,
                resFxns, scratchId)) {
        GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_7CLASS, "_rmanTask> "
                "Assign resource failed\n");
        return -1;
    }


    /*
     * Activate the Algorithm
     */
    DSKT2_activateAlg(scratchId, (IALG_Handle)dumHandle);

    /*
     * Activate All Resources
     */
    RMAN_activateAllResources((IALG_Handle)dumHandle, resFxns, scratchId);

    /*
     * Use IALG interfaces to do something 
     */
        dumHandle->fxns->useHDVICP(dumHandle, taskId);
    
    /*
     * Deactivate All Resources
     */
    RMAN_deactivateAllResources((IALG_Handle)dumHandle, resFxns, scratchId);

    /*
     * Deactivate algorithm 
     */
    DSKT2_deactivateAlg(scratchId, (IALG_Handle)dumHandle);

    /*
     * Free resources assigned to this algorihtm
     */
    if (IRES_OK != RMAN_freeResources((IALG_Handle)(dumHandle),
                resFxns, scratchId)) {
        GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_7CLASS, "_rmanTask> "
                "Free resource failed\n");
        return -1;
    }

    /*
     * Free instance of the algorithm created
     */
    SEM_pend(mutex, SYS_FOREVER);
    DSKT2_freeAlg(scratchId, (IALG_Handle)dumHandle);
    SEM_post(mutex);

    SEM_post(done);

    GT_0trace(ti_sdo_fc_rman_examples_hdvicp, GT_ENTER, "_rmanTask> Exit \n");

    return 0;
}
/**
 * \function 	SendFconDataPort
 * \brief    	使用TCP/IP协议实现FconMode的JPEG图像发送
 * \			默认作为服务器端,Port = 55000		
 * \
**/	
void SendFconDataPort()
{
	SOCKET	sockFconListen, sockFconSvr;
	int		size,i,cnt;
	Uint16	ui16Reply = 0;
	Bool	bClosed = FALSE;
	struct	sockaddr_in addr;
	Bool	bBreak=FALSE;
	static	Uint8	ui8JpgBufIndex=0;
	Uint8	ui8tmp;

	//为当前任务配置运行环境
	fdOpenSession( TaskSelf() );

	//创建侦听socket对象
	sockFconListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( sockFconListen == INVALID_SOCKET ){
		Roseek_Reset();//如果创建侦听对象失败,重启相机
	}
	bzero( &addr, sizeof(struct sockaddr_in) );
	addr.sin_family	= AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_len	= sizeof( addr );
	addr.sin_port	= htons( 55000 );
	//sockFconListen绑定
	if ( bind( sockFconListen, (PSA) &addr, sizeof(addr) ) < 0 ){
		Roseek_Reset();//如果绑定失败,重启相机
	}
	//sockFconListen开始监听,同一时刻仅支持一个连接
	if ( listen( sockFconListen, 1) < 0 ){
		Roseek_Reset();//如果侦听失败,重启相机
	}
	//迭代循环
	while( 1 ){
		size = sizeof( addr );
		sockFconSvr = accept( sockFconListen, (PSA)&addr, &size );
		if( sockFconSvr == INVALID_SOCKET){
			//如果接受连接出错则关闭接受到的连接对象,重新尝试
			fdClose(sockFconSvr);
			continue;
		}
		g_bIsFconClientConnect = TRUE; //网络线程准备完毕
		//向上位机发送MJPG图像
		while( !bClosed ){
			//等待信号灯同步
			SEM_pend( &sem_ConDataReady, SYS_FOREVER);
			//判断上传哪个缓冲区内容
			
			bBreak = FALSE;
			if(ui8JpgBufIndex==1){
				ui8tmp=0;
			}
			else{
				ui8tmp=ui8JpgBufIndex+1;
			}
			
			for( i=ui8tmp; i<ui8tmp+2; i++ ){
				if( i>1 ){
					if( g_JpgEncBufStruct.bJpgImgBuf_Lock[i-2] ){
						ui8JpgBufIndex = i-2;
						bBreak = TRUE;
						break;
					}
				}
				else{//i<=5
					if( g_JpgEncBufStruct.bJpgImgBuf_Lock[i] ){
						ui8JpgBufIndex = i;
						bBreak = TRUE;
						break;
					}
				}
			}
			
			if( !bBreak ){
				continue;
			}

			if( send( sockFconSvr, g_JpgEncBufStruct.pui8JpgImgBuf[ui8JpgBufIndex], *(Uint32*)g_JpgEncBufStruct.pui8JpgImgBuf[ui8JpgBufIndex] + 4, 0 ) < 0 ){
					break;
			}
			g_JpgEncBufStruct.bJpgImgBuf_Lock[ui8JpgBufIndex] = FALSE;

			//接受回应判断是否退出发送循环,若接受到0xffff终止发送循环,否则继续发送数据
			//启动后第一次执行后收到了0xffff(测试时)
			i = 0;
			while( i < 2 ){
				cnt = recv( sockFconSvr, (char*)&ui16Reply, 2-i, 0 );
				if( cnt <= 0 ){
					bClosed = TRUE;
					break;
				}
				i += cnt;
			}
			if( ui16Reply==0xffff ){
				bClosed = TRUE;
			}
		}
		//控制标志复位,关闭发送服务器连接,重回迭代循环等待新连接
		bClosed = FALSE;
		ui16Reply = 0x0000;
		fdClose(sockFconSvr);
		g_bIsFconClientConnect = FALSE;
		g_JpgEncBufStruct.bJpgImgBuf_Lock[0] = FALSE;
		g_JpgEncBufStruct.bJpgImgBuf_Lock[1] = FALSE;
		SEM_reset( &sem_ConDataReady, 0 );
	}//迭代循环
}