Example #1
0
/******************************************************************************
 *
 *   @name        Send_Task
 *
 *   @brief
 *
 *   @param       None
 *
 *   @return      None
 *****************************************************************************/
void Send_Task(uint_32 param)
{
    while(TRUE)
    {
        if(g_bridge.usb_enum_complete == FALSE)
        {
            continue;
        }

        if(_lwevent_wait_for(&lwevent,BRIDGE_SEND_EVENT,FALSE,NULL) !=
                MQX_OK)
        {   /* since third argument is false, the execution continues when any
               of the evnt is generated */
#if _DEBUG
            printf("Event Wait failed : Send_Task\n");
#endif
            _task_block();
        }

        /* clear the event and proceed*/
        if(_lwevent_clear(&lwevent,BRIDGE_SEND_EVENT) != MQX_OK)
        {
#if _DEBUG
            printf("\nSend Event Clear failed");
#endif
            _task_block();
        }

        if(g_connection_present == TRUE)
        {
            Bridge_Interface_Write(g_tx_buff_ptr, g_bridge_tx_size);
        }
    }
}
Example #2
0
/******************************************************************************
 *
 *   @name        Recv_Task
 *
 *   @brief
 *
 *   @param       None
 *
 *   @return      None
 *****************************************************************************/
void Recv_Task(uint_32 param)
{
    while(TRUE)
    {
        if(g_bridge.usb_enum_complete == FALSE)
        {
            continue;
        }

        if(_lwevent_wait_for(&lwevent,BRIDGE_RECV_EVENT,FALSE,NULL) !=
                MQX_OK)
        {   /* since third argument is false, the execution continues when any
               of the evnt is generated */
#if _DEBUG
            printf("Event Wait failed : Recv_Task\n");
#endif
            _task_block();
        }

        /* clear the event and proceed*/
        if(_lwevent_clear(&lwevent,BRIDGE_RECV_EVENT) != MQX_OK)
        {
#if _DEBUG
            printf("\nRecv Event Clear failed");
#endif
            _task_block();
        }

        if(g_connection_present == TRUE)
        {
            /* Queue recv on Bridge Interface of max buffer size*/
            Bridge_Interface_Read(g_bridge_rx_buff_ptr, PHDC_BULK_IN_EP_SIZE);
        }
    }
}
Example #3
0
void service_task 
   (
      uint_32 initial_data
   )
{
   _task_id second_task_id;
   _int_install_unexpected_isr();
   /* create lwevent group */
   if (_usr_lwevent_create(&lwevent,0) != MQX_OK) {
      printf("\nMake event failed");
      _task_block();
   }

   /* Create the ISR task */
   second_task_id = _usr_task_create(0, ISR_TASK, 0);
   if (second_task_id == MQX_NULL_TASK_ID) {
      printf("Could not create simulated_ISR_task \n");
      _task_block();
   }

   while (TRUE) {
      if (_lwevent_wait_ticks(&lwevent,1,TRUE,0) != MQX_OK) {
         printf("\nEvent Wait failed");
         _task_block();
      }

      if (_lwevent_clear(&lwevent,0x01) != MQX_OK) {
         printf("\nEvent Clear failed");
         _task_block();
      }
      printf(" Tick \n");
   }
}  
Example #4
0
boolean HVAC_WaitParameters(int_32 timeout) 
{
    boolean catched;
    #if DEMOCFG_ENABLE_SWITCH_TASK
        // switch-sensing task is running, we can simply wait for the event or timeout
        _lwevent_wait_ticks(&HVAC_Params.Event, HVAC_PARAMS_CHANGED, TRUE, timeout);
        
    #else
        // poll the keys frequenly until the event or timeout expires
        uint_32 poll_wait = BSP_ALARM_FREQUENCY/20; // 50ms
        int_32  elapsed;
        MQX_TICK_STRUCT tickstart, ticknow;
        
        _time_get_elapsed_ticks(&tickstart);

        do
        {
            Switch_Poll();
            _lwevent_wait_ticks(&HVAC_Params.Event, HVAC_PARAMS_CHANGED, TRUE, poll_wait);

            _time_get_elapsed_ticks(&ticknow);
            elapsed = _time_diff_ticks_int32 (&ticknow, &tickstart, NULL);
            
        } while (elapsed < timeout);
        
    #endif          
    catched = (HVAC_Params.Event.VALUE & HVAC_PARAMS_CHANGED) != 0;
    _lwevent_clear(&HVAC_Params.Event, HVAC_PARAMS_CHANGED);
    return catched;
    
}
Example #5
0
/******************************************************************************
 *   @name        PIT0_ISR
 *
 *   @brief       This routine services RTC Interrupt
 *
 *   @param       None
 *
 *   @return      None
 *
 ******************************************************************************
 * Services Programmable Interrupt Timer 0. If a Timer Object expires, then  
 * removes the object from Timer Queue and Calls the callback function 
 * (if registered)
 *****************************************************************************/
static void AUDIO_TIMER_ISR(void)
{
#if (defined BSP_TWRMCF51JE)||(defined BSP_TWRMCF51MM)||(defined BSP_MCF51JMEVB)
   ClearCmtInterrupt();
#elif (defined BSP_TWRMCF51JF)
   ClearFTMInterrupt(AUDIO_TIMER);
#else
   _pit_clear_int(AUDIO_TIMER);
#endif
   if (USB_APP_DATA_RECEIVED_EVENT_MASK == app_event.VALUE)
   {
      *duty = audio_data_buff0[audio_sample];  
      audio_sample += AUDIO_DATA_SIZE/8;
      if (AUDIO_DATA_SIZE < (audio_sample + 1))
      {
         audio_sample = 0;
         if (MQX_OK != _lwevent_clear(&app_event, USB_APP_DATA_RECEIVED_EVENT_MASK)) {
            printf("\n_lwevent_clear app_event failed.\n");
            _task_block();
         }
      }
   }
#if (defined BSP_TWR_K40X256) || (defined BSP_TWR_K60N512) || (defined BSP_TWR_K53N512) || (defined BSP_KWIKSTIK_K40X256)
   PIT_TCTRL_REG(PIT_BASE_PTR,1)|= PIT_TCTRL_TIE_MASK;
#endif
}
Example #6
0
uint32_t OS_Event_clear(os_event_handle handle, uint32_t bitmask)
{
    LWEVENT_STRUCT *event = (LWEVENT_STRUCT*)handle;
    if (_lwevent_clear(event, bitmask) != MQX_OK)
    {
        return (uint32_t)OS_EVENT_ERROR;
    }
    return (uint32_t)OS_EVENT_OK;
}
Example #7
0
int unit_test_pm2p5()
{
    int ret = 0;
    int i = READ_ADC_TIMES;
    int pm_adc[READ_ADC_TIMES] = {0};
    int  tmp;
    int32_t microsec;
    int overflow;
    MQX_TICK_STRUCT start_tick,cur_tick,diff_tick;

	/* for test led clk
	do {
	  _time_delay(500);
	  printf(".\n");
	}while(1);
	*/

#if (ADC_INPUT_CH == 3)
    	adcc_init(0);
        mux_74hc595_clear_bit(BSP_74HC595_0,   BSP_74HC595_SPI_S0);
        mux_74hc595_set_bit(BSP_74HC595_0,     BSP_74HC595_SPI_S1);

    //mux_74hc595_clear_bit(BSP_74HC595_0,   BSP_74HC595_SPI_S1);
    //mux_74hc595_set_bit(BSP_74HC595_0,     BSP_74HC595_SPI_S0);
	do {
		_time_get_elapsed_ticks_fast(&start_tick);
		tmp = adc_measure_pm2p5();
		_time_get_elapsed_ticks_fast(&cur_tick);
		overflow = 0;
		microsec = _time_diff_microseconds(&cur_tick,&start_tick,&overflow);
		printf("read batt = %d, microsecs %d ,overflow %d\n",tmp,microsec,overflow);
	}
	while (1);
#else
   	pm2p5_sample_start();

#ifdef ALWAYS_SAMPLING
       do{
	if(sample_value != 0)
	   printf("read pm2.5 = %d\n",sample_value);
	}
	while(1);
#else
	do {
          _lwevent_wait_ticks(&sample_event, 1, FALSE, 0);
          _lwevent_clear(&sample_event, 1);
          // sampling
	  tmp = adc_measure_pm2p5();
	  pm_adc[READ_ADC_TIMES - i] = tmp;
        } while (i--);
    
        printf("current PM2.5 density = %f mg/m3\n",lookup_pm25table(pm_adc,READ_ADC_TIMES));
#endif
    sample_timer_deinit();
#endif
    return 0;
}
Example #8
0
void int_service_routine_btn_pause(void *pin)                  //SW1
{
    lwgpio_int_clear_flag((LWGPIO_STRUCT_PTR) pin);

    pause_trigger = !pause_trigger;
    if(TRUE == pause_trigger)            //pause a song
    {
        if((mp_sMicroSDplay == cur_musicPlayMS)||(mp_sMSDplay == cur_musicPlayMS))
        {
            _lwevent_clear(&player_event, PLAYER_EVENT_MSK_SONG_RESUME);
        }
        else if(mp_sAccessory == cur_musicPlayMS)
        {
            //AccessoryPausePlay();
            AccessroyHidEvent |= ACCPAUSEPLAY;
        }
        else if(mp_sBT == cur_musicPlayMS)
        {
            BtAVRCPEvent |= ACCPAUSEPLAY;
        }
        printf("Paused\n");
    }
    else                                //resume a song
    {
        if((mp_sMicroSDplay == cur_musicPlayMS)||(mp_sMSDplay == cur_musicPlayMS))
        {
            _lwevent_set(&player_event, PLAYER_EVENT_MSK_SONG_RESUME);
        }
        else if(mp_sAccessory == cur_musicPlayMS)
        {
            //AccessoryResumePlay();
            AccessroyHidEvent |= ACCRESUMEPLAY;
        }
        else if(mp_sBT == cur_musicPlayMS)
        {
            BtAVRCPEvent |= ACCRESUMEPLAY;
        }
        printf("Resume\n");
    }

    //decoding = FALSE;
    //printf("SW1 pressed. %d \n", trigger);
}
Example #9
0
/**************************************************************************
  Global variables
 **************************************************************************/
int unit_test_usb_host(void) {

    static _usb_host_handle host_handle;
    USB_STATUS  error;

    USB_lock();

    _int_install_unexpected_isr();



    if (MQX_OK != _usb_host_driver_install(USBCFG_DEFAULT_HOST_CONTROLLER)) {
        printf("\n Driver installation failed");
        _task_block();
    }

    error = _usb_host_init(USBCFG_DEFAULT_HOST_CONTROLLER, &host_handle);
    if (error == USB_OK) {
        error = _usb_host_driver_info_register(host_handle, (pointer)DriverInfoTable);
        if (error == USB_OK) {
            error = _usb_host_register_service(host_handle, USB_SERVICE_HOST_RESUME, NULL);
        }
    }

    USB_unlock();

    if (error != USB_OK) {
        _task_block();
    }

    if (MQX_OK != _lwevent_create(&usb_event, LWEVENT_AUTO_CLEAR)) {
        return -1;
    }

    /* prepare events to be auto or manual */
    _lwevent_set_auto_clear(&usb_event, 0xFFFFFFFF);
    /* pre-set events */
    _lwevent_clear(&usb_event, 0xFFFFFFFF);

    _lwevent_wait_ticks(&usb_event, 0x1, FALSE, 0);

    return 0;
}
Example #10
0
/*!
 * \brief This function receives a message from the specified endpoint if one is available.
 *        The data will be copied from the receive buffer into the user supplied buffer.
 *
 * This is the "receive with copy" version of the MCC receive function. This version is simple
 * to use but it requires copying data from shared memory into the user space buffer.
 * The user has no obligation or burden to manage the shared memory buffers.
 *
 * \param[in] endpoint Pointer to the receiving endpoint to receive from.
 * \param[in] buffer Pointer to the user-app. buffer where data will be copied into.
 * \param[in] buffer_size The maximum number of bytes to copy.
 * \param[out] recv_size Pointer to an MCC_MEM_SIZE that will contain the number of bytes actually copied into the buffer.
 * \param[in] timeout_us Timeout, in microseconds, to wait for a free buffer. A value of 0 means don't wait (non-blocking call). A value of 0xffffffff means wait forever (blocking call).
 *
 * \return MCC_SUCCESS
 * \return MCC_ERR_ENDPOINT (the endpoint does not exist)
 * \return MCC_ERR_SEMAPHORE (semaphore handling error)
 * \return MCC_ERR_TIMEOUT (timeout exceeded before a new message came)
 *
 * \see mcc_send
 * \see mcc_recv_nocopy
 * \see MCC_ENDPOINT
 */
int mcc_recv_copy(MCC_ENDPOINT *endpoint, void *buffer, MCC_MEM_SIZE buffer_size, MCC_MEM_SIZE *recv_size, unsigned int timeout_us)
{
    MCC_RECEIVE_LIST *list;
    MCC_RECEIVE_BUFFER * buf;
    MCC_SIGNAL affiliated_signal;
    MCC_ENDPOINT tmp_destination = {(MCC_CORE)0, (MCC_NODE)0, (MCC_PORT)0};
    int return_value, i = 0;
#if (MCC_OS_USED == MCC_MQX)
    unsigned int time_us_tmp;
    unsigned int lwevent_index = endpoint->port / MCC_MQX_LWEVENT_GROUP_SIZE;
    unsigned int lwevent_group_index = endpoint->port % MCC_MQX_LWEVENT_GROUP_SIZE;
    MQX_TICK_STRUCT tick_time;
#endif

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Get list of buffers kept by the particular endpoint */
    list = mcc_get_endpoint_list(*endpoint);

    /* Semaphore-protected section end */
    return_value = mcc_release_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* The endpoint is not valid */
    if(list == null) {
        return MCC_ERR_ENDPOINT;
    }

    if(list->head == (MCC_RECEIVE_BUFFER*)0) {
        /* Non-blocking call */
        if(timeout_us == 0) {
            return MCC_ERR_TIMEOUT;
        }
        /* Blocking call */
        else {
#if (MCC_OS_USED == MCC_MQX)
            if(timeout_us == 0xFFFFFFFF) {
                _lwevent_wait_ticks(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index, TRUE, 0);
            }
            /* timeout_us > 0 */
            else {
                _time_get_ticks(&tick_time);
                _time_add_usec_to_ticks(&tick_time, timeout_us);
                _lwevent_wait_until(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index, TRUE, &tick_time);
            }
#endif
            MCC_DCACHE_INVALIDATE_MLINES((void*)list, sizeof(MCC_RECEIVE_LIST*));
        }
    }

    /* Clear event bit specified for the particular endpoint in the lwevent_buffer_queued lwevent group */
    _lwevent_clear(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index);

    if(list->head == (MCC_RECEIVE_BUFFER*)0) {
        /* Buffer not dequeued before the timeout */
        return MCC_ERR_TIMEOUT;
    }

    /* Copy the message from the MCC receive buffer into the user-app. buffer */
    MCC_DCACHE_INVALIDATE_MLINES((void*)&list->head->data_len, sizeof(MCC_MEM_SIZE));
    if (list->head->data_len > buffer_size) {
        list->head->data_len = buffer_size;
    }
    *recv_size = (MCC_MEM_SIZE)(list->head->data_len);
    MCC_DCACHE_INVALIDATE_MLINES((void*)&list->head->data, list->head->data_len);
    mcc_memcpy((void*)list->head->data, buffer, list->head->data_len);

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Dequeue the buffer from the endpoint list */
    buf = mcc_dequeue_buffer(list);

    /* Enqueue the buffer into the free list */
    MCC_DCACHE_INVALIDATE_MLINES((void*)&bookeeping_data->free_list, sizeof(MCC_RECEIVE_LIST*));
    mcc_queue_buffer(&bookeeping_data->free_list, buf);

    /* Notify all cores (except of itself) via CPU-to-CPU interrupt that a buffer has been freed */
    affiliated_signal.type = BUFFER_FREED;
    affiliated_signal.destination = tmp_destination;
    for (i=0; i<MCC_NUM_CORES; i++) {
        if(i != MCC_CORE_NUMBER) {
            mcc_queue_signal(i, affiliated_signal);
        }
    }
    mcc_generate_cpu_to_cpu_interrupt();

    /* Semaphore-protected section end */
    return_value = mcc_release_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    return return_value;
}
Example #11
0
/*!
 * \brief This function sends a message to an endpoint.
 *
 * The message is copied into the MCC buffer and the destination core is signaled.
 *
 * \param[in] endpoint Pointer to the receiving endpoint to send to.
 * \param[in] msg Pointer to the message to be sent.
 * \param[in] msg_size Size of the message to be sent in bytes.
 * \param[in] timeout_us Timeout, in microseconds, to wait for a free buffer. A value of 0 means don't wait (non-blocking call). A value of 0xffffffff means wait forever (blocking call).
 *
 * \return MCC_SUCCESS
 * \return MCC_ERR_ENDPOINT (the endpoint does not exist)
 * \return MCC_ERR_SEMAPHORE (semaphore handling error)
 * \return MCC_ERR_INVAL (the msg_size exceeds the size of a data buffer)
 * \return MCC_ERR_TIMEOUT (timeout exceeded before a buffer became available)
 * \return MCC_ERR_NOMEM (no free buffer available and timeout_us set to 0)
 * \return MCC_ERR_SQ_FULL (signal queue is full)
 *
 * \see mcc_recv_copy
 * \see mcc_recv_nocopy
 * \see MCC_ENDPOINT
 */
