Ejemplo n.º 1
0
void APP_Tasks ( void )
{
    /* Check the application's current state. */
    switch ( appData.state )
    {
        /* Application's initial state. */
        case APP_STATE_INIT:
        {
            break;
        }

        /* TODO: implement your application state machine.*/
        //MESSAGE SEND TEST
        xQueueSendToFront(msgq, msg, 10);
        
        xQueueReceive(msgq, receive, 10);
        

        /* The default state should never be executed. */
        default:
        {
            /* TODO: Handle error in application's state machine. */
            break;
        }
    }
}
Ejemplo n.º 2
0
/******************************************************************************
 * Function: RtlMailboxSendToFront
 * Desc: To put a message block to the head of a mailbox.
 * Para:
 *  MboxID: The identifier of the target mailbox.
 *  pMsg: The pointer of the message block to be put into the mailbox.
 *  MSToWait: If the mailbox is full, this value gives a time to wait to put 
 *            this message. The time unit is millisecond. 
 *            The special values are: 
 *               0: no waiting; 
 *               0xffffffff: wait without timeout. 
 *            If the waiting is timeout, the message sending is failed and 
 *            return _FAIL.
 *  IsFromISR: Is this function is called from an ISR ?
 * Return: _SUCCESS or _FAIL.
 ******************************************************************************/
u8 RtlMailboxSendToFront(
    IN u8 MboxID, 
    IN MSG_BLK *pMsg, 
    IN u32 MSToWait, 
    IN u8 IsFromISR
)
{
    RTL_MAILBOX *pMbox=NULL;
    u32 wait_ticks;
#ifdef PLATFORM_FREERTOS
    portBASE_TYPE ret;
#endif

    pMbox = RtlMBoxIdToHdl(MboxID);

    if (NULL == pMbox) {
   	    MSG_MBOX_ERR("RtlMailboxSendToBack: Didn't find matched MBoxID=%d\n", MboxID);
        return _FAIL;
    }

#ifdef PLATFORM_FREERTOS
    if (MBOX_WAIT_NO_TIMEOUT == MSToWait) {
        wait_ticks = portMAX_DELAY;
    }
    else if (MBOX_WAIT_NONE == MSToWait) {
        wait_ticks = 0;
    }
    else {
        wait_ticks = ((MSToWait/portTICK_RATE_MS)>0)?(MSToWait/portTICK_RATE_MS):(1);
    }

    if (IsFromISR) {
        ret = xQueueSendToFrontFromISR(pMbox->mbox_hdl, (void *)pMsg, NULL);//(portTickType) wait_ticks);
    }
    else {
        ret = xQueueSendToFront(pMbox->mbox_hdl, (void *)pMsg, (portTickType) wait_ticks);
    }
    
    if(ret != pdPASS ) {
        // send message to the queue failed
   	    MSG_MBOX_ERR("RtlMailboxSendToBack: Put Msg to Queue Failed, MBoxID=%d\n", MboxID);
        ret = _FAIL;
    }
    else {
        // try to give a semaphore to wake up the receiving task
        if (pMbox->pWakeSema) {
            RtlUpSema(pMbox->pWakeSema);  
        }
        ret = _SUCCESS;
    }

    return ret;
#endif

#ifdef PLATFORM_ECOS
    // TODO: eCos has no API to put message to the head of a mailbox
#endif

}
Ejemplo n.º 3
0
    /* Mutex uses priority inheritance */
    *mutex = xSemaphoreCreateMutex( );
    if ( *mutex == NULL )
    {
        return WICED_ERROR;
    }

    return WICED_SUCCESS;
}

wiced_result_t wiced_rtos_lock_mutex( wiced_mutex_t* mutex )
{
    wiced_assert("Bad args", mutex != NULL);

    if ( xSemaphoreTake( *mutex, WICED_WAIT_FOREVER ) != pdPASS )
    {
        return WICED_ERROR;
    }

    return WICED_SUCCESS;
}


wiced_result_t wiced_rtos_unlock_mutex( wiced_mutex_t* mutex )
{
    wiced_assert("Bad args", mutex != NULL);

    if ( xSemaphoreGive( *mutex ) != pdPASS )
    {
        return WICED_ERROR;
    }

    return WICED_SUCCESS;
}


wiced_result_t wiced_rtos_deinit_mutex( wiced_mutex_t* mutex )
{
    wiced_assert("Bad args", mutex != NULL);

    vSemaphoreDelete( *mutex );
    return WICED_SUCCESS;
}


wiced_result_t wiced_rtos_init_queue( wiced_queue_t* queue, const char* name, uint32_t message_size, uint32_t number_of_messages )
{
    UNUSED_PARAMETER( name );

    return host_rtos_init_queue( WICED_GET_QUEUE_HANDLE( queue ), NULL, number_of_messages * message_size, message_size );
}


#if 0 /* Not yet implemented by other RTOSs */
wiced_result_t wiced_rtos_push_to_queue_front( wiced_queue_t* queue, void* message, uint32_t timeout_ms )
{
    if ( xQueueSendToFront( *queue, message, (portTickType) ( timeout_ms / ms_to_tick_ratio ) ) != pdPASS )
    {
        return WICED_ERROR;
    }

    return WICED_SUCCESS;
}
Ejemplo n.º 4
0
//发送消息到队头
retStatus rootWin::sendMSGtoFront(message* msg,xQueueHandle que)
{	
	if(xQueueSendToFront(que,msg,QUE_WAIT_TIME)!= pdPASS)//等待时间为0
	{
			return GUI_QFULL;
	}
	delete msg;
	return GUI_OK;
}
Ejemplo n.º 5
0
/*!
 * \brief Queues a message to be sent to the radio transceiver.
 *
 * \param buf Pointer to the message data to be sent.
 * \param bufSize Size of buffer.
 * \param payloadSize Size of payload data.
 * \param fromISR If called from an ISR routine.
 * \param isTx If message is TX or RX.
 * \param flags Packet flags.
 *
 * \return Error code, ERR_OK if message has been queued.
 */