int mcc_send(MCC_ENDPOINT *endpoint, void *msg, MCC_MEM_SIZE msg_size, unsigned int timeout_us)
{
    int return_value, end_time_set_flag = 0;
    MCC_RECEIVE_LIST *list;
    MCC_RECEIVE_BUFFER * buf;
    MCC_SIGNAL affiliated_signal;
#if (MCC_OS_USED == MCC_MQX)
    unsigned int time_us_tmp;
    MQX_TICK_STRUCT tick_time;
#endif

    /* Check if the size of the message to be sent does not exceed the size of the mcc buffer */
    if(msg_size > sizeof(bookeeping_data->r_buffers[0].data)) {
        return MCC_ERR_INVAL;
    }

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Dequeue the buffer from the free list */
    MCC_DCACHE_INVALIDATE_MLINES((void*)&bookeeping_data->free_list, sizeof(MCC_RECEIVE_LIST*));
    buf = mcc_dequeue_buffer(&bookeeping_data->free_list);

    while(buf == null) {
        mcc_release_semaphore();

        /* Non-blocking call */
        if(timeout_us == 0) {
            return MCC_ERR_NOMEM;
        }
        /* Blocking calls: CPU-to-CPU ISR sets the event and thus resumes tasks waiting for a free MCC buffer.
         * As the interrupt request is send to all cores when a buffer is freed it could happen that several
         * tasks from different cores/nodes are waiting for a free buffer and all of them are notified that the buffer
         * has been freed. This function has to check (after the wake up) that a buffer is really available and has not been already
         * grabbed by another "competitor task" that has been faster. If so, it has to wait again for the next notification. */
        /* wait forever */
        else if(timeout_us == 0xFFFFFFFF) {
#if (MCC_OS_USED == MCC_MQX)
            _lwevent_wait_ticks(&lwevent_buffer_freed, 1, TRUE, 0);
            _lwevent_clear(&lwevent_buffer_freed, 1);
#endif
        }
        /* timeout_us > 0 */
        else {
#if (MCC_OS_USED == MCC_MQX)
            if(!end_time_set_flag) {
                _time_get_ticks(&tick_time);
                _time_add_usec_to_ticks(&tick_time, timeout_us);
                end_time_set_flag = 1;
            }
            return_value = _lwevent_wait_until(&lwevent_buffer_freed, 1, TRUE, &tick_time);
            if(return_value == LWEVENT_WAIT_TIMEOUT) {
                /* Buffer not dequeued before the timeout */
                return MCC_ERR_TIMEOUT;
            }
            _lwevent_clear(&lwevent_buffer_freed, 1);
#endif
        }
        MCC_DCACHE_INVALIDATE_MLINES((void*)&bookeeping_data->free_list, sizeof(MCC_RECEIVE_LIST*));
        mcc_get_semaphore();
        buf = mcc_dequeue_buffer(&bookeeping_data->free_list);
    }

    /* Semaphore-protected section end */
    mcc_release_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Copy the message into the MCC receive buffer */
    mcc_memcpy(msg, (void*)buf->data, (unsigned int)msg_size);
    MCC_DCACHE_FLUSH_MLINES((void*)buf->data, msg_size);
    buf->data_len = msg_size;
    MCC_DCACHE_FLUSH_MLINES((void*)&buf->data_len, sizeof(MCC_MEM_SIZE));

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Get list of buffers kept by the particular endpoint */
    list = mcc_get_endpoint_list(*endpoint);

    if(list == null) {
        /* The endpoint does not exists (has not been registered so far),
         free the buffer and return immediately - error */
        /* Enqueue the buffer back into the free list */
        MCC_DCACHE_INVALIDATE_MLINES((void*)&bookeeping_data->free_list, sizeof(MCC_RECEIVE_LIST*));
        mcc_queue_buffer(&bookeeping_data->free_list, buf);
      
        mcc_release_semaphore();
        return MCC_ERR_ENDPOINT;
    }

    /* Write the signal type into the signal queue of the particular core */
    affiliated_signal.type = BUFFER_QUEUED;
    affiliated_signal.destination = *endpoint;
    return_value = mcc_queue_signal(endpoint->core, affiliated_signal);
    if(return_value != MCC_SUCCESS) {
        /* Signal queue is full, free the buffer and return immediately - error */
        MCC_DCACHE_INVALIDATE_MLINES((void*)&bookeeping_data->free_list, sizeof(MCC_RECEIVE_LIST*));
        mcc_queue_buffer(&bookeeping_data->free_list, buf);

        mcc_release_semaphore();
        return return_value;
    }

    /* Enqueue the buffer into the endpoint buffer list */
    mcc_queue_buffer(list, buf);

    /* Semaphore-protected section end */
    mcc_release_semaphore();

    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Signal the other core by generating the CPU-to-CPU interrupt */
    return_value = mcc_generate_cpu_to_cpu_interrupt();

    return return_value;
}
Example #12
0
void USB_task(uint_32 param)
{ 
   _usb_host_handle     host_handle;
   USB_STATUS           error;
   pointer              usb_fs_handle = NULL;

#if DEMO_USE_POOLS && defined(DEMO_MFS_POOL_ADDR) && defined(DEMO_MFS_POOL_SIZE)
   _MFS_pool_id = _mem_create_pool((pointer)DEMO_MFS_POOL_ADDR, DEMO_MFS_POOL_SIZE);
#endif

   _lwsem_create(&USB_Stick,0);
   _lwevent_create(&USB_Event,0);

   USB_lock();
   _int_install_unexpected_isr();
   if (MQX_OK != _usb_host_driver_install(USBCFG_DEFAULT_HOST_CONTROLLER)) {
      printf("\n Driver installation failed");
      _task_block();
   }

   error = _usb_host_init(USBCFG_DEFAULT_HOST_CONTROLLER, &host_handle);
   if (error == USB_OK) {
      error = _usb_host_driver_info_register(host_handle, (pointer)ClassDriverInfoTable);
      if (error == USB_OK) {
         error = _usb_host_register_service(host_handle, USB_SERVICE_HOST_RESUME,NULL);
      }
   }

   USB_unlock();

   if (error == USB_OK) {
      
      for ( ; ; ) {
         // Wait for insertion or removal event
         _lwevent_wait_ticks(&USB_Event,USB_EVENT,FALSE,0);

         if ( device.STATE== USB_DEVICE_ATTACHED) {

            if (device.SUPPORTED)  {
               error = _usb_hostdev_select_interface(device.DEV_HANDLE,
               device.INTF_HANDLE, (pointer)&device.CLASS_INTF);
               if(error == USB_OK) {
                  device.STATE = USB_DEVICE_INTERFACED;

                  USB_handle = (pointer)&device.CLASS_INTF;

                  // Install the file system
                  usb_fs_handle = usb_filesystem_install( USB_handle, "USB:", "PM_C1:", "c:" );
                  if (usb_fs_handle) {
                     // signal the application
                     _lwsem_post(&USB_Stick);
                  }
               }
            } else {
                device.STATE = USB_DEVICE_INTERFACED;
            }
         } else if ( device.STATE==USB_DEVICE_DETACHED) {
            _lwsem_wait(&USB_Stick);
            // remove the file system
           usb_filesystem_uninstall(usb_fs_handle);
         }

         // clear the event
         _lwevent_clear(&USB_Event,USB_EVENT);
      }
   }
}
Example #13
0
void main_task
(
    uint32_t initial_data
)
{ /* Body */
    uint32_t        rtc_time;
    uint32_t        rtc_time_default;
    TIME_STRUCT     mqx_time;
    DATE_STRUCT     date_time;

    if (_lwevent_create(&lwevent,0) != MQX_OK)
    {
        printf("\nMake event failed");
        _task_block();
    }
    printf ("\f RTC Demo :\n\n");
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    /* initialize time */
    date_time.YEAR     = RTC_TIME_INIT_TM_YEAR;
    date_time.MONTH    = RTC_TIME_INIT_TM_MON;
    date_time.DAY      = RTC_TIME_INIT_TM_MDAY;
    date_time.HOUR     = RTC_TIME_INIT_TM_HOUR;
    date_time.MINUTE   = RTC_TIME_INIT_TM_MIN;
    date_time.SECOND   = RTC_TIME_INIT_TM_SEC;
    date_time.MILLISEC = 0;

    /* Convert date time to time struct */
    if ( _time_from_date(&date_time, &mqx_time) == FALSE)
    {
        printf("\n Cannot convert date_time ");
        _task_block();
    }

    /* Convert rtc time to TIME_STRUCT */
    rtc_time = mqx_time.SECONDS;

    printf(" Set RTC time is: %s %s %3d %.2d:%.2d:%.2d %d\n",
            _days_abbrev[date_time.WDAY],
            _months_abbrev[date_time.MONTH - 1],
            date_time.DAY,
            date_time.HOUR,
            date_time.MINUTE,
            date_time.SECOND,
            date_time.YEAR);
    /* Set MQX time*/
    _time_set(&mqx_time);
    /* Set RTC time*/
    _rtc_set_time(rtc_time);
    printf("\n MQX time: %d SECONDS, %d MILISECOND ", mqx_time.SECONDS, mqx_time.MILLISECONDS);

    /*
     * set-up alarm
     */

    /* install callback */
    _rtc_callback_reg((INT_ISR_FPTR)rtc_callback, (void*)NULL);
    /* Set alarm to maximum time to avoid unexpected interrupt in next running */
    _rtc_set_alarm(MAXIMUM_SECONDS_IN_TIME,(uint32_t)0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    
    /* Get current time */
    _rtc_get_time(&rtc_time);

    /* setup alarm in next 10 seconds & period 4 seconds*/
    rtc_time += (uint32_t)ALARM_NEXT_TIME; /* Alarm occurs in next 10 seconds */
    printf("\n Setup to occur alarm in next %d seconds & with period: %d seconds",ALARM_NEXT_TIME, ALARM_PERIOD);
    _rtc_set_alarm(rtc_time,(uint32_t)ALARM_PERIOD);
    printf("\n Wait %d seconds ....",ALARM_NEXT_TIME);
    /* Wait to clear LWE_ALARM event */
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    printf ("\nALARM! ALARM! ALARM!\n");
    /* Print current time */
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf("\n Wait next alarm in %d seconds....",ALARM_PERIOD);
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);
    printf ("\nALARM! ALARM! ALARM!\n");
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf ("\nClearing RTC:\n");
    _rtc_set_time(0);
    _rtc_get_time(&rtc_time_default);
    print_rtc_time(rtc_time_default);
    /* Wait 2 seconds after resynchronize rtc time with mqx time*/
    do{
       _rtc_get_time(&rtc_time);
    } while ((rtc_time - rtc_time_default) < 2);

    /* Get current time & display on terminal */
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);

    printf ("Synchronize RTC to MQX time again:\n");
    _time_get(&mqx_time);
    rtc_time = mqx_time.SECONDS;
    _rtc_set_time(rtc_time);
    
    _rtc_get_time(&rtc_time);
    print_rtc_time(rtc_time);
    
#if PSP_HAS_IRTC == 1
    irtc_test();
#endif /* PSP_HAS_IRTC == 1 */

    printf ("Finish, press/hold reset to repeat.\n");
    _task_block() ;
} /* Endbody */
Example #14
0
/*!
 * \brief 	MQX API handler for usermode - part of wrapper around standard MQX API
 *  which require privilege mode.
 *
 * \param[in] api_no API number - number of wrapped function
 * \param[in] params generic parameter - direct use with called MQX API fn
 *
 * \return uint32_t return of called function
 */
uint32_t _mqx_api_call_handler
    (
        // [IN] API number - number of wrapped function
        MQX_API_NUMBER_ENUM api_no,
        // [IN] generic parameter - direct use with called MQX API fn
        MQX_API_CALL_PARAMS_PTR params
    )
{
    int32_t res = -1;
    uint32_t param0 = params->param0;
    uint32_t param1 = params->param1;
    uint32_t param2 = params->param2;
    uint32_t param3 = params->param3;
    uint32_t param4 = params->param4;

    switch (api_no) {

    // _lwsem
    case MQX_API_LWSEM_POLL:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)))
            res = (uint32_t)_lwsem_poll((LWSEM_STRUCT_PTR)param0);
        break;
    case MQX_API_LWSEM_POST:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)))
            res = _lwsem_post((LWSEM_STRUCT_PTR)param0);
        break;
    case MQX_API_LWSEM_WAIT:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)))
            res = _lwsem_wait((LWSEM_STRUCT_PTR)param0);
        break;
    case MQX_API_LWSEM_CREATE:
        res = _lwsem_create_internal((LWSEM_STRUCT_PTR)param0, (_mqx_int)param1, (bool)param2, TRUE);
        break;
#if MQX_HAS_TICK
    case MQX_API_LWSEM_WAIT_FOR:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)) && (!param1 || _psp_mem_check_access(param1, sizeof(MQX_TICK_STRUCT), MPU_UM_RW)))
            res = _lwsem_wait_for((LWSEM_STRUCT_PTR)param0, (MQX_TICK_STRUCT_PTR)param1);
        break;
    case MQX_API_LWSEM_WAIT_TICKS:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)))
            res = _lwsem_wait_ticks((LWSEM_STRUCT_PTR)param0, (_mqx_uint)param1);
        break;
    case MQX_API_LWSEM_WAIT_UNTIL:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0)) && (!param1 || _psp_mem_check_access(param1, sizeof(MQX_TICK_STRUCT), MPU_UM_RW)))
            res = _lwsem_wait_until((LWSEM_STRUCT_PTR)param0, (MQX_TICK_STRUCT_PTR)param1);
        break;
    case MQX_API_LWSEM_DESTROY:
        if (MQX_OK == (res = _lwsem_usr_check((LWSEM_STRUCT_PTR)param0))) {
            res = _lwsem_destroy_internal((LWSEM_STRUCT_PTR)param0, TRUE);
        }
        break;

#endif // MQX_HAS_TICK

    // _lwevent
#if MQX_USE_LWEVENTS
    case MQX_API_LWEVENT_CLEAR:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0)))
            res = _lwevent_clear((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1);
        break;
    case MQX_API_LWEVENT_SET:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0)))
            res = _lwevent_set((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1);
        break;
    case MQX_API_LWEVENT_SET_AUTO_CLEAR:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0)))
            res = _lwevent_set_auto_clear((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1);
        break;
    case MQX_API_LWEVENT_WAIT_FOR:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0)) && \
            (!param3 || _psp_mem_check_access(param3, sizeof(MQX_TICK_STRUCT), MPU_UM_RW))) {
            res = _lwevent_wait_for((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1, (bool)param2, (MQX_TICK_STRUCT_PTR)param3);
        }
        break;
    case MQX_API_LWEVENT_WAIT_FOR_TICKS:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0))) {
            res = _lwevent_wait_ticks((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1, (bool)param2, (_mqx_uint)param3);
        }
        break;
    case MQX_API_LWEVENT_WAIT_UNTIL:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0)) && \
            (!param3 || _psp_mem_check_access(param3, sizeof(MQX_TICK_STRUCT), MPU_UM_RW))) {
            res = _lwevent_wait_until((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1, (bool)param2, (MQX_TICK_STRUCT_PTR)param3);
        }
        break;
    case MQX_API_LWEVENT_GET_SIGNALLED:
        res = _lwevent_get_signalled();
        break;

    case MQX_API_LWEVENT_CREATE:
        res = _lwevent_create_internal((LWEVENT_STRUCT_PTR)param0, (_mqx_uint)param1, TRUE);
        break;

    case MQX_API_LWEVENT_DESTROY:
        if (MQX_OK == (res = _lwevent_usr_check((LWEVENT_STRUCT_PTR)param0))) {
            res = _lwevent_destroy_internal((LWEVENT_STRUCT_PTR)param0, TRUE);
        }
        break;
#endif

#if MQX_USE_LWMSGQ
    case MQX_API_LWMSGQ_INIT:
        res = _lwmsgq_init_internal((void *)param0, (_mqx_uint)param1, (_mqx_uint)param2, TRUE);
        break;
    case MQX_API_LWMSGQ_RECEIVE:
        if (MQX_OK == (res = _lwmsgq_usr_check((LWMSGQ_STRUCT_PTR)param0)) && \
            _psp_mem_check_access(param1, ((LWMSGQ_STRUCT_PTR)param0)->MSG_SIZE, MPU_UM_RW) && \
            (!param4 || _psp_mem_check_access(param4, sizeof(MQX_TICK_STRUCT), MPU_UM_RW)))
            res = _lwmsgq_receive((void *)param0, (_mqx_max_type_ptr)param1, (_mqx_uint)param2, (_mqx_uint)param3, (MQX_TICK_STRUCT_PTR)param4);

        break;
    case MQX_API_LWMSGQ_SEND:
        if (MQX_OK == (res = _lwmsgq_usr_check((LWMSGQ_STRUCT_PTR)param0)) && \
            _psp_mem_check_access(param1, ((LWMSGQ_STRUCT_PTR)param0)->MSG_SIZE, MPU_UM_RW))
            res = _lwmsgq_send((void *)param0, (_mqx_max_type_ptr)param1, (_mqx_uint)param2);
        break;
#endif // MQX_USE_LWMSGQ

    case MQX_API_TASK_CREATE:
        res = _task_create_internal((_processor_number)param0, (_mqx_uint)param1, (uint32_t)param2, TRUE);
        break;
    case MQX_API_TASK_DESTROY:
        res = _task_destroy_internal((_task_id)param0, TRUE);
        break;
    case MQX_API_TASK_ABORT:
        res = _task_abort_internal((_task_id)param0, TRUE);
        break;
    case MQX_API_TASK_READY:
        _task_ready((void *)param0);
        res = MQX_OK;       // irelevant, function is without return value
        break;
    case MQX_API_TASK_SET_ERROR:
        res = _task_set_error((_mqx_uint)param0);
        break;
    case MQX_API_TASK_GET_TD:
        res = (uint32_t)_task_get_td((_task_id)param0);
        break;

#if MQX_USE_LWMEM
    case MQX_API_LWMEM_ALLOC:
        res = (uint32_t)_usr_lwmem_alloc_internal((_mem_size)param0);
        break;

    case MQX_API_LWMEM_ALLOC_FROM:
        if (_psp_mem_check_access(param0, sizeof(LWMEM_POOL_STRUCT), MPU_UM_RW) && \
            _psp_mem_check_access((uint32_t)(((LWMEM_POOL_STRUCT_PTR)param0)->POOL_ALLOC_START_PTR), (char*)(((LWMEM_POOL_STRUCT_PTR)param0)->POOL_ALLOC_END_PTR) - (char*)(((LWMEM_POOL_STRUCT_PTR)param0)->POOL_ALLOC_START_PTR), MPU_UM_RW))
            res = (uint32_t)_lwmem_alloc_from((_lwmem_pool_id)param0, (_mem_size)param1);
        else
            res = 0; // NULL, allocation failed
        break;

    case MQX_API_LWMEM_FREE:
        if (_psp_mem_check_access(param0, 4, MPU_UM_RW))
            res = _lwmem_free((void *)param0);
        break;

    case MQX_API_LWMEM_CREATE_POOL:\
        if (_psp_mem_check_access(param0, sizeof(LWMEM_POOL_STRUCT), MPU_UM_RW) && \
            _psp_mem_check_access(param1, param2, MPU_UM_RW))
            res = (uint32_t)_lwmem_create_pool((LWMEM_POOL_STRUCT_PTR)param0, (void *)param1, (_mem_size)param2);
        break;

    case MQX_API_LWMEM_REALLOC:
        if (_psp_mem_check_access(param0, 4, MPU_UM_RW))
          res = (uint32_t)_lwmem_realloc((void *)param0,(_mem_size)param1);
        break;
#endif // MQX_USE_LWMEM

    // _time
    case MQX_API_TIME_DELAY:
        _time_delay(param0);
        res = MQX_OK;       // irelevant, function is without return value
        break;

#if MQX_HAS_TICK
    case MQX_API_TIME_DELAY_TICKS:
        _time_delay_ticks(param0);
        res = MQX_OK;       // irelevant, function is without return value
        break;
    case MQX_API_TIME_GET_ELAPSED_TICKS:
        if (_psp_mem_check_access(param0, sizeof(MQX_TICK_STRUCT), MPU_UM_RW)) {
            _time_get_elapsed_ticks((MQX_TICK_STRUCT_PTR)param0);
            res = MQX_OK;       // irelevant, function is without return value
        }
        else {
            _task_set_error(MQX_ACCESS_ERROR);
        }

        break;
#endif // MQX_HAS_TICK
    default:
        while (1);
    }

    return res;
}
Example #15
0
/*TASK*-----------------------------------------------------------------
*
* Function Name  : sdcard_task
* Returned Value : void
* Comments       :
*
*END------------------------------------------------------------------*/
void sdcard_task(uint_32 temp)
{
    boolean      inserted = TRUE, readonly = FALSE, last = FALSE;
    _mqx_int     error_code;
    _mqx_uint    param;
    MQX_FILE_PTR com_handle, sdcard_handle, filesystem_handle, partman_handle;
    char         filesystem_name[] = "a:";// 文件系统 名字
    char         partman_name[] = "pm:";// 分区管理 名字
#if defined BSP_SDCARD_GPIO_DETECT
    #if ! BSP_SDCARD_GPIO_DETECT_INT
    LWGPIO_STRUCT      sd_detect;
    #else 
    LWGPIO_STRUCT      sd_detect;
    /************************dx 20121210**********************************************
     */
    GPIO_PIN_STRUCT sd_detect_int[] = {
        BSP_SDCARD_GPIO_DETECT | GPIO_PIN_IRQ_FALLING | GPIO_PIN_IRQ_RISING,
        GPIO_LIST_END
    };
    
    MQX_FILE_PTR port_file_sd_detect_int;
    /***********************************************************************************/
    #endif
    
    
#endif
#if defined BSP_SDCARD_GPIO_PROTECT
    LWGPIO_STRUCT      sd_protect;
#endif
#ifdef BSP_SDCARD_GPIO_CS

    LWGPIO_STRUCT          sd_cs;
    SPI_CS_CALLBACK_STRUCT callback;

#endif
    
    
    /* Open low level communication device */
    com_handle = fopen (SDCARD_COM_CHANNEL, NULL);// 打开"esdhc:"模块底层驱动 

    if (NULL == com_handle)
    {
        printf("Error installing communication handle.\n");
        _task_block();
    }

#ifdef BSP_SDCARD_GPIO_CS

    /* Open GPIO file for SPI CS signal emulation */
    error_code = lwgpio_init(&sd_cs, BSP_SDCARD_GPIO_CS, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);// 安装简单引脚用于spi片选
    if (!error_code)
       {
           printf("Initializing GPIO with associated pins failed.\n");
           _task_block();
       }
    lwgpio_set_functionality(&sd_cs,BSP_SDCARD_CS_MUX_GPIO);
    lwgpio_set_attribute(&sd_cs, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
    /* Set CS callback */
    callback.MASK = BSP_SDCARD_SPI_CS;
    callback.CALLBACK = set_CS;
    callback.USERDATA = &sd_cs;
    if (SPI_OK != ioctl (com_handle, IO_IOCTL_SPI_SET_CS_CALLBACK, &callback))
    {
        printf ("Setting CS callback failed.\n");
        _task_block();
    }

#endif

#if defined BSP_SDCARD_GPIO_DETECT
    #if ! BSP_SDCARD_GPIO_DETECT_INT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_detect, BSP_SDCARD_GPIO_DETECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);// 安装简单引脚用于插入检测
       if (!error_code)
       {
           printf("Initializing GPIO with sdcard detect pin failed.\n");
           _task_block();
       }
       /*Set detect and protect pins as GPIO Function */
       lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_GPIO);
       lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
   #else 
       /******************dx 20121210***********************************************/
        if (NULL == (port_file_sd_detect_int = fopen("gpio:read", (char_ptr) &sd_detect_int )))
        {
           printf("Opening port_file_sd_detect_int GPIO with associated button1_int failed.\n");
          _task_block();
        }
        ioctl(port_file_sd_detect_int, GPIO_IOCTL_SET_IRQ_FUNCTION, (pointer)sd_detect_int__callback);
         _lwevent_create(&SD_Event,0); // 创建轻量级事件用于检测SD插入
       /****************************************************************************/
    
   #endif
    
      
#endif

#if defined BSP_SDCARD_GPIO_PROTECT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_protect, BSP_SDCARD_GPIO_PROTECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);// 安装简单引脚用于只读检测
       if (!error_code)
       {
           printf("Initializing GPIO with sdcard protect pin failed.\n");
           _task_block();
       }
       /*Set detect and protect pins as GPIO Function */
       lwgpio_set_functionality(&sd_protect,BSP_SDCARD_PROTECT_MUX_GPIO);
       lwgpio_set_attribute(&sd_protect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif

    /* Install SD card device */
    error_code = _io_sdcard_install("sdcard:", (pointer)&_bsp_sdcard0_init, com_handle);// 安装SD卡驱动,基于"esdhc:"模块
    if ( error_code != MQX_OK )
    {
        printf("Error installing SD card device (0x%x)\n", error_code);
        _task_block();
    }
      /*使用内部IOCTL命令测试SD卡是否已经插入 dx20121223*/
      uint_32  sd_param;
     
      sd_param = 0;
      if (ESDHC_OK != ioctl (com_handle, IO_IOCTL_ESDHC_GET_CARD, &sd_param))
      {
         printf("Error get SD card device type.\n");
          _task_block();
      }
      if (ESDHC_CARD_NONE != sd_param)
      {
         inserted = TRUE; // 已插入SD卡
         printf("inserted = 1 -> %d\n",(int)sd_param);
      }else 
      {
         inserted = FALSE; // 无SD卡
         printf("inserted = 0 -> %d\n",(int)sd_param);
         
      }

    for (;;)/////////////////////////////////////////////////////////////////////////////循环
    {


#if defined BSP_SDCARD_GPIO_PROTECT
        /* Get value of protect pin */
        readonly = lwgpio_get_value(&sd_protect);// 检测磁盘是否只读////////////////////////////////////////
#endif
#ifdef BSP_MPC8308RDB
        /* Set function as SD_CD which indicate that card is present in Present State Register */
        lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_SD_CD);
        lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif
        if (last != inserted)
        {
            if (inserted)// 插入磁盘
            {
               // _time_delay (200);// 将活动的任务挂起指定的毫秒数
                /* Open the device which MFS will be installed on */
                sdcard_handle = fopen("sdcard:", 0);// 打开SD卡层驱动
                if ( sdcard_handle == NULL )
                {
                    printf("Unable to open SD card device.\n");
                    _task_block();
                }

                /* Set read only flag as needed */
                param = 0;
                if (readonly)
                {
                    param = IO_O_RDONLY;
                }
                if (IO_OK != ioctl(sdcard_handle, IO_IOCTL_SET_FLAGS, (char_ptr) &param))
                {
                    printf("Setting device read only failed.\n");
                    _task_block();
                }

                /* Install partition manager over SD card driver */
                error_code = _io_part_mgr_install(sdcard_handle, partman_name, 0);// 分区管理
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error installing partition manager: %s\n", MFS_Error_text((uint_32)error_code));
                    _task_block();
                }

                /* Open partition manager */
                partman_handle = fopen(partman_name, NULL);// 打开分区
                if (partman_handle == NULL)
                {
                    error_code = ferror(partman_handle);
                    printf("Error opening partition manager: %s\n", MFS_Error_text((uint_32)error_code));
                    _task_block();
                }

                /* Validate partition 1 */
                param = 1;
                error_code = _io_ioctl(partman_handle, IO_IOCTL_VAL_PART, &param);// 控制分区
                if (error_code == MQX_OK)
                {

                    /* Install MFS over partition 1 */
                    error_code = _io_mfs_install(partman_handle, filesystem_name, param);/////安装文件系统,基于分区
                    if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error initializing MFS over partition: %s\n", MFS_Error_text((uint_32)error_code));
                        _task_block();
                    }

                } else {

                    /* Install MFS over SD card driver */
                    error_code = _io_mfs_install(sdcard_handle, filesystem_name, (_file_size)0);////////安装文件系统,无分区
                    if (error_code != MFS_NO_ERROR)
                    {
                        printf("Error initializing MFS: %s\n", MFS_Error_text((uint_32)error_code));
                        _task_block();
                    }

                }

                /* Open file system */
                filesystem_handle = fopen(filesystem_name, NULL);// 打开文件系统
                error_code = ferror (filesystem_handle);
                if ((error_code != MFS_NO_ERROR) && (error_code != MFS_NOT_A_DOS_DISK))
                {
                    printf("Error opening filesystem: %s\n", MFS_Error_text((uint_32)error_code));
                    _task_block();
                }
                if ( error_code == MFS_NOT_A_DOS_DISK )
                {
                    printf("NOT A DOS DISK! You must format to continue.\n");
                }

                printf ("SD card installed to %s\n", filesystem_name);
                if (readonly)
                {
                    printf ("SD card is locked (read only).\n");
                }
            }
            else // 拔出磁盘
            {
                /* Close the filesystem */
                if (MQX_OK != fclose (filesystem_handle))
                {
                    printf("Error closing filesystem.\n");
                    _task_block();
                }
                filesystem_handle = NULL;

                /* Uninstall MFS  */
                error_code = _io_dev_uninstall(filesystem_name);
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error uninstalling filesystem.\n");
                    _task_block();
                }

                /* Close partition manager */
                if (MQX_OK != fclose (partman_handle))
                {
                    printf("Unable to close partition manager.\n");
                    _task_block();
                }
                partman_handle = NULL;

                /* Uninstall partition manager  */
                error_code = _io_dev_uninstall(partman_name);
                if (error_code != MFS_NO_ERROR)
                {
                    printf("Error uninstalling partition manager.\n");
                    _task_block();
                }

                /* Close the SD card device */
                if (MQX_OK != fclose (sdcard_handle))
                {
                    printf("Unable to close SD card device.\n");
                    _task_block();
                }
                sdcard_handle = NULL;

                printf ("SD card uninstalled.\n");
                printf ("sd unOK dx.\n");/////////////////////////dx
            }
        }

        last = inserted;
       // _time_delay (200);// 将活动的任务挂起指定的毫秒数 
        