static uint8_t QueuePut( uint8_t *buf, size_t bufSize, size_t payloadSize, bool fromISR, bool isTx,
        bool toBack, uint8_t flags )
{
    /* data format is: dataSize(8bit) data */
    uint8_t res = ERR_OK;
    xQueueHandle queue;
    BaseType_t qRes;

    if ( bufSize != LORAPHY_BUFFER_SIZE ) {
        return ERR_OVERFLOW; /* must be exactly this buffer size!!! */
    }

    if ( isTx ) {
        queue = msgTxQueue;
    } else {
        queue = msgRxQueue;
    }

    LORAPHY_BUF_FLAGS(buf) = flags;
    LORAPHY_BUF_SIZE(buf) = (uint8_t) payloadSize;

#if(LORAMESH_DEBUG_OUTPUT_PAYLOAD == 1)
    LOG_TRACE("LoRaPhy %s - Size %d", __FUNCTION__, payloadSize);
    LOG_TRACE_BARE("\t");
    for ( uint8_t i = 0; i < (payloadSize + 2); i++ )
    LOG_TRACE_BARE("0x%02x ", buf[i]);
    LOG_TRACE_BARE("\r\n");
#endif

    if ( fromISR ) {
        signed portBASE_TYPE
        pxHigherPriorityTaskWoken;

        if ( toBack ) {
            qRes = xQueueSendToBackFromISR(queue, buf, &pxHigherPriorityTaskWoken);
        } else {
            qRes = xQueueSendToFrontFromISR(queue, buf, &pxHigherPriorityTaskWoken);
        }
        if ( qRes != pdTRUE ) {
            /* was not able to send to the queue. Well, not much we can do here... */
            res = ERR_BUSY;
        }
    } else {
        if ( toBack ) {
            qRes = xQueueSendToBack(queue, buf, MSG_QUEUE_PUT_WAIT);
        } else {
            qRes = xQueueSendToFront(queue, buf, MSG_QUEUE_PUT_WAIT);
        }
        if ( qRes != pdTRUE ) {
            res = ERR_BUSY;
        }
    }
    return res;
}
Ejemplo n.º 6
0
//set Parameters for driving and fill the driveParameterBuffer for intertask communication
void drive(int8_t speed, int8_t directionPercent, portTickType duration_ms) {
	driveParameters par;

#ifdef NAVIGATION_THREAD
	par.direction = directionPercent;
	par.speed = speed;
	par.duration = duration_ms;
	par.startTime = os_getTime();
	xQueueSendToFront(driveParameterBuffer, &par, (portTickType)10);
//#endif
#else
	Drive_SetServo(directionPercent);
	Drive_SetMotor(speed);
#endif
}
Ejemplo n.º 7
0
/** \brief
*/
extern uint32_t WGT_SendMessage( uint32_t dwMsgID, uint32_t dwParam1, uint32_t dwParam2 )
{
    SWGTCoreMessage sMsg ;

    sMsg.dwID=dwMsgID ;
    sMsg.dwParam1=dwParam1 ;
    sMsg.dwParam2=dwParam2 ;

    // Send message
    if ( xQueueSendToFront( g_WGT_CoreData.hMessagesQueue, &sMsg, ( portTickType )10 ) != pdPASS )
    {
        return SAMGUI_E_MSQUEUE ;
    }

    return SAMGUI_E_OK ;
}
Ejemplo n.º 8
0
/*..........................................................................*/
void QActive_postLIFO(QActive *me, QEvent const *e) {
    portBASE_TYPE err;
    QF_INT_LOCK_KEY_
    QF_INT_LOCK_();
    if (e->dynamic_ != (uint8_t)0) {
        ++((QEvent *)e)->dynamic_;
   	 }
    QF_INT_UNLOCK_();

//  	err = xQueueSendToFront(me->eQueue, &e, (portTickType)0);
#define XXX
#ifdef XXX
	if (ulCriticalNesting == (unsigned portLONG)0) { /* task level? */
			err = xQueueSendToFront(me->eQueue, &e, (portTickType)0);
	}
	else  { /* must be ISR level */
		portBASE_TYPE xHigherPriorityTaskWoken;
		err = xQueueSendToFrontFromISR(me->eQueue, &e,&xHigherPriorityTaskWoken);
	}

#endif
	Q_ASSERT(err == pdPASS);

 }