//        #if defined BSP_SDCARD_GPIO_DETECT
//            #if BSP_SDCARD_GPIO_DETECT_INT
//            /****************dx 20121211************************************************************/
//             _lwevent_wait_ticks(&SD_Event,SD_EVENT_DETECT,FALSE,0);///////////等待事件USB_EVENT
//             _lwevent_clear(&SD_Event,SD_EVENT_DETECT);
//           /****************************************************************************************/    
//            #endif
//        #endif
      /*使用SD外部端口测试SD卡是否已经插入*/
#if defined BSP_SDCARD_GPIO_DETECT
        #ifdef BSP_MPC8308RDB
        /* Set function as GPIO to detect sdcard */
        lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_GPIO);
        lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
        #endif
        #if ! BSP_SDCARD_GPIO_DETECT_INT
        
        inserted = !lwgpio_get_value(&sd_detect);// 检测磁盘是否插入/////////////////////////////////////////
        #else
        /****************dx 20121211************************************************************/
         _lwevent_wait_ticks(&SD_Event,SD_EVENT_DETECT,FALSE,0);///////////等待事件USB_EVENT
          _lwevent_clear(&SD_Event,SD_EVENT_DETECT);
         ioctl(port_file_sd_detect_int, GPIO_IOCTL_READ, (char_ptr) &sd_detect_int);
         inserted = !( sd_detect_int[0] & GPIO_PIN_STATUS);
       /****************************************************************************************/    
        #endif
            
#endif
        
       
    }/////////////////////////////////////////////////////////////////////////////循环
}
Example #16
0
void sd_file_search_task(uint_32 para) {
	
	lp_param_t *  lpp_param =  (lp_param_t *)para;
	char * path = (char *)lpp_param->path;
	set_file_filter((char **) ext_wantted);
	
	while (1) {
		_lwevent_wait_ticks(
				&player_event,
				PLAYER_EVENT_MSK_NEXT_BTN_PRESSED
						| PLAYER_EVENT_MSK_PREV_BTN_PRESSED
						| PLAYER_EVENT_MSK_SD_FS_MOUNTED |PLAYER_EVENT_MSK_SEARCH_TASK_QUIT, FALSE, 0);

		full_path[0] = '\0';

		if (player_event.VALUE & PLAYER_EVENT_MSK_SEARCH_TASK_QUIT) {
			//printf("search task %d exit\n",lpp_param->lp_type);
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_SEARCH_TASK_QUIT);
			goto exit_search;
		}

		printf("search lock umount at %d\n",lpp_param->lp_type);
		_lwsem_wait(lpp_param->mfs_io_sem);
		if (player_event.VALUE & PLAYER_EVENT_MSK_NEXT_BTN_PRESSED) {
			//get_next_file_name("a:\\", full_path);
			get_next_file_name(path, full_path);
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_NEXT_BTN_PRESSED);
			
			//printf("search id1\n");
		} else if (player_event.VALUE & PLAYER_EVENT_MSK_PREV_BTN_PRESSED) {
			//get_prev_file_name("a:\\", full_path);
			get_prev_file_name(path, full_path);
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_PREV_BTN_PRESSED);
			
			//printf("search id2\n");
		} else if (player_event.VALUE & PLAYER_EVENT_MSK_SD_FS_MOUNTED) {
			//get_next_file_name("a:\\", full_path);
			get_next_file_name(path, full_path);
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_SD_FS_MOUNTED);
			//printf("MOUNTED! 1: %s\n", full_path);
		}		

		printf("search unlock umount at %d\n",lpp_param->lp_type);
		_lwsem_post(lpp_param->mfs_io_sem);
		/* If found*/
		if (full_path[0] != '\0')
			{_lwevent_set(&player_event, PLAYER_EVENT_MSK_SONG_READY);
			 printf("search y\n");
			}
		else
		     printf("search n\n");
	}

exit_search:
   fs_walker_clear();
   printf("sd_file_search_task exit.\n");
   //printf("__guoyifang__: sd_file_search_task  %d set SEARCH_TASK_KILLED.\n",lpp_param->lp_type);
  _lwevent_set(&player_event, PLAYER_EVENT_MSK_SEARCH_TASK_KILLED);
 //_task_block(); //wait for being destroyed

}
Example #17
0
void local_player_task(uint_32 para) 
{
	_mqx_int return_code, res;
	my_audio_format_t format;
	FILE_PTR stream_ptr = NULL, stream_ptr1 = NULL;      //device_ptr = NULL, 
	uint_32 mclk_freq, fs_freq, bit_width = 0;
	I2S_STATISTICS_STRUCT stats;
	int32_t numberOfSamples =0, sampleProduced, bufOut;
	file_meta_data_t * metadata = NULL;
	audio_stream_type_t stream_type;
	char_ptr mem_ptr = NULL;
	boolean shell_cmd = FALSE;
        CCI_Ctx ctx;
	int32_t strLen, i;
	uint32_t file_extension=0;
	
	_task_id pcm_flush_id = MQX_NULL_TASK_ID;
	uint_32 cnt = 0;
	int32_t max_audio_buf_size = 0;
	lp_param_t *  lpp_param =  (lp_param_t *)para;
        TASK_TEMPLATE_STRUCT task_template;

	printf("local_player_task.. Enter 1\n");
	if (msi_snd_init_with_periodbuffer(1024, 18) != 0) /* for SPI sd card play FLAC, 18K buffer is at least! */
	{
		LOCALPLAY_LOG("  Error: Unable to open the device \"%s\".\n",
				AUDIO_DIVECE_NAME_STR);
		return;
	}
	
	/* create semaphore must before pcm_flush_task */
	if(MQX_OK != _lwsem_create(&pcm_decoded_sem, 0))
	{
		LOCALPLAY_LOG("\n Error - Unable to creat lwsem: pcm_decoded_sem\n");
	}
	
	
        LOCALPLAY_LOG("Creating pcm flush task.........\n");

        task_template.TASK_TEMPLATE_INDEX  = 0;
        task_template.TASK_ADDRESS         = pcm_flush_task;
        task_template.TASK_STACKSIZE       = 2000;
        task_template.TASK_PRIORITY        = 12;
        task_template.TASK_NAME            = "pcm_flush";
        task_template.TASK_ATTRIBUTES      = 0;
        task_template.CREATION_PARAMETER   = 0;
        task_template.DEFAULT_TIME_SLICE   = 0;

        pcm_flush_id = _task_create_blocked(0, 0, (uint_32)&task_template);

        if (pcm_flush_id  == MQX_NULL_TASK_ID)
        {
            printf("local_player_task create pcm_flush_task failed \n");
            goto clean_up;
        }
        else{
            gPcmFlushTaskFinish = 0;
            _task_ready(_task_get_td(pcm_flush_id));
            _lwevent_set(&player_event, PLAYER_EVENT_MSK_SONG_RESUME);
        }


	metadata = (file_meta_data_t *) _mem_alloc_system_zero(sizeof(file_meta_data_t));
	if (NULL == metadata) 
	{
		LOCALPLAY_LOG("\n Failed to allocate memory for metadata.\n");
		return;
	}

        decoding = TRUE;
	
	while (1) {

#ifndef  USB_ACCESSORY_PLAY		
		_lwevent_wait_ticks(
				&player_event,
				PLAYER_EVENT_MSK_SONG_READY | PLAYER_EVENT_MSK_SD_FS_UNMOUNTED
						| PLAYER_EVENT_MSK_SHELL_COMMAND, FALSE, 0);
#else
_lwevent_wait_ticks(
				&player_event,
				PLAYER_EVENT_MSK_SONG_READY | PLAYER_EVENT_MSK_SD_FS_UNMOUNTED
						| PLAYER_EVENT_MSK_SHELL_COMMAND | PLAYER_EVENT_MSK_USB_ATTACHED, FALSE, 0);		
#endif
		shell_cmd = FALSE;


#ifdef USB_ACCESSORY_PLAY
		if (player_event.VALUE & PLAYER_EVENT_MSK_USB_ATTACHED) {
					_lwevent_clear(&player_event, PLAYER_EVENT_MSK_USB_ATTACHED);
					//LOCALPLAY_LOG("__guoyifang__: sd_player_task PLAYER_EVENT_MSK_USB_ACC_ATTACHED \n");
					break;
				}
#endif

		if (player_event.VALUE & PLAYER_EVENT_MSK_SD_FS_UNMOUNTED) {
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_SD_FS_UNMOUNTED);
			//LOCALPLAY_LOG("__guoyifang__: sd_player_task PLAYER_EVENT_MSK_SD_FS_UNMOUNTED \n");
			break;
		}	

		if (player_event.VALUE & PLAYER_EVENT_MSK_SONG_READY) {
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_SONG_READY);
		}

		if (player_event.VALUE & PLAYER_EVENT_MSK_SHELL_COMMAND) {
			_lwevent_clear(&player_event, PLAYER_EVENT_MSK_SHELL_COMMAND);
			shell_cmd = TRUE;
		}

		LOCALPLAY_LOG(" --------------------------------------------------------------\n");

	    printf("play lock umount at %d\n",lpp_param->lp_type);
	    _lwsem_wait(lpp_param->mfs_io_sem);
	    /******************decoding is a critical value, assume decoding is TRUE every time.*******************/    
	    printf("SET decoding.\n");
	    decoding = TRUE; // next/prev btn ISR may clear decoding to 0
	    /*******************************************/
		/*config the audio subsystem according metadata*/
		        		printf(
		        				"  Open stream file %s\n", full_path);
		        		stream_ptr = fopen(full_path, "r");
		        		if (stream_ptr == NULL) {
		        			printf("  Unable to open the file: %s\n", full_path);
		        			goto clean_up;
		        		}

		        		stream_ptr1 = fopen(full_path, "r");
		        		if (stream_ptr1 == NULL) {
		        			printf("  Unable to open the file: %s\n", full_path);
		        			goto clean_up;
		        		}
		        		
		                /* Determine the extension of the file */ 
		                i=0;
		                strLen= strlen((const char *)full_path);

		                if(strLen > 4){
		                    /* find the '.' */
		                    while(strLen--){
		                        if(full_path[i]=='.')
		                            break;
		                        i++;
		                    }
		                    if(strLen){
		                        char *p;
		                        /* Copy out the extension : 8.3 filename */
		                        memcpy(&file_extension, full_path+i+1, 3);
		                        p = (char *) (&file_extension);
		                        for(i = 0; i < 4; i++, p++){
		                            if((*p >= 'a') && (*p <= 'z')){
		                                *p -= ('a' - 'A');
		                            }
		                        }
		                    } 

		                    ctx.user_data = (void*) stream_ptr;
		                    ctx.cci_dec_read = get_file_data;;
		                    ctx.cci_dec_seek = seek_file_data;
		                    ctx.cci_dec_tell = get_file_position;

		                    /* Check if metadata was found. */
		                    return_code = cci_extract_meta_data(file_extension, metadata, &ctx);        
		        		    if (return_code != 0) {
		        			    printf("\n Metadata not found\n");
		        			    goto clean_up;
		        		    }

		        		    print_metadata(metadata); //todo

		                } else {
		        			printf("\n Metadata not found\n");
		        			goto clean_up;
		                }
		                if ( metadata->stream_type == STREAM_TYPE_MP3 ) {
		                	/* Seek from the beginning of the file */ 
		                    seek_file_data(0, metadata->start_pos, 0, stream_ptr);
		                } else {
		                	/* Seek from the beginning of the file */
		                	seek_file_data(0, 0, 0, stream_ptr);
		        		}
		        
		        
		        stream_type = metadata->stream_type;

#if 0	
		format.audio_format.ENDIAN = AUDIO_LITTLE_ENDIAN;
		format.audio_format.ALIGNMENT = AUDIO_ALIGNMENT_LEFT;
		if((streamType == kCodecStreamTypePcm) ||	// bitsPerSample Value is 8/16/24
				/*
				 * The demo not support kCodecStreamTypeImaAdpcm/kCodecStreamTypeMsAdpcm currently.
				 */
				(streamType == kCodecStreamTypeImaAdpcm) || // bitsPerSample Value is 4
				(streamType == kCodecStreamTypeMsAdpcm))	// bitsPerSample Value is 4
		{	
			format.audio_format.BITS = metadata->i32BitsPerSample;
		}else{
			format.audio_format.BITS = 16; 
		}
		
		// Currently, the wave decoder output 16bits only for kCodecStreamTypePcm.
		format.audio_format.BITS = 16;
		
		format.audio_format.SIZE = (format.audio_format.BITS + 7)/8;

		
		format.audio_format.CHANNELS = metadata->i32NumChannels;
		format.fs_freq = metadata->u32SampleRate;

		fs_freq = format.fs_freq;
		mclk_freq = fs_freq * CLK_MULT;
		// Setup audio data format in device 
		if (ioctl(device_ptr, IO_IOCTL_AUDIO_SET_IO_DATA_FORMAT,
				&format.audio_format) != I2S_OK) {
			LOCALPLAY_LOG("  Error: Input data format not supported.\n");
			goto clean_up;
		}
		// Setup rest of parameters - master clock, valid data bits and sampling frequency 
		if ((ioctl(device_ptr, IO_IOCTL_I2S_SET_MCLK_FREQ, &mclk_freq) != I2S_OK)
				|| (ioctl(device_ptr, IO_IOCTL_I2S_SET_DATA_BITS,
						&format.audio_format.BITS) != I2S_OK)
				|| (ioctl(device_ptr, IO_IOCTL_I2S_SET_FS_FREQ, &fs_freq)
						!= I2S_OK)) {
			LOCALPLAY_LOG("  Error: Unable to setup \"%s\" device driver.\n",
					AUDIO_DIVECE_NAME_STR);
			goto clean_up;
		}

		// Setup audio codec 
		return_code = SetupCodec(device_ptr);
		if (return_code != 0) {
			LOCALPLAY_LOG("  Audio codec configuration failed. Error 0x%X.\n",
					return_code);
			goto clean_up;
		}

		ioctl(device_ptr, IO_IOCTL_I2S_GET_FS_FREQ, &fs_freq);
		ioctl(device_ptr, IO_IOCTL_I2S_GET_DATA_BITS, &bit_width);
		LOCALPLAY_LOG("  Playback information\n");
		LOCALPLAY_LOG("  Sampling frequency:     %d Hz\n", fs_freq);
		LOCALPLAY_LOG("  Bit depth:              %d bits\n", (uint_8)bit_width);
		LOCALPLAY_LOG("  Channels:               ");
		
		if (format.audio_format.CHANNELS == 1) {
			LOCALPLAY_LOG("mono\n");
		} else {
			LOCALPLAY_LOG("stereo\n");
		}
#else
		if((stream_type == STREAM_TYPE_PCM) ||	// bitsPerSample Value is 8/16/24
		/*
		 * The demo not support kCodecStreamTypeImaAdpcm/kCodecStreamTypeMsAdpcm currently.
		 */
		(stream_type == STREAM_TYPE_IMAADPCM) || // bitsPerSample Value is 4
		(stream_type == STREAM_TYPE_MSADPCM))	// bitsPerSample Value is 4
		{	
			format.audio_format.BITS = metadata->bits_per_sample;
		}else{
			format.audio_format.BITS = 16; 
		}
		
		format.audio_format.CHANNELS = metadata->num_channels;
		// Currently, the wave decoder output 16bits only for kCodecStreamTypePcm.
		format.audio_format.BITS = 16;
#if 0
		if(audio_ioctl(setChNum, format.audio_format.CHANNELS)!= I2S_OK)
        {
		  LOCALPLAY_LOG("  Error: audio_ioctl setChNum failed.\n");
		  goto clean_up;
        }
		if(audio_ioctl(setBitWidth, format.audio_format.BITS)!= I2S_OK)
		{

		  LOCALPLAY_LOG("  Error: audio_ioctl setBitWidth failed.\n");
		  goto clean_up;
		}
#endif
		
		format.fs_freq = metadata->sample_rate;
		
#if 0
		if(audio_ioctl(setSamplerate, format.fs_freq)!= I2S_OK)
	    {
		  LOCALPLAY_LOG("  Error: audio_ioctl setSamplerate failed.\n");
		  goto clean_up;
	    }
#endif
		msi_snd_set_format(format.fs_freq, format.audio_format.BITS, format.audio_format.CHANNELS);
	

#endif

		mem_ptr = (char_ptr) _mem_alloc_system_zero(codec_get_mem_info(stream_type));
		if (NULL == mem_ptr) {
			LOCALPLAY_LOG("Failed to allocate memory for the decoder.\n");
			goto clean_up;
		}

		// MP4 decoder need two fd
		g_userData[0] = (int) stream_ptr;
		g_userData[1] = (int) stream_ptr1;
		if (metadata->audio_sub_type == MEDIA_SUBTYPE_ADTS)
			g_userData[2] = 1;
		else if (metadata->audio_sub_type == MEDIA_SUBTYPE_M4A)
			g_userData[2] = 2;
		else if ( metadata->stream_type == STREAM_TYPE_OPUS )
		{
			g_userData[2] = metadata->sample_rate;
			g_userData[3] = metadata->num_channels;
	    }
		else
			g_userData[2] = 0; 

		g_callbackFunctionArray[0] = (int32_t *) &get_file_data;
		g_callbackFunctionArray[1] = (int32_t *) &seek_file_data;
		g_callbackFunctionArray[2] = (int32_t *) &get_file_position;

		while (1) {
			res = codec_init(stream_type, (long **)&mem_ptr,g_callbackFunctionArray,
								&g_userData[0]);
			if (res == CODEC_INIT_ERROR) {
				LOCALPLAY_LOG("\n  Codec Init Failed with error code %d\n", res);
				decoding = FALSE; 
				goto clean_up;
			}
			if (res == CODEC_MORE_DATA_REQUIRED) {
				LOCALPLAY_LOG("\n  More Data Processing Required for Init \n");
			}
			if (res == CODEC_SUCCESS) {
				LOCALPLAY_LOG("\n  Codec Init Done Successfully \n\n");
				break;
			}
			else {
				printf("codec init other err\n");
				decoding = FALSE;
				goto clean_up;
			}
		}

		if (res == CODEC_SUCCESS) {
			LOCALPLAY_LOG("  Playing %s...\n\n", full_path);
		//	ioctl(device_ptr, IO_IOCTL_I2S_CLEAR_STATISTICS, NULL);
			/* Reset variables before every song's playbacking */
			
			//printf("SET decoding.\n");
			//decoding = TRUE; // next/prev btn ISR may clear decoding to 0
			cnt = 0;

			max_audio_buf_size = 0;
			g_audio_buf_ptr = NULL;
			//_lwevent_clear(&player_event, PLAYER_EVENT_MSK_AUDIO_BUF_FILLED);
			/* Clear pcm_decoded_sem for play next song */
			_lwsem_poll(&pcm_decoded_sem);
			_lwsem_poll(&pcm_decoded_sem);  
					
			if(MQX_OK != _lwsem_create(&pcm_flush_sem, AUDIO_BUF_CNT))
			{
				LOCALPLAY_LOG("\n Error - Unable to create lwsem: pcm_flush_sem\n");
			}
			
			/*
			 * umute
			 */
			msi_snd_umute();
			//sai_dma_output_init();
			
			while (decoding) {
				/*
				 * For FLAC decoder, it produced more than 18K bytes per frame, and takes about 30ms. 
				 * While take 44.1K/16bit/2ch/4Kbytes DMA buffer as example, the margin time is 4K/4/2/44100~=10ms. 
				 * We need bigger DMA buffer, or decode in a ping-pong way.
				 */		
				res = codec_decode(stream_type, (long **)&mem_ptr, &sampleProduced,
										&bufOut);
              
				if (res == CODEC_END_OF_DECODE) {					
					printf("\n  End of Decode \n");
					break;
				}
				else if (res == CODEC_DECODE_ERROR) {
					printf("\n  Codec Decode Failed \n");
					break;
				}
				else if(res != CODEC_SUCCESS){
					printf("codec_decode else err %d\n",res);
						break;
				}
				
				cnt += sampleProduced;
				
				while (decoding) 
				 {
					numberOfSamples = codec_get_pcm_samples(stream_type,
											(long **)&mem_ptr, &sampleProduced, &bufOut);
					if (numberOfSamples == 0)
						break;
					
#if 1
					if (max_audio_buf_size < sampleProduced) { //More bigger buffer needed
						max_audio_buf_size = sampleProduced;
						if (NULL != g_audio_buf_ptr) {
							LOCALPLAY_LOG(" Bigger buffer needed.\n");
							_mem_free(g_audio_buf_ptr);
						}
						g_audio_buf_ptr = (uchar_ptr) _mem_alloc_system_zero(max_audio_buf_size);
						if (NULL == g_audio_buf_ptr) {
							LOCALPLAY_LOG(" Failed to allocate g_audio_buf_ptr. max_audio_buf_size %d \n", max_audio_buf_size);
							decoding = 0;
							break;
						}	
#if 1
						//sai_dma_buffer_adjust(sampleProduced);			
#endif
					}
#endif
					
				    if (MQX_OK != _lwsem_wait(&pcm_flush_sem))
				    {
					  LOCALPLAY_LOG("\n Error: Wait for pcm_flush_sem failed.\n");
					 // _task_set_error(res);
				    }
				    
					_mem_copy((void *)bufOut, g_audio_buf_ptr, sampleProduced);
                                        //g_audio_buf_ptr = bufOut;
					g_buf_bytes_to_flush = sampleProduced;
		
					if (_lwsem_post(&pcm_decoded_sem) != MQX_OK)
					 {
					   LOCALPLAY_LOG("\n  pcm_flush : Error - Unable to set pcm_decoded_sem.");
					 }

					if (numberOfSamples == sampleProduced)
						sampleProduced = 0;
				 }//end while decoding
	 	  }//end while decoding
		}//end if res==kCodeSuccess
		
		#if 0
		fflush(device_ptr);
		#else
		msi_snd_mute();

                if (MQX_OK != _lwsem_wait(&pcm_flush_sem))
                    LOCALPLAY_LOG("\n Error: Wait for latest pcm_flush_sem failed.\n");
		msi_snd_flush();
		#endif
		
#if 1
		//sai_dma_output_stop();
#endif	
#if 0
		/* Print transfer statistics */
		if (ioctl(device_ptr, IO_IOCTL_I2S_GET_STATISTICS, &stats) != I2S_OK) {
			LOCALPLAY_LOG("  Error: Cannot read I2S statistics.\n");
		} else {
			LOCALPLAY_LOG("\n  Playback stats\n");
			LOCALPLAY_LOG("  Total interrupts:              %d\n", stats.INTERRUPTS);
			LOCALPLAY_LOG("  Bytes requested for transmit:  %d\n",
					stats.PACKETS_REQUESTED * format.audio_format.SIZE);
			LOCALPLAY_LOG("  Bytes transmitted:             %d\n",
					stats.TX_PACKETS * format.audio_format.SIZE);
			LOCALPLAY_LOG("  Underruns of hardware FIFO:    %d\n", stats.FIFO_ERROR);
			LOCALPLAY_LOG("  Software buffer empty:         %d\n", stats.BUFFER_ERROR);
		}
#endif
	        LOCALPLAY_LOG("\n  DONE\n");
			
		clean_up:
		printf("done to clean up,decoding %d \n",decoding);		
		/* Clean up for next song */
		if (NULL != mem_ptr) {
			_mem_free(mem_ptr);
			mem_ptr = NULL;
		}
		if (NULL != g_audio_buf_ptr) {
			_mem_free(g_audio_buf_ptr);
			g_audio_buf_ptr = NULL;
		}
		if (NULL != stream_ptr) {
			res = fclose(stream_ptr);
			if ((res != MQX_OK)&&(res != MFS_DISK_IS_WRITE_PROTECTED)) {
				/*LOCALPLAY_LOG*/printf("  Error: Unable to close file 0x%x.\n", res);
			}
			stream_ptr = NULL;
		}
		if (NULL != stream_ptr1) {
			res = fclose(stream_ptr1);
			if ((res != MQX_OK)&&(res != MFS_DISK_IS_WRITE_PROTECTED)) {
				/*LOCALPLAY_LOG*/printf("  Error: Unable to close file 0x%x.\n", res);
			}
			stream_ptr1 = NULL;
		}
		
		if(MQX_OK != _lwsem_destroy(&pcm_flush_sem))
		  {
			LOCALPLAY_LOG("\n Error - Unable to destroy lwsem: pcm_flush_sem\n");
		  }

		if (decoding == TRUE) { // playback finished in normal way, ie, next/prev not pressed
			if (!shell_cmd) { 	// and was not triggered by Shell
				// just like next btn being pressed
				_lwevent_set(&player_event, PLAYER_EVENT_MSK_NEXT_BTN_PRESSED);
			}
		}
		
	    /* if exit this task ,must route this point ! */
	    printf("play unlock umount at %d\n",lpp_param->lp_type);
	    _lwsem_post(lpp_param->mfs_io_sem);
	}//end while(1)
#if 0
	// clean up further
	if (NULL != device_ptr) {	
		if (fclose(device_ptr) != MQX_OK) {
			LOCALPLAY_LOG("  Error: Unable to close \"%s\" device driver.\n",
					full_path);
		}
	}
#else	
	msi_snd_deinit();