Ejemplo n.º 9
0
static void prvSendFrontAndBackTest( void *pvParameters )
{
unsigned portLONG ulData, ulData2;
xQueueHandle xQueue;

	#ifdef USE_STDIO
	void vPrintDisplayMessage( const portCHAR * const * ppcMessageToSend );
	
		const portCHAR * const pcTaskStartMsg = "Queue SendToFront/SendToBack/Peek test started.\r\n";

		/* Queue a message for printing to say the task has started. */
		vPrintDisplayMessage( &pcTaskStartMsg );
	#endif

	xQueue = ( xQueueHandle ) pvParameters;

	for( ;; )
	{
		/* The queue is empty, so sending an item to the back of the queue
		should have the same efect as sending it to the front of the queue.

		First send to the front and check everything is as expected. */
		xQueueSendToFront( xQueue, ( void * ) &ulLoopCounter, genqNO_BLOCK );

		if( uxQueueMessagesWaiting( xQueue ) != 1 )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueReceive( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != pdPASS )
		{
			xErrorDetected = pdTRUE;
		}

		/* The data we sent to the queue should equal the data we just received
		from the queue. */
		if( ulLoopCounter != ulData )
		{
			xErrorDetected = pdTRUE;
		}

		/* Then do the same, sending the data to the back, checking everything
		is as expected. */
		if( uxQueueMessagesWaiting( xQueue ) != 0 )
		{
			xErrorDetected = pdTRUE;
		}

		xQueueSendToBack( xQueue, ( void * ) &ulLoopCounter, genqNO_BLOCK );

		if( uxQueueMessagesWaiting( xQueue ) != 1 )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueReceive( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != pdPASS )
		{
			xErrorDetected = pdTRUE;
		}

		if( uxQueueMessagesWaiting( xQueue ) != 0 )
		{
			xErrorDetected = pdTRUE;
		}

		/* The data we sent to the queue should equal the data we just received
		from the queue. */
		if( ulLoopCounter != ulData )
		{
			xErrorDetected = pdTRUE;
		}

		#if configUSE_PREEMPTION == 0
			taskYIELD();
		#endif



		/* Place 2, 3, 4 into the queue, adding items to the back of the queue. */
		for( ulData = 2; ulData < 5; ulData++ )
		{
			xQueueSendToBack( xQueue, ( void * ) &ulData, genqNO_BLOCK );
		}

		/* Now the order in the queue should be 2, 3, 4, with 2 being the first
		thing to be read out.  Now add 1 then 0 to the front of the queue. */
		if( uxQueueMessagesWaiting( xQueue ) != 3 )
		{
			xErrorDetected = pdTRUE;
		}
		ulData = 1;
		xQueueSendToFront( xQueue, ( void * ) &ulData, genqNO_BLOCK );
		ulData = 0;
		xQueueSendToFront( xQueue, ( void * ) &ulData, genqNO_BLOCK );

		/* Now the queue should be full, and when we read the data out we
		should receive 0, 1, 2, 3, 4. */
		if( uxQueueMessagesWaiting( xQueue ) != 5 )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueSendToFront( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != errQUEUE_FULL )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueSendToBack( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != errQUEUE_FULL )
		{
			xErrorDetected = pdTRUE;
		}

		#if configUSE_PREEMPTION == 0
			taskYIELD();
		#endif

		/* Check the data we read out is in the expected order. */
		for( ulData = 0; ulData < genqQUEUE_LENGTH; ulData++ )
		{
			/* Try peeking the data first. */
			if( xQueuePeek( xQueue, &ulData2, genqNO_BLOCK ) != pdPASS )
			{
				xErrorDetected = pdTRUE;
			}

			if( ulData != ulData2 )
			{
				xErrorDetected = pdTRUE;
			}
			

			/* Now try receiving the data for real.  The value should be the
			same.  Clobber the value first so we know we really received it. */
			ulData2 = ~ulData2;
			if( xQueueReceive( xQueue, &ulData2, genqNO_BLOCK ) != pdPASS )
			{
				xErrorDetected = pdTRUE;
			}

			if( ulData != ulData2 )
			{
				xErrorDetected = pdTRUE;
			}
		}

		/* The queue should now be empty again. */
		if( uxQueueMessagesWaiting( xQueue ) != 0 )
		{
			xErrorDetected = pdTRUE;
		}

		#if configUSE_PREEMPTION == 0
			taskYIELD();
		#endif


		/* Our queue is empty once more, add 10, 11 to the back. */
		ulData = 10;
		if( xQueueSend( xQueue, &ulData, genqNO_BLOCK ) != pdPASS )
		{
			xErrorDetected = pdTRUE;
		}
		ulData = 11;
		if( xQueueSend( xQueue, &ulData, genqNO_BLOCK ) != pdPASS )
		{
			xErrorDetected = pdTRUE;
		}

		if( uxQueueMessagesWaiting( xQueue ) != 2 )
		{
			xErrorDetected = pdTRUE;
		}

		/* Now we should have 10, 11 in the queue.  Add 7, 8, 9 to the
		front. */
		for( ulData = 9; ulData >= 7; ulData-- )
		{
			if( xQueueSendToFront( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != pdPASS )
			{
				xErrorDetected = pdTRUE;
			}
		}

		/* Now check that the queue is full, and that receiving data provides
		the expected sequence of 7, 8, 9, 10, 11. */
		if( uxQueueMessagesWaiting( xQueue ) != 5 )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueSendToFront( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != errQUEUE_FULL )
		{
			xErrorDetected = pdTRUE;
		}

		if( xQueueSendToBack( xQueue, ( void * ) &ulData, genqNO_BLOCK ) != errQUEUE_FULL )
		{
			xErrorDetected = pdTRUE;
		}

		#if configUSE_PREEMPTION == 0
			taskYIELD();
		#endif

		/* Check the data we read out is in the expected order. */
		for( ulData = 7; ulData < ( 7 + genqQUEUE_LENGTH ); ulData++ )
		{
			if( xQueueReceive( xQueue, &ulData2, genqNO_BLOCK ) != pdPASS )
			{
				xErrorDetected = pdTRUE;
			}

			if( ulData != ulData2 )
			{
				xErrorDetected = pdTRUE;
			}
		}

		if( uxQueueMessagesWaiting( xQueue ) != 0 )
		{
			xErrorDetected = pdTRUE;
		}

		ulLoopCounter++;
	}
}
Ejemplo n.º 10
0
void APP2_Tasks ( void )
{
/* Update the application state machine based
     * on the current state */

    switch(app2Data.state)
    {
        case APP2_STATE_INIT:

            /* Open the device layer */
            app2Data.deviceHandle = USB_DEVICE_Open( USB_DEVICE_INDEX_0, DRV_IO_INTENT_READWRITE );

            if(app2Data.deviceHandle != USB_DEVICE_HANDLE_INVALID)
            {
                /* Register a callback with device layer to get event notification (for end point 0) */
                USB_DEVICE_EventHandlerSet(app2Data.deviceHandle, APP_USBDeviceEventHandler, 0);

                app2Data.state = APP2_STATE_WAIT_FOR_CONFIGURATION;
            }
            else
            {
                /* The Device Layer is not ready to be opened. We should try
                 * again later. */
            }

            break;

        case APP2_STATE_WAIT_FOR_CONFIGURATION:

            /* Check if the device was configured */
            if(app2Data.isConfigured)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_READ:
            if(APP_StateReset())
            {
                break;
            }
            
            /* If a read is complete, then schedule a read
            * else wait for the current read to complete */
            
            app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            if(app2Data.isReadComplete == true)
            {
                app2Data.isReadComplete = false;
                app2Data.readTransferHandle =  USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
                
                USB_DEVICE_CDC_Read (USB_DEVICE_CDC_INDEX_0,
                        &app2Data.readTransferHandle, app2Data.readBuffer,
                        APP_READ_BUFFER_SIZE);
                
                if(app2Data.readTransferHandle == USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID)
                {
                    app2Data.state = APP2_STATE_ERROR;
                    break;
                }
            }
            break;

        case APP2_STATE_WAIT_FOR_READ_COMPLETE:
            
            if(APP_StateReset())
            {
                break;
            }
            
            if(app2Data.isReadComplete == true)
            {            
                // Check for delimiter
                int res = APP_CheckForMessage(app2Data.readBuffer);
                if(res == MESSAGE_BAD_POINTER)
                {
                    // Do something
                    break;
                }
                else if(res == MESSAGE_NO_DELIMITER)
                {
                    strcat(messageBuffer, app2Data.readBuffer);
                    memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                    app2Data.state = APP2_STATE_SCHEDULE_READ;
                    break;
                }
 
                strcat(messageBuffer, app2Data.readBuffer);
                // Parse for the command being sent so we can handle it
                int command = APP_ParseCommand(messageBuffer);

                // Lets build our response message
                // First initialize the JSON value and object from parson library
                JSON_Value *rootValue = json_value_init_object();
                JSON_Object *rootObject = json_value_get_object(rootValue);
                char *serializedString = NULL;  
                    
                // Build response and handle the command
                switch(command)
                {
                    // If hello command, respond with discovery packet 
                    case COMMAND_HELLO:
                            json_object_dotset_string(rootObject, "message.command", "discovery");
                            json_object_dotset_string(rootObject, "message.discovery_object.title", APP_TITLE);
                            json_object_dotset_string(rootObject, "message.discovery_object.part_number", APP_PART_NUMBER);
                            json_object_dotset_string(rootObject, "message.discovery_object.mac_address", appData.macAddress);
                            json_object_dotset_string(rootObject, "message.discovery_object.firmware_version", APP_FIRMWARE_VERSION);
                            json_object_dotset_string(rootObject, "message.discovery_object.harmony_version", SYS_VERSION_STR);
                            json_object_dotset_boolean(rootObject, "message.discovery_object.is_commissioned", appData.isCommissioned);
                        break;
                        
                    // If configuration command, respond with ACK/NACK 
                    case COMMAND_CONFIGURE:
                    {
                        if(appData.isCommissioned == false)
                        {
                            JSON_Value *messageRoot = json_parse_string(messageBuffer);
                            if(json_value_get_type(messageRoot) != JSONObject)
                            {
                                BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                                break;
                            }
                            else
                            {
                                JSON_Object *messageObject = json_value_get_object(messageRoot);
                                if( json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key") != NULL )
                                {
                                    json_object_dotset_string(rootObject, "message.command", "ack");
                                    json_object_dotset_string(rootObject, "message.ack_nack_message", "Writing commission parameters to flash");
                                    sprintf((char *)appData.host, json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address"));
                                    sprintf((char *)appData.clientCert, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate"));
                                    sprintf((char *)appData.clientKey, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key"));
                                    appData.isCommissioned = true;
                                    appData.writeToNVM = true;
                                }
                                else
                                {
                                    BuildAckNackMessage(rootObject, "nack", "Invalid commission parameters");
                                    break;
                                }
                            } 
                        }
                        else
                        {
                            BuildAckNackMessage(rootObject, "nack", "Already commissioned");
                        }                    
                        break;
                    }
                    
                    case COMMAND_DEBUG_SET:
                    {
                        JSON_Value *messageRoot = json_parse_string(messageBuffer);
                        if(json_value_get_type(messageRoot) != JSONObject)
                        {
                            BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                            break;
                        }
                        JSON_Object *messageObject = json_value_get_object(messageRoot);
                        if(messageObject == NULL)
                        {
                            BuildAckNackMessage(rootObject, "nack", "NULL Pointer");
                            break;
                        }
                        BuildAckNackMessage(rootObject, "ack", "Received debug set");
                        int DebugMessage = DEBUG_UPDATE;
                        xQueueSendToFront(app2Data.debugQueue, &DebugMessage, 1);
                        if(json_object_dotget_boolean(messageObject, "message.debug_set_object.set"))
                            appData.debugSet = true;
                        else
                            appData.debugSet = false;
                        break;
                    }
                    
                    case COMMAND_BAD_JSON:
                            BuildAckNackMessage(rootObject, "nack", "Bad JSON");
                        break;
                    
                    case COMMAND_INVALID:
                            BuildAckNackMessage(rootObject, "nack", "Command Invalid");
                        break;
                        
                    default:
                            BuildAckNackMessage(rootObject, "nack", "Something went wrong");
                        break;
                }
                memset(app2Data.writeBuffer, '\0', APP_WRITE_BUFFER_SIZE);
                // With our response built, serialize the response into a string
                serializedString = json_serialize_to_string(rootValue);
                strcpy(app2Data.writeBuffer, serializedString);
                // Find length of string and add delimiter to end
                app2Data.writeBuffer[strlen(app2Data.writeBuffer)] = '\r';
                
                json_free_serialized_string(serializedString);  
                // Reset string buffers
                memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                memset(messageBuffer, '\0', APP_MESSAGE_BUFFER_SIZE);
                app2Data.state = APP2_STATE_SCHEDULE_WRITE;
            }
            else
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
                if( uxQueueMessagesWaiting( app2Data.debugQueue ) > 0 )
                {
                    int debugMessageNumber;
                    xQueueReceive( app2Data.debugQueue, &debugMessageNumber, 1 );
                    sprintf(app2Data.writeBuffer,                       
                    "{"                                                  
                         "\"message\":{"                                 
                            "\"command\":\"debug\","
                                "\"debug_object\":{"
                                    "\"board_ip_address\":\"%d.%d.%d.%d\","
                                    "\"aws_iot_endpoint\":\"%s\","
                                    "\"mac_address\":\"%s\","
                                    "\"socket_connected\":%s,"
                                    "\"mqtt_connected\":%s,"
                                    "\"raw_message\":\"%s\""
                    "}}}\r",
                    appData.board_ipAddr.v4Add.v[0],
                    appData.board_ipAddr.v4Add.v[1],
                    appData.board_ipAddr.v4Add.v[2],
                    appData.board_ipAddr.v4Add.v[3],
                    appData.host,
                    appData.macAddress,
                    (appData.socket_connected ? "true" : "false"),
                    (appData.mqtt_connected ? "true" : "false"),
                    APP_ReturnDebugCodeToString(debugMessageNumber));
                    app2Data.state = APP2_STATE_SCHEDULE_DEBUG_WRITE;
                }
            }
            break;
            
                        
        case APP2_STATE_SCHEDULE_WRITE:

            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_DEBUG_WRITE:
            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            }
            break;

        case APP2_STATE_ERROR:
            break;
        default:
            break;
    }
}
Ejemplo n.º 11
0
static void prvLowPriorityPeekTask( void *pvParameters )
{
xQueueHandle xQueue = ( xQueueHandle ) pvParameters;
unsigned portLONG ulValue;

	for( ;; )
	{
		/* Write some data to the queue.  This should unblock the highest 
		priority task that is waiting to peek data from the queue. */
		ulValue = 0x11223344;
		if( xQueueSendToBack( xQueue, &ulValue, qpeekNO_BLOCK ) != pdPASS )
		{
			/* We were expecting the queue to be empty so we should not of
			had a problem writing to the queue. */
			xErrorDetected = pdTRUE;
		}

		/* By the time we get here the data should have been removed from
		the queue. */
		if( uxQueueMessagesWaiting( xQueue ) != 0 )
		{
			xErrorDetected = pdTRUE;
		}

		/* Write another value to the queue, again waking the highest priority
		task that is blocked on the queue. */
		ulValue = 0x01234567;
		if( xQueueSendToBack( xQueue, &ulValue, qpeekNO_BLOCK ) != pdPASS )
		{
			/* We were expecting the queue to be empty so we should not of
			had a problem writing to the queue. */
			xErrorDetected = pdTRUE;
		}

		/* All the other tasks should now have successfully peeked the data.
		The data is still in the queue so we should be able to receive it. */
		ulValue = 0;
		if( xQueueReceive( xQueue, &ulValue, qpeekNO_BLOCK ) != pdPASS )
		{
			/* We expected to receive the data. */
			xErrorDetected = pdTRUE;
		}

		if( ulValue != 0x01234567 )
		{
			/* We did not receive the expected value. */
		}
		
		/* Lets just delay a while as this is an intensive test as we don't
		want to starve other tests of processing time. */
		vTaskDelay( qpeekSHORT_DELAY );

		/* Unsuspend the other tasks so we can repeat the test - this time
		however not all the other tasks will peek the data as the high
		priority task is actually going to remove it from the queue.  Send
		to front is used just to be different.  As the queue is empty it
		makes no difference to the result. */
		vTaskResume( xMediumPriorityTask );
		vTaskResume( xHighPriorityTask );
		vTaskResume( xHighestPriorityTask );

		ulValue = 0xaabbaabb;
		if( xQueueSendToFront( xQueue, &ulValue, qpeekNO_BLOCK ) != pdPASS )
		{
			/* We were expecting the queue to be empty so we should not of
			had a problem writing to the queue. */
			xErrorDetected = pdTRUE;
		}

		/* This time we should find that the queue is empty.  The high priority
		task actually removed the data rather than just peeking it. */
		if( xQueuePeek( xQueue, &ulValue, qpeekNO_BLOCK ) != errQUEUE_EMPTY )
		{
			/* We expected to receive the data. */
			xErrorDetected = pdTRUE;
		}

		/* Unsuspend the highest and high priority tasks so we can go back
		and repeat the whole thing.  The medium priority task should not be
		suspended as it was not able to peek the data in this last case. */
		vTaskResume( xHighPriorityTask );
		vTaskResume( xHighestPriorityTask );		

		/* Lets just delay a while as this is an intensive test as we don't
		want to starve other tests of processing time. */
		vTaskDelay( qpeekSHORT_DELAY );
	}
}
Ejemplo n.º 12
0
void bmc_task( void *pvParameters )
{
    ipmbMSG_t       *message;
    ipmbMSG_t       *response;
    int priv;
    unsigned int    priv_pos;
    unsigned char   netfn;
    unsigned char   cmd;


#if defined (CFG_EMMCPM)
    /* init the PM task */
    init_pm();
#endif

    /* set firmware working */
    config_set_fw_ok();

    while (1)
    {

#ifdef CFG_WATCHDOG
        if (!bmc_sched_reset)
        {
            /* reset watchdog timer here */
            taskENTER_CRITICAL();
            lpc_watchdog_reset();
            taskEXIT_CRITICAL();
        }
#endif

        /* wait for data in bmc_rx_queue... */
        if (xQueueReceive(bmc_rx_queue, &message, QUEUE_BLOCK_100))
        {
#ifdef CFG_DEBUG_PERFORMANCE
            unsigned char perf_temp;
            perf_temp = uxQueueMessagesWaiting(bmc_rx_queue);
            if (perf_temp > perf_bmc_rx_waiting) perf_bmc_rx_waiting = perf_temp;
            perf_bmc_task_stack = uxTaskGetStackHighWaterMark(NULL);
#endif
            /* allocate memory for response from global buffer */
            if (!(response = msg_malloc()))
            {
                /* no memory for response -> put message back to queue and retry */
                /* important: DO NOT BLOCK OR MIGHT CAUSE DEADLOCK!!! */

                ERROR_PRINTF((DEBUG_UART, "ERR: %s: Could not msg_malloc() for response.\n", __func__));
                if (xQueueSendToFront(bmc_rx_queue, &message, QUEUE_BLOCK_NONE) != pdPASS)
                {
                    /* set error flag */
                    mon_queues |= MON_QUEUE_BMC_RX;

                    /* delete received message */
                    msg_free(message);
                }
            }
            else
            {
                /* Check the privilege level of the command */
                netfn = message->netFN;
                cmd = message->cmd;
                priv_pos = 1;

                /* decapsulate bridged messages */
                while (netfn == NETFN_APP_RQ && cmd == CMD_SEND_MSG)
                {
                    netfn = message->data[priv_pos + 1] >> 2;
                    cmd = message->data[priv_pos + 5];
                    priv_pos += 7; /* skip next message header + tracking/channel number */
                }

                priv = IPMI_PRIV_PERMITTED;

#ifdef CFG_LAN
                /* at the moment is the lan interface the only onee with authentication */
                if(message->orig_channel == MSG_CHANNEL_LAN)
                {
                    /* determine if the given command is allowed in the given privilege level */
                    priv = ipmi_priv_check_privilege(ipmi_lan_get_privilege(0), netfn, cmd);
                }
#endif
                /* handle value retrieved from privilege check */
                switch (priv)
                {
                case IPMI_PRIV_PERMITTED:
                    /* answer to the message with a local response */
                    bmc_respond(message, response);
                    break;

                case IPMI_PRIV_SEND:
                case IPMI_PRIV_DENIED:
                case IPMI_PRIV_BOOT:
                    /* build response command */
                    response->rsSA  = message->rqSA;
                    response->netFN = (message->netFN | 0x01);          /* response */
                    response->rsLUN = message->rqLUN;
                    response->rqSA  = global_data.bmc_ipmb_addr;        /* BMC's IPMB address */
                    response->rqSeq = message->rqSeq;
                    response->rqLUN = message->rsLUN;
                    response->cmd   = message->cmd;
                    response->orig_channel = message->dest_channel;     /* swap destination and origin channel */
                    response->dest_channel = message->orig_channel;
                    response->data[0] = CC_INSUFFICIENT_PRIVILEGE_LEVEL;
                    response->data_len = 1;
                    break;

                case IPMI_PRIV_INVALID:
                default:
                    /* build response command */
                    response->rsSA  = message->rqSA;
                    response->netFN = (message->netFN | 0x01);          /* response */
                    response->rsLUN = message->rqLUN;
                    response->rqSA  = global_data.bmc_ipmb_addr;        /* BMC's IPMB address */
                    response->rqSeq = message->rqSeq;
                    response->rqLUN = message->rsLUN;
                    response->cmd   = message->cmd;
                    response->orig_channel = message->dest_channel;     /* swap destination and origin channel */
                    response->dest_channel = message->orig_channel;
                    response->data[0] = CC_UNDEFINED;
                    response->data_len = 1;
                    break;
                }

                /* delete received message and send response */
                msg_free(message);

                /* forward reply to msg_hub_rx_queue */
                if (xQueueSend(msg_hub_rx_queue, &response, QUEUE_BLOCK_10) != pdPASS)
                {
                    ERROR_PRINTF((DEBUG_UART, "ERR: %s: msg_hub_rx_queue full\n", __func__));

                    /* set error flag */
                    mon_queues |= MON_QUEUE_MSG_HUB_RX;

                    /* purge response */
                    msg_free(response);
                }
            }
        }
        else
        {
Ejemplo n.º 13
0
/**
 * bmc_task is the main task that handles all requests to/from the BMC
 *
 * In addition it performs:
 * - LED control
 * - FRU state handling
 */
void bmc_task(void *pvParameters)
{
	ipmbMSG_t *message;
	ipmbMSG_t *response;
	int priv;

	/* set firmware working */
	config_set_fw_ok();
		
	while (1)
	{
#ifdef CFG_WATCHDOG
		/* if there is no cold reset sheduled */
		if (!bmc_sched_reset)
		{
			/* reset watchdog timer here */
			lpc_watchdog_reset();
		}
#endif
		
		/* wait for data in bmc_rx_queue... */
		if (xQueueReceive(bmc_rx_queue, &message, QUEUE_BLOCK_100))
		{
#ifdef CFG_DEBUG_PERFORMANCE
			unsigned char perf_temp;
			perf_temp = uxQueueMessagesWaiting(bmc_rx_queue);
			if (perf_temp > perf_bmc_rx_waiting)
				perf_bmc_rx_waiting = perf_temp;
			perf_bmc_task_stack = uxTaskGetStackHighWaterMark(NULL);
#endif
			/* allocate memory for response from global buffer */
			if (!(response = msg_malloc()))
			{
				/* no memory for response -> put message back to queue and retry */
				/* important: DO NOT BLOCK OR MIGHT CAUSE DEADLOCK!!! */
				uart_printf("ERR: %s: Could not msg_malloc() for response.\n", __func__);

				if (xQueueSendToFront(bmc_rx_queue, &message, QUEUE_BLOCK_NONE) != pdPASS)
				{
					/* set error flag */
					mon_queues |= MON_QUEUE_BMC_RX;

					/* delete received message */
					msg_free(message);
				}
			}
			else
			{
				priv = IPMI_PRIV_PERMITTED;

#ifdef CFG_LAN
				/* at the moment is the lan interface the only one with authentication */
				if (message->orig_channel == MSG_CHANNEL_LAN)
				{
					/* determine if the given command is allowed in the given privilege level */
					priv = ipmi_priv_check_privilege(ipmi_lan_get_privilege(0), message->netFN, message->cmd);
				}
#endif
				/* handle value retrieved from privilege check */
				switch (priv)
				{
				case IPMI_PRIV_PERMITTED:
					/* answer to the message with a local response */
					bmc_respond(message, response);
					break;

				case IPMI_PRIV_SEND:
				case IPMI_PRIV_DENIED:
				case IPMI_PRIV_BOOT:
					/* build response command */
					response->rsSA = message->rqSA;
					response->netFN = (message->netFN | 0x01);	/* response */
					response->rsLUN = message->rqLUN;
					response->rqSA = global_data.bmc_ipmb_addr;	/* BMC's IPMB address */
					response->rqSeq = message->rqSeq;
					response->rqLUN = message->rsLUN;
					response->cmd = message->cmd;
					response->orig_channel = message->dest_channel;	/* swap destination and origin channel */
					response->dest_channel = message->orig_channel;
					response->data[0] = CC_INSUFFICIENT_PRIVILEGE_LEVEL;
					response->data_len = 1;
					break;

				case IPMI_PRIV_INVALID:
				default:
					/* build response command */
					response->rsSA = message->rqSA;
					response->netFN = (message->netFN | 0x01);	/* response */
					response->rsLUN = message->rqLUN;
					response->rqSA = global_data.bmc_ipmb_addr;	/* BMC's IPMB address */
					response->rqSeq = message->rqSeq;
					response->rqLUN = message->rsLUN;
					response->cmd = message->cmd;
					response->orig_channel = message->dest_channel;	/* swap destination and origin channel */
					response->dest_channel = message->orig_channel;
					response->data[0] = CC_UNDEFINED;
					response->data_len = 1;
					break;
				}

				/* message was a response don't send anything back */
				if (message->netFN & 0x01)
				{
					/* purge response */
					msg_free(response);
				}

				/* forward reply to msg_hub_rx_queue */
				else if (xQueueSend(msg_hub_rx_queue, &response, QUEUE_BLOCK_10) != pdPASS)
				{
					uart_printf("ERR: %s: msg_hub_rx_queue full\n", __func__);

					/* set error flag */
					mon_queues |= MON_QUEUE_MSG_HUB_RX;

					/* purge response */
					msg_free(response);
				}

				/* delete received message and send response */
				msg_free(message);
			}
		}

#ifdef CFG_ATCA
		/* periodically update FRU state */
		fru_update_state();
#endif
	}
}
Ejemplo n.º 14
0
void cm_update_power_status(void)
{
    ipmbMSG_t   *message;
    ipmbMSG_t   *response;

    /* check if there is data in the cm_mtca_queue... */
    while (xQueueReceive(cm_mtca_queue, &message, QUEUE_BLOCK_NONE))
    {
        /* if CM is disabled do nothing */
        if (!(cm_fru.cmflags & CM_ACTIVE))
        {
            msg_free(message);
            return;
        }

        /* request or response? */
        if (message->netFN & 0x01)
        {
            /* handle response */
            cm_handle_pm_response(message);

            /* delete received message */
            msg_free(message);
        }
        else
        {
            /* allocate memory for response from global buffer */
            if (!(response = msg_malloc()))
            {
                /* no memory for response -> put message back to queue and retry */
                /* important: DO NOT BLOCK OR MIGHT CAUSE DEADLOCK!!! */

                ERROR_PRINTF((DEBUG_UART, "ERR: %s: Could not msg_malloc() for response.\n", __func__));
                if (xQueueSendToFront(cm_mtca_queue, &message, QUEUE_BLOCK_NONE) != pdPASS)
                {
                    /* set error flag */
                    mon_queues |= MON_QUEUE_CM_MTCA;

                    /* delete received message */
                    msg_free(message);
                }
            }
            else
            {
                /* handle power channel notifications */
                cm_handle_powchan(message);

                /* respond to PM */
                cm_pm_respond(message, response);

                /* delete received message and send response */
                msg_free(message);

                /* forward reply to msg_hub_rx_queue */
                if (xQueueSend(msg_hub_rx_queue, &response, QUEUE_BLOCK_10) != pdPASS)
                {
                    ERROR_PRINTF((DEBUG_UART, "ERR: %s: msg_hub_rx_queue full\n", __func__));

                    /* set error flag */
                    mon_queues |= MON_QUEUE_MSG_HUB_RX;

                    /* purge response */
                    msg_free(response);
                }
            }
        }
    }

    return;
}
void wanwuyun_task(void * pvParameters)
{
	//创建Queue
	SENSOR_STRUCT *pRxSensorFrame;
	portBASE_TYPE  xStatus; 
	struct ip_addr WanWuYunIPaddr;
	static err_t err,recv_err;
	
	//网络相关结构体
	struct   netbuf *inbuf;
	uint8_t  *buf;
	uint16_t buflen;
	//成功发送 = true,其他状态为 = false	
	bool wan_send_success_flag = false;	
	
	//创建Json的结构体
	cJSON   *DataUpReqJson, *RowJson, *DataUpResJson,*fld;
	char 	*DataOut;
	
	char double_string[]={0};
#if 0	
	cJSON   *SignInReqJson ,*SignInResJson;
	SignInReqJson=cJSON_CreateObject();
	cJSON_AddStringToObject(SignInReqJson, "username", "jackeyjiang");
	cJSON_AddStringToObject(SignInReqJson, "accessid", "AMFJA2V5AMLHBMCXNDI5NZE2NDIXMTMW");
	cJSON_AddStringToObject(SignInReqJson, "appid", "9785739981");
	cJSON_AddStringToObject(SignInReqJson, "dev_id", "stm32_test");
	DataOut = cJSON_Print(DataUpReqJson);
	cJSON_Delete(SignInReqJson);
	vPortFree(DataOut);
	
	DataUpReqJson=cJSON_CreateArray();
	cJSON_AddItemToObject(DataUpReqJson,NULL,fld = cJSON_CreateObject());
	cJSON_AddStringToObject(fld, "seckey", "HgqoOLTlav5jTsefyj3nL5AkRu8UAFRf");
	cJSON_AddItemToObject(fld, "row", RowJson=cJSON_CreateObject());
	cJSON_AddStringToObject(RowJson, "DEV_ID", "stm32_test");
	cJSON_AddNumberToObject(RowJson, "TEMPERATURE", 12.5);
	cJSON_AddNumberToObject(RowJson, "LATITUDE", 12.7);
	cJSON_AddNumberToObject(RowJson, "LONGITUDE", 12.8);
	//转换数据为cJSON数据
	DataOut = cJSON_Print(DataUpReqJson);
	cJSON_Delete(DataUpReqJson);
	printf("%s",DataOut);
	vPortFree(DataOut);	

	//解析返回的Json数据
	SignInResJson = cJSON_Parse(SignInResponse);
	if (!SignInResJson) 
	vPrintString("Error before: [%s]\n",cJSON_GetErrorPtr());
	else {};
	DataUpResJson = cJSON_Parse(DataUpResponse);
	if (!DataUpResJson) vPrintString("Error before: [%s]\n",cJSON_GetErrorPtr());
	else {};	
#endif	
	//创建传感器队列
	pRxSensor_xQueue = xQueueCreate( 2, sizeof(  struct _SENSOR_STRUCT * ) );

	//建立短连接,接收到队列传过来的数据,将其打包成json数据传送到万物云。
	IP4_ADDR( &WanWuYunIPaddr, WANWUYUN_IP_ADDR0, WANWUYUN_IP_ADDR1, WANWUYUN_IP_ADDR2, WANWUYUN_IP_ADDR3 );
	
	while(1)
	{
		/* Create a new connection identifier. */
		STM_EVAL_LEDOff(LED2);
		wanwuyun_clientconn = netconn_new_with_callback(NETCONN_TCP,wanwuyun_callback); //测试
		if (wanwuyun_clientconn!=NULL)
		{  
			/*built a connect to wanwuyun.com server*/
			//netconn_set_nonblocking(wanwuyun_clientconn, 1); //测试
			err = netconn_connect(wanwuyun_clientconn,&WanWuYunIPaddr,WANWUYUN_SERVER_PORT);
			if (err != ERR_OK)  netconn_delete(wanwuyun_clientconn); 
			else if (err == ERR_OK)
			{
				STM_EVAL_LEDOn(LED2);
				vPrintString("netconn_connect wanwuyun_clientconn\r\n");
				/*timeout to wait for new data to be received <Avoid death etc.> */
				netconn_set_sendtimeout(wanwuyun_clientconn,300);
				netconn_set_recvtimeout(wanwuyun_clientconn,700);
				while(!ERR_IS_FATAL(wanwuyun_clientconn->last_err)) 
				{
					STM_EVAL_LEDToggle(LED3);
					xStatus = xQueueReceive(pRxSensor_xQueue,&(pRxSensorFrame),( portTickType ) 1 );
					if(xStatus == pdPASS)
					{	
						//提取结构体中的数据
						DataUpReqJson=cJSON_CreateArray();
						cJSON_AddItemToObject(DataUpReqJson,NULL,fld = cJSON_CreateObject());
						cJSON_AddStringToObject(fld, "seckey", "HgqoOLTlav5jTsefyj3nL5AkRu8UAFRf");
						cJSON_AddItemToObject(fld, "row", RowJson=cJSON_CreateObject());
						cJSON_AddStringToObject(RowJson, "DEV_ID", "stm32_test");
						sprintf(double_string,"%f",pRxSensorFrame->temperature[0]);
						cJSON_AddStringToObject(RowJson, "TEMPERATURE", double_string);
						sprintf(double_string,"%f",pRxSensorFrame->latitude[0]);
						cJSON_AddStringToObject(RowJson, "LATITUDE", double_string);
						sprintf(double_string,"%f",pRxSensorFrame->longitude[0]);
						cJSON_AddStringToObject(RowJson, "LONGITUDE", double_string);
						//转换数据为cJSON数据
						DataOut = cJSON_Print(DataUpReqJson);
						//printf("%d",strlen(DataOut));
						cJSON_Delete(DataUpReqJson);
						vPrintString("%s\r\n",DataOut);
						//vPortFree(DataOut);					
						err=netconn_write(wanwuyun_clientconn,\
							DataOut,strlen(DataOut),\
							NETCONN_COPY);	
						if(err != ERR_OK)  
						{
							vPortFree(DataOut);
							vPrintString("StatuUploadReq erro code is %d\r\n",err);
							break;
						}	
						else
						{
							wan_send_success_flag = true; //表示数据已经发送了
							vPortFree(DataOut);	
						}
					}
					//netconn_recved(wanwuyun_clientconn,100); //测试
					recv_err = netconn_recv(wanwuyun_clientconn, &inbuf);
					if (recv_err == ERR_OK)
					{
						if (netconn_err(wanwuyun_clientconn) == ERR_OK)
						{ 
							netbuf_data(inbuf, (void**)&buf, &buflen);
							DataUpResJson = cJSON_Parse((char *)buf);
							DataOut = cJSON_Print(DataUpResJson);
							vPrintString("%s\r\n",DataOut);
							netbuf_delete(inbuf);
							wan_send_success_flag = false;
							//使用短链接,成功后跳出while(1)
							//break;
						}
						else
						{
							vPrintString("recv_err != ERR_OK \r\n");
						}
					}
					#if 1  //测试当断开连接的时候的状态
					else if((recv_err == ERR_TIMEOUT)&&(wan_send_success_flag == true)) 
					{
						wan_send_success_flag = false;
						vPrintString("recv_err == %d\r\n",recv_err);
						netconn_close(wanwuyun_clientconn);
						netbuf_delete(inbuf);
						netconn_delete(wanwuyun_clientconn);
						//为发送的数据重新入队
						xQueueSendToFront(pRxSensor_xQueue,&(pRxSensorFrame),( portTickType )1);
						break;
					}
					#endif
				}
			}
		}
	}	
}
Ejemplo n.º 16
0
/*-----------------------------------------------------------------------------------*/
void vTaskGPIOcalc(void *pvParameters)
{
  xTCPTypeDef uTCPt; 
  portBASE_TYPE xStatus_TaskGPIOcalc;
  xDataDriveTypeDef uDRIVE_temp, uDRIVE_new;
  xTCPTypeDef      uTCPcalc;
  char msg[] = {0x00, 0x00, 0x00, 0x00};
  
  // начальная инициализация
  T_step = 2*tau_step;
  calc = 1;
 // vTaskPrioritySet( NULL, ( configMAX_PRIORITIES - 2) );
  
  TIM_Cmd(TIM3, ENABLE);
  
  for (;;)  {
  
    // Проблемы с семафором
    // захват светофора. Ждем до последнего
    xSemaphoreTake(xBinarySemaphore, portMAX_DELAY);  
    
    
    if (calc != 1)
    {
    
    // проверка наличия команд в буфере
    if (uxQueueMessagesWaiting(qDRIVE) > 0)   {
      
      if (uxQueueMessagesWaiting(qDRIVE) == BUF_COM_SDRIVE)
      {
        xStatus_TaskGPIOcalc = uxQueueMessagesWaiting(qDRIVE);
      }
      
       // считываем первое значение из очереди
       xStatus_TaskGPIOcalc = xQueueReceive(qDRIVE, &uDRIVE_temp,  0 );    // тайм-аут не нужен. В очереди точно есть элемент
      
      
       
            // определяем состояние портов, изменяем текущий шаг в uDRIVE, записываем в начало очереди 
             
             // ПРОЦЕДУРЫ расчета нового положения и сосотояния портов
             if (uDRIVE_temp.num_com == G00)    fProc_GOO(&uDRIVE_temp);
             if (uDRIVE_temp.num_com == G01)    fProc_GO1(&uDRIVE_temp);
            // if (uDRIVE_temp.num_com == G01)    Proc_GO1();   // e.t.c
             
             
          
         
       
       // проверка окончания выполенния команды
       if((uDRIVE_temp.STEP_X == uDRIVE_temp.step_x)&&
          (uDRIVE_temp.STEP_Y == uDRIVE_temp.step_y)&&        
          (uDRIVE_temp.STEP_Z == uDRIVE_temp.step_z))
       {  
         
         // проверяем есть ли дальше команды
          if (uxQueueMessagesWaiting(qDRIVE) > 0)   {
            // задаем период повторения для следующей команды
            // считываем без удаления             
            xStatus_TaskGPIOcalc = xQueuePeek(qDRIVE, &uDRIVE_new,  0 );   
            T_step = configTICK_RATE_HZ / uDRIVE_new.SPEED ;
            
            // нужен ли переброс знака
            if (uDRIVE_new.DIR_X!=uDRIVE_temp.DIR_X) CDX = 1;
            else                                     CDX = 0;
            
            if (uDRIVE_new.DIR_Y!=uDRIVE_temp.DIR_Y) CDY = 1;
            else                                     CDY = 0;
            
            if (uDRIVE_new.DIR_Z!=uDRIVE_temp.DIR_Z) CDZ = 1;
            else                                     CDZ = 0;  
            
          }
          else      // если ничего больше нет
          {
                // сброс всех степов
                BSRRL_val  = GPIOE->BSRRL;
                BSRRL_val &= 0xFFF1;     // Зануляем только степы
              
                BSRRH_val  = GPIOE->BSRRH;;     // в резете устанавливаем степы
                BSRRH_val |= 0x000E;
                
                //оставляем срабатывание TaskSW
                T_step = 2*tau_step;       
          }
          
          // выдача сообщения    
              msg[0] = 0x43;
              msg[0] |= 0x80;
              uTCPcalc.ucLen = 4;
              uTCPcalc.ucDATA = msg;
              xStatus_TaskGPIOcalc = xQueueSend(qTCPt, &uTCPcalc, portMAX_DELAY);          
           
       }
       else {
            xStatus_TaskGPIOcalc = xQueueSendToFront(qDRIVE, &uDRIVE_temp, 0);   //запись в начало очереди нового сотояния команды перемещения
       }
          
       }            
       
    calc = 1;                                           // расчет выполнен
    // понижаем приоритет задачи
    vTaskPrioritySet( NULL, ( tskIDLE_PRIORITY) );
    } // calc != 1
     
  } // for (;;)
}