#endif
			
	if (NULL != metadata)
		_mem_free(metadata);	

	if (MQX_NULL_TASK_ID != pcm_flush_id)
	  {
            gPcmFlushTaskFinish = 1;
	    _lwsem_post(&pcm_decoded_sem);
            while(gPcmFlushTaskFinish == 1){
                _sched_yield();
            }

            //_task_destroy(pcm_flush_id);
	    pcm_flush_id = MQX_NULL_TASK_ID;
	    ///*LOCALPLAY_LOG*/printf(" pcm flush task destoryed \n");
	  }
	
	if(MQX_OK != _lwsem_destroy(&pcm_decoded_sem))
		  {
			LOCALPLAY_LOG("\n Error - Unable to destroy lwsem: pcm_decoded_sem\n");
		  }
	
  //printf("__guoyifang__: sd_player_task %d set PLAYER_TASK_KILLED.\n",lpp_param->lp_type);
  _lwevent_set(&player_event, PLAYER_EVENT_MSK_PLAYER_TASK_KILLED);
  
  printf("sd_player_task  exit.\n");
  //_task_block(); //wait for being destroyed
  
}
Example #18
0
void TestApp_Init(void)
{
   AUDIO_CONFIG_STRUCT       audio_config;
   USB_CLASS_AUDIO_ENDPOINT  * endPoint_ptr;

   /* Pointer to audio endpoint entry */  
   endPoint_ptr = USB_mem_alloc_zero(sizeof(USB_CLASS_AUDIO_ENDPOINT)*AUDIO_DESC_ENDPOINT_COUNT);
   /* USB descriptor endpoint */
   audio_config.usb_ep_data = &usb_desc_ep;
   /* USB audio unit */
   audio_config.usb_ut_data = &usb_audio_unit;
   /* Endpoint count */
   audio_config.desc_endpoint_cnt = AUDIO_DESC_ENDPOINT_COUNT;
   /* Application callback */
   audio_config.audio_class_callback.callback = USB_App_Callback;
   /* Application callback argurment */
   audio_config.audio_class_callback.arg = &g_app_handle;
   /* Vendor callback */
   audio_config.vendor_req_callback.callback = NULL;
   /* Vendor callback argurment */
   audio_config.vendor_req_callback.arg = NULL;
   /* Param callback function */
   audio_config.param_callback.callback = USB_Notif_Callback;
   /* Param callback argurment */
   audio_config.param_callback.arg = &g_app_handle;
   /* Memory param callback */
   audio_config.mem_param_callback.callback = NULL;
   /* Memory param callback argurment */
   audio_config.mem_param_callback.arg = &g_app_handle;
   /* Descriptor callback pointer */
   audio_config.desc_callback_ptr =  &desc_callback;
   /* Audio enpoint pointer */
   audio_config.ep = endPoint_ptr;

   /* Initialize timer module */
//   audio_timer_init();

//   _audio_timer_init_freq(AUDIO_TIMER, AUDIO_TIMER_CHANNEL, AUDIO_SPEAKER_FREQUENCY, AUDIO_TIMER_CLOCK, TRUE);

    if (MQX_OK != _usb_device_driver_install(USBCFG_DEFAULT_DEVICE_CONTROLLER)) {
        printf("Driver could not be installed\n");
        return;
    }

   /* Initialize the USB interface */
   g_app_handle = USB_Class_Audio_Init(&audio_config);

   if (MQX_OK != _lwevent_create(&app_event, LWEVENT_AUTO_CLEAR)) {
      printf("\n_lwevent_create app_event failed.\n");
      _task_block();
   }
   
   if (MQX_OK != _lwevent_wait_ticks(&app_event, USB_APP_ENUM_COMPLETE_EVENT_MASK, FALSE, 0)) {
      printf("\n_lwevent_wait_ticks app_event failed.\n");
      _task_block();
   }
   
   if (MQX_OK != _lwevent_clear(&app_event, USB_APP_ENUM_COMPLETE_EVENT_MASK)) {
      printf("\n_lwevent_clear app_event failed.\n");
      _task_block();
   }
   printf("Audio speaker is working ... \r\n");
   /* Prepare buffer for first isochronous input */
   USB_Class_Audio_Recv_Data(g_app_handle,AUDIO_ISOCHRONOUS_ENDPOINT,
                  audio_data_buff0, DATA_BUFF_SIZE);

   _task_block();   
} 
Example #19
0
/*TASK*-----------------------------------------------------
*
* Task Name    : main_task
* Comments     : Low power modes switching.
*
*END*-----------------------------------------------------*/
void main_task
    (
        uint32_t initial_data
    )
{
    LPM_OPERATION_MODE operation_mode;
    IDLE_LOOP_STRUCT   idle_loops;
    uint32_t            loop1;

    /* Initialize switches */
    button_led_init();
    
    _int_install_unexpected_isr();
    _lpm_register_wakeup_callback(BSP_LLWU_INTERRUPT_VECTOR, BSP_LLWU_INTERRUPT_PRIORITY, NULL);

    /* Install interrupt for timer wakeup */
    install_timer_interrupt();
    
    /* Create global event */
    if (_lwevent_create(&app_event, 0) != MQX_OK)
    {
        printf("\nCreating app_event failed.\n");
        _task_block();
    }

#if (PSP_MQX_CPU_IS_KINETIS)
    if (_lpm_get_reset_source() != MQX_RESET_SOURCE_LLWU)
        printf("\nMQX Low Power Modes Demo\n");
    else
#endif
        printf("\nWake up by reset from LLWU\n");

    while (1)
    {
#if (MQX_ENABLE_HSRUN)
        /* Find out current mode setting */
        operation_mode = _lpm_get_operation_mode();

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s ***********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: HSRUN operation mode is mapped on HSRUN power mode by default.\n"
        "      The core runs at full clock speed.\n"
        "      It continues the execution after entering the mode.\n"
        "      LED2 blinks quickly, LED1 toggles after the button press.\n");

                /* Wait for button press */
        printf ("Press button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        /* Change frequency to normal run mode. */
        printf("\nChanging frequency to normal run mode.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_0))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }
                /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN) == 0 ? "OK" : "ERROR");
#endif
        /* Find out current mode setting */
        operation_mode = _lpm_get_operation_mode();

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s ***********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: RUN operation mode is mapped on RUN power mode by default.\n"
        "      The core runs at full clock speed.\n"
        "      It continues the execution after entering the mode.\n"
        "      LED2 blinks quickly, LED1 toggles after the button press.\n");

        /* Demonstration of idle task sleep feature */
        printf("\nIdle task sleep feature disabled.\n");
        _lpm_idle_sleep_setup (FALSE);
        
        printf("Task suspended for 1 second to let run the idle task.\n");
        _mqx_get_idle_loop_count (&idle_loops);
        loop1 = idle_loops.IDLE_LOOP1;
        _time_delay (1000);
        
        _mqx_get_idle_loop_count (&idle_loops);
        printf ("Idle loops per second with idle sleep disabled: %d\n", idle_loops.IDLE_LOOP1 - loop1);
        
        printf("Idle task sleep feature enabled.\n");
        _lpm_idle_sleep_setup (TRUE);
        
        printf("Task suspended for 1 second to let run the idle task.\n");
        _mqx_get_idle_loop_count (&idle_loops);
        loop1 = idle_loops.IDLE_LOOP1;
        _time_delay (1000);
        
        _mqx_get_idle_loop_count (&idle_loops);
        printf ("Idle loops per second with idle sleep enabled:  %d\n", idle_loops.IDLE_LOOP1 - loop1);

        printf("Idle task sleep feature disabled.\n\n");
        _lpm_idle_sleep_setup (FALSE);
        
        /* Wait for button press */
        printf ("Press button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_WAIT;
        
        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s **********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: WAIT operation mode is mapped on VLPR power mode by default.\n"
        "      It requires 2 MHz core clock and bypassed pll.\n"
        "      Core continues the execution after entering the mode.\n"
        "      LED2 blinks slowly, LED1 toggles after the button press.\n");

        /* The LPM_OPERATION_MODE_WAIT is mapped on LPM_CPU_POWER_MODE_VLPR by default,
        this mode requires 2 MHz, bypassed PLL clock setting. Change clocks to appropriate mode */
        printf("\nChanging frequency to 2 MHz.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_2MHZ))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }
        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_WAIT) == 0 ? "OK" : "ERROR");

        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed.\n");

        /* Return to RUN mode */
        printf ("\nSetting operation mode back to %s ... ", get_operation_mode_name (LPM_OPERATION_MODE_RUN));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN) == 0 ? "OK" : "ERROR");

        /* Return default clock configuration */
        printf("\nChanging frequency back to the default one.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_DEFAULT))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }

        printf("\nMoving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_SLEEP;

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s *********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: SLEEP operation mode is mapped on WAIT power mode by default.\n"
        "      The core is inactive in this mode, reacting only to interrupts.\n"
        "      The LPM_CPU_POWER_MODE_FLAG_SLEEP_ON_EXIT is set on Kinetis, therefore\n"
        "      core goes to sleep again after any isr finishes. The core will stay awake\n"
        "      after call to _lpm_wakeup_core() from timer wakeup or serial interrupt.\n"
        "      LED2 doesn't blink, LED1 toggles after the button press.\n");

        /* Wake up in 10 seconds */
        set_timer_wakeup ();

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (operation_mode) == 0 ? "OK" : "ERROR");
        
        if (LWEVENT_WAIT_TIMEOUT == _lwevent_wait_ticks (&app_event, TIMER_EVENT_MASK, FALSE, 1))
        {
            printf("\nCore woke up by interrupt. Waiting for timer wakeup ... ");
            _lwevent_wait_ticks (&app_event, TIMER_EVENT_MASK, FALSE, 0);
            printf("OK\n");
        }
        else
        {
            printf("\nCore woke up by timer wakeup.\n");
        }
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        
        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        operation_mode = LPM_OPERATION_MODE_STOP;

        printf("\n******************************************************************************\n");
        printf("************** Operation mode : %s **********************\n", get_operation_mode_name (operation_mode));
        printf("******************************************************************************\n");

        display_operation_mode_setting(operation_mode);

        printf(
        "Info: STOP operation mode is mapped to LLS power mode by default.\n"
        "      Core and most peripherals are inactive in this mode, reacting only to\n"
        "      specified wake up events. The events can be changed in BSP (init_lpm.c).\n"
        "      Serial line is turned off in this mode. The core will wake up from\n"
        "      timer wakeup interrupt.\n"
        "      LED2 doesn't blink, LED1 toggles after the button press.\n");

        /* Wake up in 10 seconds */
        set_timer_wakeup ();

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... \n", get_operation_mode_name (operation_mode));
        _lpm_set_operation_mode (operation_mode);

        /**************************************************************************************************/
        /* SCI HW MODULE IS DISABLED AT THIS POINT - SERIAL DRIVER MUST NOT BE USED UNTIL MODE IS CHANGED */
        /**************************************************************************************************/
        
        /* Return to RUN mode */
        _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN);
        
        printf("\nCore is awake. Moved to next operation mode.\n");
#if MQX_ENABLE_HSRUN
        /* Wait for button press */
        printf ("Press button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");
                        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", get_operation_mode_name (operation_mode));
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_HSRUN) == 0 ? "OK" : "ERROR");
        /* Change frequency to HSRUN mode . */
        printf("\nChanging frequency to HSRUN mode.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_3))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }

#endif
    }
}
Example #20
0
/*!
 * \brief This function receives a message from the specified endpoint if one is available. The data is NOT copied into the user-app. buffer.
 *
 * This is the "zero-copy receive" version of the MCC receive function. No data is copied. 
 * Only the pointer to the data is returned. This version is fast, but it requires the user to manage
 * buffer allocation. Specifically, the user must decide when a buffer is no longer in use and
 * make the appropriate API call to free it.
 *
 * \param[in] endpoint Pointer to the receiving endpoint to receive from.
 * \param[out] buffer_p Pointer to the MCC buffer of the shared memory where the received data is stored.
 * \param[out] recv_size Pointer to an MCC_MEM_SIZE that will contain the number of valid bytes in the buffer.
 * \param[in] timeout_us Timeout, in microseconds, to wait for a free buffer. A value of 0 means don't wait (non-blocking call). A value of 0xffffffff means wait forever (blocking call).
 *
 * \return MCC_SUCCESS
 * \return MCC_ERR_ENDPOINT (the endpoint does not exist)
 * \return MCC_ERR_SEMAPHORE (semaphore handling error)
 * \return MCC_ERR_TIMEOUT (timeout exceeded before a new message came)
 *
 * \see mcc_send
 * \see mcc_recv_copy
 * \see MCC_ENDPOINT
 */
int mcc_recv_nocopy(MCC_ENDPOINT *endpoint, void **buffer_p, MCC_MEM_SIZE *recv_size, unsigned int timeout_us)
{
    MCC_RECEIVE_LIST *list;
    int return_value;
#if (MCC_OS_USED == MCC_MQX)
    unsigned int time_us_tmp;
    unsigned int lwevent_index = endpoint->port / MCC_MQX_LWEVENT_GROUP_SIZE;
    unsigned int lwevent_group_index = endpoint->port % MCC_MQX_LWEVENT_GROUP_SIZE;
    MQX_TICK_STRUCT tick_time;
#endif

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Get list of buffers kept by the particular endpoint */
    list = mcc_get_endpoint_list(*endpoint);

    /* Semaphore-protected section end */
    return_value = mcc_release_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* The endpoint is not valid */
    if(list == null) {
        return MCC_ERR_ENDPOINT;
    }

    if(list->head == (MCC_RECEIVE_BUFFER*)0) {
        /* Non-blocking call */
        if(timeout_us == 0) {
            return MCC_ERR_TIMEOUT;
        }
        /* Blocking call */
        else {
#if (MCC_OS_USED == MCC_MQX)
            if(timeout_us == 0xFFFFFFFF) {
                _lwevent_wait_ticks(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index, TRUE, 0);
            }
            /* timeout_us > 0 */
            else {
                _time_get_ticks(&tick_time);
                _time_add_usec_to_ticks(&tick_time, timeout_us);
                _lwevent_wait_until(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index, TRUE, &tick_time);
            }
#endif
            MCC_DCACHE_INVALIDATE_MLINES((void*)list, sizeof(MCC_RECEIVE_LIST*));
        }
    }

    /* Clear event bit specified for the particular endpoint in the lwevent_buffer_queued lwevent group */
    _lwevent_clear(&lwevent_buffer_queued[lwevent_index], 1<<lwevent_group_index);

    if(list->head == (MCC_RECEIVE_BUFFER*)0) {
        /* Buffer not dequeued before the timeout */
        return MCC_ERR_TIMEOUT;
	}

    /* Get the message pointer from the head of the receive buffer list */
    MCC_DCACHE_INVALIDATE_MLINES((void*)&list->head->data, list->head->data_len);
    *buffer_p = (void*)&list->head->data;
    MCC_DCACHE_INVALIDATE_MLINES((void*)&list->head->data_len, sizeof(MCC_MEM_SIZE));
    *recv_size = (MCC_MEM_SIZE)(list->head->data_len);

    /* Semaphore-protected section start */
    return_value = mcc_get_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    /* Dequeue the buffer from the endpoint list */
    mcc_dequeue_buffer(list);

    /* Semaphore-protected section end */
    return_value = mcc_release_semaphore();
    if(return_value != MCC_SUCCESS)
        return return_value;

    return return_value;
}
Example #21
0
uint_32 MACNET_send
   (
      ENET_CONTEXT_STRUCT_PTR  enet_ptr,
         /* [IN] the Ethernet state structure */
      PCB_PTR              packet,
         /* [IN] the packet to send */
      uint_32              size,
         /* [IN] total size of the packet */
      uint_32              frags,
         /* [IN] total fragments in the packet */
      uint_32              flags
         /* [IN] optional flags, zero = default */
   )
{ 
   MACNET_CONTEXT_STRUCT_PTR   macnet_context_ptr = (MACNET_CONTEXT_STRUCT_PTR) enet_ptr->MAC_CONTEXT_PTR;
   ENET_MemMapPtr              macnet_ptr= macnet_context_ptr->MACNET_ADDRESS;
   PCB_FRAGMENT_PTR            frag_ptr;
   VENET_BD_STRUCT_PTR         tx_bd_ptr;
   uint_32                     len,totlen,frag;
   uchar_ptr                   txmem;
   boolean                     aligned;
   uint_32                     err = ENET_OK;
#if ENETCFG_SUPPORT_PTP
   MACNET_PTP_DATA             tmp_tx_time;
   boolean                     wait_for_ts=FALSE;
#endif

   if (macnet_ptr == NULL) 
      return ENETERR_INVALID_DEVICE;
   
   MACNET_int_disable();
   
   /*
   ** Make sure there aren't too many fragments.  (We really should check
   ** this every time through the previous loop, but it is extremely
   ** unlikely that the fragment counter overflowed -- there would have
   ** to be over 2^32 fragments.)
   */
   if (macnet_context_ptr->AvailableTxBDs < 1) {
      ENET_INC_STATS(COMMON.ST_TX_MISSED);
   
      err = ENETERR_SEND_FULL;      
      goto END;
   } 

   #if BSPCFG_ENABLE_ENET_HISTOGRAM
   {
      uint_32 index = size>> ENET_HISTOGRAM_SHIFT;
      
      if (index < ENET_HISTOGRAM_ENTRIES) {
         ENET_INC_STATS(TX_HISTOGRAM[index]);
      }
   }
   #endif
   
   aligned = TRUE;
   for (frag_ptr = packet->FRAG; frag_ptr->LENGTH; frag_ptr++) {
      if (MACNET_TX_ALIGN((uint_32)frag_ptr->FRAGMENT)!= (uint_32)frag_ptr->FRAGMENT)
         aligned = FALSE;
   } 
   if (aligned) {
      ENET_INC_STATS(TX_ALL_ALIGNED);
   }
   
   /*
   ** Enqueue the packet on the transmit ring.  Don't set the ready
   ** bit in the first descriptor until all descriptors are enqueued.
   */
   tx_bd_ptr = &macnet_context_ptr->MACNET_TX_RING_PTR[macnet_context_ptr->NextTxBD];

   frag_ptr = packet->FRAG;
   frag = (uint_32) frag_ptr->FRAGMENT;
   if (frags > 1 || (MACNET_TX_ALIGN(frag)!= frag)) {
      // Packet is fragmented and/or it is misaligned, needs to be copied
      txmem = NULL;
      // See if it fits in a small buffer
      if (size <= MACNET_SMALL_PACKET_SIZE) {
         // it does
         txmem = ENET_Dequeue_Buffer((pointer *) &macnet_context_ptr->SMALL_BUFFERS);
      }
      // If it didn't fit, or the small alloc failed, try for a large buffer
      if (txmem) {
         // signal buffer is to be deallocated.
         macnet_context_ptr->FREE_TX_SMALL |= (1<<macnet_context_ptr->NextTxBD);
         ENET_INC_STATS(ST_TX_COPY_SMALL);

      } else { 
         if (size <=  macnet_context_ptr->AlignedTxBufferSize) {

            txmem = ENET_Dequeue_Buffer((pointer *) &macnet_context_ptr->TX_BUFFERS);
         }
         if (txmem) {
            // signal buffer is to be deallocated.
            macnet_context_ptr->FREE_TX |= (1<<macnet_context_ptr->NextTxBD);
         } else {
            ENET_INC_STATS(COMMON.ST_TX_MISSED);
            
            err = ENETERR_NO_TX_BUFFER;      
            goto END;
         }
         
      }
      totlen = 0;
      
      for (len = frag_ptr->LENGTH; len != 0; len = frag_ptr->LENGTH) {
         _mem_copy(frag_ptr->FRAGMENT, txmem + totlen, len);
         totlen += len;
         frag_ptr++;
      } 

   } else {
      // Packet is not fragmented and it is not misaligned
      totlen = frag_ptr->LENGTH;
      txmem  = frag_ptr->FRAGMENT;
      ENET_INC_STATS(TX_ALIGNED);
   } 

   // Flush the buffer from cache
   _DCACHE_FLUSH_MBYTES(txmem, totlen);  

   // Invalidate the bd from cache
   _DCACHE_INVALIDATE_MBYTES((pointer)tx_bd_ptr, sizeof(ENET_BD_STRUCT));  

   // set up the tx bd
   tx_bd_ptr->CONTROL &= HOST_TO_BE_SHORT_CONST(ENET_BD_ETHER_TX_WRAP);
   tx_bd_ptr->BUFFER = (uchar_ptr)HOST_TO_BE_LONG((uint_32)txmem);
   tx_bd_ptr->LENGTH = HOST_TO_BE_SHORT(totlen);
   tx_bd_ptr->CONTROL |= HOST_TO_BE_SHORT_CONST(ENET_BD_ETHER_TX_LAST | ENET_BD_ETHER_TX_SEND_CRC | ENET_BD_ETHER_TX_READY);
   
   tx_bd_ptr->CONTROL_EXT0 |= HOST_TO_BE_SHORT_CONST(ENET_BD_EXT0_ETHER_TX_GENERATE_INTR);
     
   
#if ENETCFG_SUPPORT_PTP
   if (macnet_context_ptr->PTP_PRIV->PTIMER_PRESENT) 
   {
       /* PTP over Ethernet frames: Check the PTPv2 over Ethernet type (identifier) */
       if((totlen > 44) && 
          (*(uint_16 *)(txmem + MACNET_PTP_ETHER_PKT_TYPE_OFFS) == HOST_TO_BE_SHORT_CONST(MACNET_PACKET_TYPE_IEEE_802_3)))
       {
           /* Allow interrupt and timestamp generation */
           tx_bd_ptr->CONTROL_EXT0 |= HOST_TO_BE_SHORT_CONST(ENET_BD_EXT0_ETHER_TX_TIMESTAMP);
           tmp_tx_time.KEY = HOST_TO_BE_SHORT(*((uint_16 *)(txmem + MACNET_PTP_ETHER_SEQ_ID_OFFS)));
           for(len=0;len<MACNET_PTP_CLOCKID_SIZE;len++)
               tmp_tx_time.CLOCKID[len] = *((uint_8 *)(txmem + MACNET_PTP_ETHER_CLOCKID + len));
           wait_for_ts = TRUE;
       }
       /* PTP over UDP: Check if port is 319 for PTP Event, and check for UDP */
       else if((totlen > 44) && 
          (*(uchar_ptr)(txmem + MACNET_PTP_UDP_PKT_TYPE_OFFS) == MACNET_PACKET_TYPE_UDP) && 
          (*(uint_16 *)(txmem + MACNET_PTP_UDP_PORT_OFFS) == HOST_TO_BE_SHORT_CONST(MACNET_PTP_EVNT_PORT)))
       {
           tx_bd_ptr->CONTROL_EXT0 |= HOST_TO_BE_SHORT_CONST(ENET_BD_EXT0_ETHER_TX_TIMESTAMP);
           tmp_tx_time.KEY = HOST_TO_BE_SHORT(*((uint_16 *)(txmem + MACNET_PTP_UDP_SEQ_ID_OFFS)));
           for(len=0;len<MACNET_PTP_CLOCKID_SIZE;len++)
               tmp_tx_time.CLOCKID[len] = *((uint_8 *)(txmem + MACNET_PTP_UDP_CLOCKID + len));
           wait_for_ts = TRUE;
       }

   }
#endif /* ENETCFG_SUPPORT_PTP */

   // Flush the tx bd from cache
   _DCACHE_FLUSH_MBYTES((pointer)tx_bd_ptr, sizeof(ENET_BD_STRUCT));  

   macnet_context_ptr->TxPCBS_PTR[macnet_context_ptr->NextTxBD] = packet;
   
   macnet_context_ptr->AvailableTxBDs--;
   BD_INC(macnet_context_ptr->NextTxBD,macnet_context_ptr->NumTxBDs);

   macnet_ptr->TDAR = ENET_TDAR_TDAR_MASK;
   
END:
   MACNET_int_enable();
      
#if ENETCFG_SUPPORT_PTP
   if(wait_for_ts)
   {
      /* Wait for the interrupt */
      _lwevent_wait_ticks(&macnet_context_ptr->PTP_PRIV->LWEVENT_PTP, MACNET_PTP_LWEVENT_TX_TS_INTR, FALSE, (uint_32)NULL);

      /* Clear the event */
      _lwevent_clear(&macnet_context_ptr->PTP_PRIV->LWEVENT_PTP, MACNET_PTP_LWEVENT_TX_TS_INTR);

      /* Clear the TS flag from the BD */
      tx_bd_ptr->CONTROL_EXT0 &= HOST_TO_BE_SHORT_CONST(~ENET_BD_EXT0_ETHER_TX_TIMESTAMP);
      
      tmp_tx_time.TS_TIME.NSEC = macnet_context_ptr->PTP_PRIV->TXSTAMP.NSEC;
      tmp_tx_time.TS_TIME.SEC  = macnet_context_ptr->PTP_PRIV->TXSTAMP.SEC;
      MACNET_ptp_insert(&(macnet_context_ptr->PTP_PRIV->TX_TIME), &tmp_tx_time);
      wait_for_ts = FALSE;
   }
#endif /* ENETCFG_SUPPORT_PTP */
   return err;
}
Example #22
0
void main_task
(
        uint_32 initial_data
)
{
    DATE_STRUCT     time_rtc;
    TIME_STRUCT     time_mqx;

    if (_lwevent_create(&lwevent,0) != MQX_OK)
    {
        printf("\nMake event failed");
        _task_block();
    }

    printf ("\fStart time (MQX synchronized to RTC time during bsp init):\n\n");


    /* initialize time */
    time_rtc.YEAR     = 2010;
    time_rtc.MONTH    = 10;
    time_rtc.DAY      = 15;
    time_rtc.HOUR     = 10;
    time_rtc.MINUTE   = 8;
    time_rtc.SECOND   = 0;
    time_rtc.MILLISEC = 0;

    _time_from_date (&time_rtc, &time_mqx);

    _time_set( &time_mqx);
    if( _rtc_sync_with_mqx(FALSE) != MQX_OK )
    {
        printf("\nError synchronize time!\n");
        _task_block();
    }
    _time_get (&time_mqx);

    _time_to_date (&time_mqx, &time_rtc);
    print_mqx_time(&time_rtc, &time_mqx);
    print_current_time();

    /* except MPC5125 */
#ifndef BSP_TWRMPC5125
    install_interrupt();

    /* enable stopwatch */
    install_stopwatch();

    /* enable alarm */
    install_alarm();

    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);

    printf ("\nALARM!\n");
    print_current_time();
    /* end of alarm */

    printf ("Continue wasting time (2 minutes max) ...\n");
    _lwevent_wait_ticks(&lwevent,LWE_STOPWATCH,FALSE,0);
    _lwevent_clear(&lwevent,LWE_STOPWATCH);

    printf ("\nSTOPWATCH!\n");
    print_current_time();

    printf ("\nClearing RTC:\n");
    _rtc_init (RTC_INIT_FLAG_CLEAR | RTC_INIT_FLAG_ENABLE);

    print_current_time();

    install_alarm();
    _lwevent_wait_ticks(&lwevent,LWE_ALARM,FALSE,0);
    _lwevent_clear(&lwevent,LWE_ALARM);

    printf ("ALARM!\n");
    print_current_time();

#else /* BSP_TWRMPC5125 */
    printf ("Waste 10 seconds here\n");
    _time_delay(10000);
    _rtc_get_time_mqxd (&time_rtc);
    print_rtc_time(&time_rtc, &time_mqx);
#endif

    printf ("Synchronize RTC to MQX time again:\n");
    _rtc_sync_with_mqx (FALSE);
    _rtc_get_time_mqxd (&time_rtc);
    _time_from_date (&time_rtc, &time_mqx);
    print_rtc_time(&time_rtc, &time_mqx);

#if PSP_HAS_IRTC == 1
    irtc_test();
#endif /* PSP_HAS_IRTC == 1 */

    /* Test tamper event functionality on MCF51EMxx device */
#if PSP_MQX_CPU_IS_MCF51EM
    test_tamper();
#else
    printf ("Finish, press/hold reset to repeat.\n");
    _task_block() ;
#endif
}
Example #23
0
/*TASK*-----------------------------------------------------------------
*
* Function Name  : Sdcard_task
* Returned Value : void
* Comments       :
*
*END------------------------------------------------------------------*/
void Sdcard_task
(
    uint_32 temp
)
{
    boolean      inserted = TRUE, last = FALSE;

    _mqx_int     error_code;

    MQX_FILE_PTR com_handle;

//#if defined BSP_SDCARD_GPIO_DETECT
//    LWGPIO_STRUCT      sd_detect;
//#endif
#if defined BSP_SDCARD_GPIO_PROTECT
    LWGPIO_STRUCT      sd_protect;
#endif

#ifdef BSP_SDCARD_GPIO_CS

    LWGPIO_STRUCT          sd_cs;
    SPI_CS_CALLBACK_STRUCT callback;

#endif
    _task_id player_task_id, sd_walker_id;

    _mqx_int        sd_event_value;
    _mqx_uint       wait_state;

#ifdef USB_ACCESSORY_PLAY
    connect_msg_t msg;
    int delaySetp = 0;
#endif

    if (MQX_OK !=_lwevent_create(&(sddetect_event), LWEVENT_AUTO_CLEAR)) {
        printf("\n_lwevent_create sddetect_event failed\n");
        _task_block();
    }

    /* Open low level communication device */
    com_handle = fopen (SDCARD_COM_CHANNEL, NULL);

    if (NULL == com_handle)
    {
        printf("Error installing communication handle.\n");
        _task_block();
    }

#ifdef BSP_SDCARD_GPIO_CS

    /* Open GPIO file for SPI CS signal emulation */
    error_code = lwgpio_init(&sd_cs, BSP_SDCARD_GPIO_CS, LWGPIO_DIR_OUTPUT, LWGPIO_VALUE_NOCHANGE);
    if (!error_code)
    {
        printf("Initializing GPIO with associated pins failed.\n");
        _task_block();
    }
    lwgpio_set_functionality(&sd_cs,BSP_SDCARD_CS_MUX_GPIO);
    lwgpio_set_attribute(&sd_cs, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
    /* Set CS callback */
    callback.MASK = BSP_SDCARD_SPI_CS;
    callback.CALLBACK = set_CS;
    callback.USERDATA = &sd_cs;
    if (SPI_OK != ioctl (com_handle, IO_IOCTL_SPI_SET_CS_CALLBACK, &callback))
    {
        printf ("Setting CS callback failed.\n");
        _task_block();
    }

#endif


#if defined BSP_SDCARD_GPIO_DETECT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_detect, BSP_SDCARD_GPIO_DETECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
    if (!error_code)
    {
        printf("Initializing GPIO with sdcard detect pin failed.\n");
        _task_block();
    }
    /*Set detect and protect pins as GPIO Function */
    lwgpio_set_functionality(&sd_detect,BSP_SDCARD_DETECT_MUX_GPIO);
    lwgpio_set_attribute(&sd_detect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);

#ifndef SD_DETECT_POLLING // init sd detcet pin interrupt
    lwgpio_int_init(&sd_detect,LWGPIO_INT_MODE_RISING | LWGPIO_INT_MODE_FALLING /* LWGPIO_INT_MODE_HIGH*/);     /* falling,raising mode = 3 */

    /* install gpio interrupt service routine */
    _int_install_isr(lwgpio_int_get_vector(&sd_detect), EXT_SDDETECT_ISR, (void *) &sd_detect);
    _bsp_int_init(lwgpio_int_get_vector(&sd_detect), 5, 0, TRUE);

    lwgpio_int_enable(&sd_detect, TRUE);
#endif

#endif

#if defined BSP_SDCARD_GPIO_PROTECT
    /* Init GPIO pins for other SD card signals */
    error_code = lwgpio_init(&sd_protect, BSP_SDCARD_GPIO_PROTECT, LWGPIO_DIR_INPUT, LWGPIO_VALUE_NOCHANGE);
    if (!error_code)
    {
        printf("Initializing GPIO with sdcard protect pin failed.\n");
        _task_block();
    }
    /*Set detect and protect pins as GPIO Function */
    lwgpio_set_functionality(&sd_protect,BSP_SDCARD_PROTECT_MUX_GPIO);
    lwgpio_set_attribute(&sd_protect, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);
#endif

    /* Install SD card device */
    error_code = _io_sdcard_install("sdcard:", (pointer)&_bsp_sdcard0_init, com_handle);
    if ( error_code != MQX_OK )
    {
        printf("Error installing SD card device (0x%x)\n", error_code);
        _task_block();
    }

    _lwevent_set(&sddetect_event,SD_ATTACHED_EVENT); // set attached event at mode manager

    _time_delay(1000);   /* wait otg main task ready */
    printf("start sd card task\n");

    // use sd detect interrupt
    for (;;) {
#ifdef SD_DETECT_POLLING
        wait_state = _lwevent_wait_ticks(&sddetect_event,SD_EVENT_MASK, FALSE, 4/* 0*/);
#else
        wait_state = _lwevent_wait_ticks(&sddetect_event,SD_EVENT_MASK, FALSE,   0);
#endif

        //if (wait_state == LWEVENT_WAIT_TIMEOUT/* MQX_OK*/) {
        if (wait_state !=  MQX_OK ) {
#ifndef SD_DETECT_POLLING
            printf("waiting sddetect_event fail\n");
            // _task_block(); // _lwevent_destroy(&sddetect_event);
            //-goto wait_timeout;
            continue;
#else
            _lwevent_set(&sddetect_event,SD_ATTACHED_EVENT);
#endif
        }
        //else

        sd_event_value = _lwevent_get_signalled();

        if (sd_event_value == SD_ATTACHED_EVENT ) {
            _time_delay (200);
            inserted = !lwgpio_get_value(&sd_detect);
            if(!inserted)   // mount sd fs ,must attached sd card !
                continue;

            // printf("mount sd card...\n");
            // mount_sdcard();

#ifndef USB_ACCESSORY_PLAY
            /* create player and sd_walker task*/
            player_task_id = _task_create(0, PLAYER_TASK, 0);
            printf("Creating sd player task................");
            if (player_task_id == MQX_NULL_TASK_ID) {
                printf("[FAIL]\n");
            }
            else {
                printf("[OK]\n");
            }

            sd_walker_id = _task_create(0, SD_WALKER_TASK, 0);
            printf("Creating sd walker task................");
            if (sd_walker_id == MQX_NULL_TASK_ID) {
                printf("[FAIL]\n");
            }
            else {
                printf("[OK]\n");
            }
#else
            msg.conct_source = mp_for_TF;
            msg.conct_action = mp_plugIn;     /* post message,  TFcard plug in*/
            if (LWMSGQ_FULL == _lwmsgq_send(connect_taskq, (uint_32 *) &msg, 0)) {
                printf("Could not inform  about TFCard device attached\n");
            }
            //_time_delay (1); // give mode manager task some times to cancel play ,if sd task high than mode task

#endif
            // _lwevent_set(&player_event, PLAYER_EVENT_MSK_SD_FS_MOUNTED);     //auto play event
            last = inserted;

        } // SD_ATTACHED_EVENT
        else if (sd_event_value == SD_DETTACHED_EVENT ) {
            // _time_delay (100);
            //inserted = !lwgpio_get_value(&sd_detect);
            //if(inserted)
            //    continue;


#ifndef USB_ACCESSORY_PLAY
            _lwevent_set(&player_event, PLAYER_EVENT_MSK_SD_FS_UNMOUNTED);
            _lwevent_wait_ticks(&player_event,
                                PLAYER_EVENT_MSK_PLAYER_TASK_KILLED,
                                TRUE, 0);
            _lwevent_clear(&player_event, PLAYER_EVENT_MSK_PLAYER_TASK_KILLED);
            /* And the destroy play_task and sd_walker task */
            _task_destroy(sd_walker_id);
            _task_destroy(player_task_id);
#else
            /* post message,  TFcard plug out*/
            msg.conct_source = mp_for_TF;
            msg.conct_action = mp_plugOut;     /* post message,  TFcard plug out*/
            if (LWMSGQ_FULL == _lwmsgq_send(connect_taskq, (uint_32 *) &msg, 0))  {
                printf("Could not inform  about TFCard device de-attached\n");
            }
            //_time_delay (1); // give mode manager task some times to cancel play ,if sd task high than mode task

#endif
            // printf("unmount sd card...\n");
            // unmount_sdcard();
            // printf ("SD card uninstalled.\n");
        }

    }

}
Example #24
0
/*FUNCTION*----------------------------------------------------------------
*
* Function Name  : Main_Task
* Returned Value : None
* Comments       :
*     First function called.  This function is the entry for
*     the PHDC Application
*
*END*--------------------------------------------------------------------*/
void Main_Task(uint_32 param)
{
    /* Initialize Global Variable Structure */
    PHDC_CONFIG_STRUCT phdc_config;
    phdc_config.phdc_callback.callback =  USB_App_Callback;
    phdc_config.phdc_callback.arg = (void*)&g_bridge.handle;
    phdc_config.vendor_callback.callback = NULL;
    phdc_config.vendor_callback.arg = NULL;
    phdc_config.desc_callback_ptr = &desc_callback;
    phdc_config.info = &usb_desc_ep;

    USB_mem_zero(&g_bridge, sizeof(BRIDGE_GLOBAL_VARIABLE_STRUCT));

    if (_lwevent_create(&lwevent,0) != MQX_OK)
    {
#if _DEBUG
        printf("\nMake event failed : Main_Task");
#endif
        _task_block();
    }

    g_usb_rx_buff_ptr = USB_mem_alloc_zero(PHDC_BULK_OUT_EP_SIZE);
    if(g_usb_rx_buff_ptr == NULL)
    {
#if _DEBUG
        printf("g_usb_rx_buff_ptr malloc failed\n");
#endif
    }

    g_bridge_rx_buff_ptr = USB_mem_alloc_zero(PHDC_BULK_IN_EP_SIZE);
    if(g_bridge_rx_buff_ptr == NULL)
    {
#if _DEBUG
        printf("g_bridge_rx_buff_ptr  malloc failed\n");
#endif
    }

    _int_disable();
    g_bridge.handle = USB_Class_PHDC_Init(&phdc_config);
    Bridge_Interface_Init(Bridge_Callback);
    _int_enable();

    while(TRUE)
    {
        /* Block the task untill USB Enumeration is completed */
        if(_lwevent_wait_for(&lwevent,USB_ENUM_COMPLETED,FALSE,NULL) !=
                MQX_OK)
        {
#if _DEBUG
            printf("USB_ENUM_COMPLETEDEvent Wait failed\n");
#endif
            _task_block();
        }

        if(_lwevent_clear(&lwevent,USB_ENUM_COMPLETED) != MQX_OK)
        {
#if _DEBUG
            printf("Enum Event Clear failed\n");
#endif
            _task_block();
        }

        Bridge_Interface_Open(param);
    }
}
Example #25
0
void usb_host_cdc_data_event
   (
      /* [IN] pointer to device instance */
      _usb_device_instance_handle      dev_handle,

      /* [IN] pointer to interface descriptor */
      _usb_interface_descriptor_handle intf_handle,

      /* [IN] code number for event causing callback */
      uint_32                          event_code
   )
{ /* Body */
   INTERFACE_DESCRIPTOR_PTR   intf_ptr =
      (INTERFACE_DESCRIPTOR_PTR)intf_handle;

   fflush(stdout);
   switch (event_code) {
      case USB_CONFIG_EVENT:
         /* Drop through into attach, same processing */
      case USB_ATTACH_EVENT: {
         /* This data interface could be controlled by some control interface,
          * which could be already initialized (or not). We have to find 
          * that interface. Then we need to bind this interface with
          * found control interface. */
         INTERFACE_DESCRIPTOR_PTR   if_desc;
         
         if (USB_OK != usb_class_cdc_get_ctrl_descriptor(dev_handle,
            intf_handle,
            &if_desc))
            break;

         /* initializes interface members and selects it */
         if (USB_OK != _usb_hostdev_select_interface(dev_handle,
            intf_handle, (pointer)&data_device.CLASS_INTF))
         {
            break;
         }
         /* binds this data interface with its control interface, if possible */
         if (USB_OK != usb_class_cdc_bind_acm_interface((pointer)&data_device.CLASS_INTF,
            if_desc))
         {
            break;
         }
         
         printf("----- CDC data interface attach event -----\n");
         fflush(stdout);
         printf("State = attached");
         printf("  Class = %d", intf_ptr->bInterfaceClass);
         printf("  SubClass = %d", intf_ptr->bInterfaceSubClass);
         printf("  Protocol = %d\n", intf_ptr->bInterfaceProtocol);
         fflush(stdout);

         break;
      }   
      case USB_INTF_EVENT: 
      {
         CLASS_CALL_STRUCT_PTR data_parser;
         
         fflush(stdout);
         
         if (NULL == (data_parser = usb_class_cdc_get_data_interface(intf_handle)))
             break;
         if (MQX_OK != usb_class_cdc_data_use_lwevent(data_parser, &data_device.data_event))
             break;
         if (USB_OK == usb_class_cdc_install_driver(data_parser, device_name)) 
         {
             if (((USB_DATA_CLASS_INTF_STRUCT_PTR) (data_parser->class_intf_handle))->BOUND_CONTROL_INTERFACE != NULL) {
                 if (reg_device == 0) {
                     reg_device = dev_handle;
                     _lwevent_set(device_registered, 0x01);
                 }
             }
             printf("----- Device installed -----\n");
         }
         printf("----- CDC data interface selected -----\n");

         break;
      }
         
      case USB_DETACH_EVENT: 
      {
         CLASS_CALL_STRUCT_PTR data_parser;
         
         if (NULL == (data_parser = usb_class_cdc_get_data_interface(intf_handle)))
             break;

         /* Allow tasks waiting for data to be finished...
         ** This does have sense only if this task will not be active
         ** or scheduler switches to another task.
         ** For simplification, we dont use any semaphore to indicate that
         ** all tasks have finished its job with device. Instead, we have just
         ** informed them that device is detached and we rely on USB stack layer
         ** that it checking if the device is available returns false.
         ** The code that would synchronize tasks to be finished would look like:
         **
         **  _lwsem_wait(if_ptr->device_using_tasks);
         */

         /* unbind data interface */
         if (USB_OK != usb_class_cdc_unbind_acm_interface(data_parser))
             break;
         if (USB_OK != usb_class_cdc_uninstall_driver(data_parser))
             break;
         
         if (reg_device == dev_handle) {
             reg_device = 0;
             _lwevent_clear(device_registered, 0x01);
         }

         printf("----- CDC data interface detach Event -----\n");
         fflush(stdout);
         printf("State = detached");
         printf("  Class = %d", intf_ptr->bInterfaceClass);
         printf("  SubClass = %d", intf_ptr->bInterfaceSubClass);
         printf("  Protocol = %d\n", intf_ptr->bInterfaceProtocol);
         fflush(stdout);

         break;
      }

      default:
         printf("CDC device: unknown data event\n");
         fflush(stdout);
         break;
   } /* EndSwitch */
} /* Endbody */
Example #26
0
void main_task
    (
        uint_32 initial_data
    )
{
    LPM_OPERATION_MODE power_mode;

    /* Initialize switches */
    button_led_init();

    /* Install interrupt for RTC alarm */
    install_rtc_interrupt();

    /* Create global event */
    if (_lwevent_create(&app_event, 0) != MQX_OK)
    {
        printf("\nCreating app_event failed.\n");
        _task_block();
    }

    printf("\nMQX Low Power Modes Demo\n");

    while (1)
    {
        /* Find out current mode setting */
        power_mode = _lpm_get_operation_mode();

        printf("\n******************************************************************************\n");
        printf("**************** Current Mode : %s ***********************\n", predefined_power_modes_names[power_mode]);
        printf("******************************************************************************\n");

        display_operation_mode_setting(power_mode);
        
        /* Wait for button press */
        printf ("Press button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        power_mode = LPM_OPERATION_MODE_WAIT;
		
        printf("\n******************************************************************************\n");
        printf("**************** Current Mode : %s **********************\n", predefined_power_modes_names[power_mode]);
        printf("******************************************************************************\n");

        display_operation_mode_setting(power_mode);

        printf(
        "Info: WAIT mode is mapped on Kinets VLPR mode by default.\n"
        "      It requires 2 MHz clock and bypassed pll.\n"
        "      Core continues the execution after entering the mode.\n");

        /* The LPM_OPERATION_MODE_WAIT is mapped on  LPM_CPU_POWER_MODE_KINETIS_VLPR by default,
        this mode requires 2 MHz, bypassed PLL clock setting. Change clocks to appropriate mode */
        printf("\nChanging frequency to 2 MHz.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_2MHZ))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }
        
        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", predefined_power_modes_names[power_mode]);
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_WAIT) == 0 ? "OK" : "ERROR");

        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed.\n");

        /* Return to RUN mode */
        printf ("\nSetting operation mode back to %s ... ", predefined_power_modes_names[LPM_OPERATION_MODE_RUN]);
        printf ("%s\n", _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN) == 0 ? "OK" : "ERROR");

        /* Return default clock configuration */
        printf("\nChanging frequency back to the default one.\n");
        if (CM_ERR_OK != _lpm_set_clock_configuration(BSP_CLOCK_CONFIGURATION_DEFAULT))
        {
            printf("Cannot change clock configuration");
            _task_block();
        }

        printf("\nMoving to next operation mode.\n");

        power_mode = LPM_OPERATION_MODE_SLEEP;

        printf("\n******************************************************************************\n");
        printf("**************** Current Mode : %s *********************\n", predefined_power_modes_names[power_mode]);
        printf("******************************************************************************\n");

        display_operation_mode_setting(power_mode);

        printf(
        "Info: SLEEP mode is mapped on Kinetis WAIT mode by default. Core is inactive\n"
        "      in this mode, reacting only to interrupts.\n"
        "      The LPM_CPU_POWER_MODE_FLAG_SLEEP_ON_EXIT is set, therefore core goes\n"
        "      to sleep again after any isr finishes. The core will stay awake after\n"
        "      call to _lpm_wakeup_core() from RTC or serial line interrupt.\n");

        /* Wake up in 10 seconds */
        set_rtc_alarm(10);

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... ", predefined_power_modes_names[power_mode]);
        printf ("%s\n", _lpm_set_operation_mode (power_mode) == 0 ? "OK" : "ERROR");
        
        if (LWEVENT_WAIT_TIMEOUT == _lwevent_wait_ticks (&app_event, RTC_EVENT_MASK, FALSE, 1))
        {
            printf("\nCore woke up by serial interrupt. Waiting for RTC alarm ... ");
            _lwevent_wait_ticks (&app_event, RTC_EVENT_MASK, FALSE, 0);
            printf("OK\n");
        }
        else
        {
            printf("\nCore woke up by RTC interrupt.\n");
        }
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        
        /* Wait for button press */
        printf ("\nPress button to move to next operation mode.\n");
        _lwevent_wait_ticks (&app_event, SW_EVENT_MASK, FALSE, 0);
        _lwevent_clear (&app_event, ALL_EVENTS_MASK);
        printf("\nButton pressed. Moving to next operation mode.\n");

        power_mode = LPM_OPERATION_MODE_STOP;

        printf("\n******************************************************************************\n");
        printf("**************** Current Mode : %s **********************\n", predefined_power_modes_names[power_mode]);
        printf("******************************************************************************\n");

        display_operation_mode_setting(power_mode);

        printf(
        "Info: STOP mode is mapped to Kinets LLS mode by default.\n"
        "      Core and most peripherals are inactive in this mode, reacting only to\n"
        "      specified wake up events. The events can be changed in BSP (init_lpm.c).\n"
        "      Serial line is turned off in this mode. The core will wake up from\n"
        "      RTC interrupt.\n");

        /* Wake up in 10 seconds */
        set_rtc_alarm(10);

        /* Change the operation mode */
        printf ("\nSetting operation mode to %s ... \n", predefined_power_modes_names[power_mode]);
        _lpm_set_operation_mode (power_mode);

        /**************************************************************************************************/
        /* SCI HW MODULE IS DISABLED AT THIS POINT - SERIAL DRIVER MUST NOT BE USED UNTIL MODE IS CHANGED */
        /**************************************************************************************************/
        
        /* Return to RUN mode */
        _lpm_set_operation_mode (LPM_OPERATION_MODE_RUN);
        
        printf("\nCore is awake. Moved to next operation mode.\n");
    }
}