9 · 原书 320–353 页任务通知
9.1本章引言与范围
使用 FreeRTOS 的应用由一组相互独立的任务构成;这些自主任务之间很可能需要相互通信,从而共同提供有用的系统功能。
9.1.1经由中间对象通信
本书前文已介绍多种任务间通信方式。迄今为止描述的方法都需要先创建一个通信对象,例如队列、事件组以及各种不同类型的信号量。使用通信对象时,事件和数据并不直接发送给接收任务或接收 ISR,而是发送给通信对象;同样,任务和 ISR 从通信对象接收事件和数据,而非直接从发送事件或数据的任务、ISR 接收,见图 76。
ASendFunction() 向 vTask2 发送事件;事件不直接发给 vTask2,而是发给中间的通信对象(队列、事件组或某类信号量);vTask2 在某点通过 AReceiveFunction() 从通信对象接收事件,而非直接从 vTask1 接收。9.1.2任务通知——直达任务的通信
“任务通知”允许任务与其他任务交互、与 ISR 同步,而无需单独的通信对象。借助任务通知,任务或 ISR 可把事件直接发送给接收任务,见图 77。
AReceiveFunction() 直接收到来自 vTask1 的通知。任务通知功能是可选的;要包含任务通知功能,在 FreeRTOSConfig.h 中把 configUSE_TASK_NOTIFICATIONS 设为 1。设为 1 后,每个任务都有一个“通知状态”(可取“挂起”或“未挂起”)和一个“通知值”(32 位无符号整数)。任务收到通知时,其通知状态置为挂起;任务读取通知值后,通知状态置为未挂起。任务可在阻塞态等待自己的通知状态变为挂起,可带可选超时。
9.1.3范围
本章帮助读者理解:任务的通知状态与通知值;何时、如何用任务通知替代信号量等通信对象;用任务通知替代通信对象的优势。
9.2任务通知:收益与局限
9.2.1性能收益
用任务通知向任务发送事件或数据,比用队列、信号量或事件组完成同等操作显著更快。
9.2.2RAM 占用收益
同样地,用任务通知发送事件或数据所需 RAM 也显著少于队列、信号量或事件组。因为每个通信对象(队列、信号量、事件组)使用前都必须创建;而启用任务通知功能,每个任务仅有固定的 8 字节 RAM 开销。
9.2.3任务通知的局限
任务通知更快、更省 RAM,但并非所有场景都适用。下列场景不能使用任务通知:
- 向 ISR 发送事件或数据:通信对象可用于从 ISR 向任务、从任务向 ISR 发送事件和数据;任务通知可用于从 ISR 向任务发送,但不能用于从任务向 ISR 发送。
- 支持多个接收任务:通信对象可被任何知道其句柄的任务或 ISR 访问,任意数量的任务和 ISR 都可处理发送到同一通信对象的事件或数据。任务通知直接发给接收任务,只能由通知所发往的任务处理。实际中这很少构成限制:虽然多个任务、ISR 发送到同一通信对象很常见,但从同一通信对象接收则很少见。
- 缓冲多个数据项:队列可同时保存多个数据项,已发送但尚未出队的数据缓冲在队列对象内。任务通知通过更新接收任务的通知值发送数据,通知值一次只能保存一个值。
- 向多个任务广播:事件组可一次向多个任务发送事件;任务通知直接发给接收任务,只能由该任务处理。
- 在阻塞态等待发送完成:通信对象暂时无法再写入时(例如队列已满),尝试写入的任务可选择进入阻塞态等待写操作完成。若任务尝试向一个通知已挂起的任务发送任务通知,发送任务无法进入阻塞态等待接收任务复位其通知状态。后续可见,在使用任务通知的实际场景中这很少构成限制。
9.3使用任务通知
9.3.1任务通知 API 选项
任务通知是非常强大的特性,常可替代二值信号量、计数信号量、事件组,有时甚至可替代队列。宽泛的适用场景通过 xTaskNotify() 发送通知、xTaskNotifyWait() 接收通知实现。但多数情况下并不需要这两个 API 提供的全部灵活性,更简单的函数就足够;因此 xTaskNotifyGive() 作为 xTaskNotify() 更简单(但灵活性更低)的替代,ulTaskNotifyTake() 作为 xTaskNotifyWait() 更简单(但灵活性更低)的替代。
9.3.2xTaskNotifyGive() API 函数
xTaskNotifyGive() 直接向任务发送通知,并把接收任务的通知值加 1;若接收任务通知状态尚未挂起,调用后会置为挂起。它提供一种比二值/计数信号量更轻量、更快的替代。
BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );
xTaskNotifyGive() 实际以宏而非函数实现;本书为简化起见统称其为函数。| 参数名 / 返回值 | 说明 |
|---|---|
| xTaskToNotify | 通知所发往任务的句柄;获取任务句柄的方法见 xTaskCreate() 的 pxCreatedTask 参数。 |
| 返回值 | xTaskNotifyGive() 是调用 xTaskNotify() 的宏;宏传入 xTaskNotify() 的参数被设为使唯一可能返回值为 pdPASS。xTaskNotify() 见后文。 |
9.3.3vTaskNotifyGiveFromISR() API 函数
vTaskNotifyGiveFromISR() 是 xTaskNotifyGive() 可在中断服务程序中使用的版本。
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify,
BaseType_t *pxHigherPriorityTaskWoken );| 参数名 | 说明 |
|---|---|
| xTaskToNotify | 通知所发往任务的句柄;获取方法见 xTaskCreate() 的 pxCreatedTask 参数。 |
| pxHigherPriorityTaskWoken | 若被通知任务正在阻塞态等待接收通知,发送通知会使其退出阻塞态。若调用本函数导致任务退出阻塞态,且被解除阻塞任务优先级高于当前被中断任务的优先级,函数内部会把 *pxHigherPriorityTaskWoken 置为 pdTRUE。该值为 pdTRUE 时,退出中断前应执行一次上下文切换,确保中断直接返回到最高优先级就绪态任务。与所有中断安全 API 一样,使用前必须先把 pxHigherPriorityTaskWoken 初始化为 pdFALSE。 |
9.3.4ulTaskNotifyTake() API 函数
ulTaskNotifyTake() 允许任务在阻塞态等待自己的通知值大于 0,并在返回前把通知值减 1 或清零。它提供一种比二值/计数信号量更轻量、更快的替代。
uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
| 参数名 / 返回值 | 说明 |
|---|---|
| xClearCountOnExit | 设为 pdTRUE:ulTaskNotifyTake() 返回前调用任务通知值清零;设为 pdFALSE 且通知值大于 0:返回前通知值减 1。 |
| xTicksToWait | 任务为等待通知值大于 0 而停留在阻塞态的最长时间。阻塞时间以节拍为单位,绝对时间取决于节拍频率;可用 pdMS_TO_TICKS() 把毫秒换算为节拍。设为 portMAX_DELAY 时无限等待(不超时),前提是 INCLUDE_vTaskSuspend 为 1。 |
| 返回值 | 返回值是通知值在被清零或减 1 之前的值(按 xClearCountOnExit 指定方式处理)。若指定了阻塞时间(xTicksToWait 非 0)且返回值非 0,说明任务可能曾进入阻塞态等待,通知值在阻塞时间到期前被更新;若返回值为 0,说明任务曾进入阻塞态等待,但指定阻塞时间到期前通知值仍未变为大于 0。 |
9.3.5示例 24:用任务通知替代信号量,方法 1
示例 16 用二值信号量在中断服务程序内解除任务阻塞——实质上是让任务与中断同步。本例复刻示例 16 的功能,但用直达任务通知替代二值信号量。
清单 148 给出与中断同步的任务实现;示例 16 中使用的 xSemaphoreTake() 调用被替换为 ulTaskNotifyTake() 调用。xClearCountOnExit 参数设为 pdTRUE,使接收任务通知值在 ulTaskNotifyTake() 返回前清零;因此每次调用之间必须处理完所有已可用事件。示例 16 用二值信号量时,待处理事件数必须从硬件判断,并不总是可行;示例 24 中待处理事件数由 ulTaskNotifyTake() 返回。两次 ulTaskNotifyTake() 调用之间发生的中断事件锁存于任务通知值中;若调用时通知已挂起,ulTaskNotifyTake() 立即返回。
/* The rate at which the periodic task generates software interrupts. */
const TickType_t xInterruptFrequency = pdMS_TO_TICKS( 500UL );
static void vHandlerTask( void *pvParameters )
{
/* xMaxExpectedBlockTime is set to be a little longer than the maximum expected time
between events. */
const TickType_t xMaxExpectedBlockTime = xInterruptFrequency + pdMS_TO_TICKS( 10 );
uint32_t ulEventsToProcess;
/* As per most tasks, this task is implemented within an infinite loop. */
for( ;; )
{
/* Wait to receive a notification sent directly to this task from the
interrupt service routine. */
ulEventsToProcess = ulTaskNotifyTake( pdTRUE, xMaxExpectedBlockTime );
if( ulEventsToProcess != 0 )
{
/* To get here at least one event must have occurred. Loop here until
all the pending events have been processed (in this case, just print out
a message for each event). */
while( ulEventsToProcess > 0 )
{
vPrintString( "Handler task - Processing event.\r\n" );
ulEventsToProcess--;
}
}
else
{
/* If this part of the function is reached then an interrupt did not
arrive within the expected time, and (in a real application) it may be
necessary to perform some error recovery operations. */
}
}
}用于产生软件中断的周期任务,在中断产生前打印一条消息,中断产生后再打印一条,便于在输出中观察执行序列。清单 149 给出中断处理程序实现;它除了直接向推迟中断处理的任务发送通知外几乎不做其他事。
static uint32_t ulExampleInterruptHandler( void )
{
BaseType_t xHigherPriorityTaskWoken;
/* The xHigherPriorityTaskWoken parameter must be initialized to pdFALSE as
it will get set to pdTRUE inside the interrupt safe API function if a
context switch is required. */
xHigherPriorityTaskWoken = pdFALSE;
/* Send a notification directly to the task to which interrupt processing is
being deferred. */
vTaskNotifyGiveFromISR( /* The handle of the task to which the notification
is being sent. The handle was saved when the task
was created. */
xHandlerTask,
/* xHigherPriorityTaskWoken is used in the usual
way. */
&xHigherPriorityTaskWoken );
/* Pass the xHigherPriorityTaskWoken value into portYIELD_FROM_ISR(). If
xHigherPriorityTaskWoken was set to pdTRUE inside vTaskNotifyGiveFromISR()
then calling portYIELD_FROM_ISR() will request a context switch. If
xHigherPriorityTaskWoken is still pdFALSE then calling
portYIELD_FROM_ISR() will have no effect. The implementation of
portYIELD_FROM_ISR() used by the Windows port includes a return statement,
which is why this function does not explicitly return a value. */
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}执行示例 24 的输出见图 78。如预期,与执行示例 16 的输出相同:中断一产生,vHandlerTask() 就进入运行态,因此任务输出穿插在周期任务产生的输出之间,进一步解释见图 79。
vHandlerTask(),任务解除阻塞;因任务此时是就绪态中最高优先级,ISR 直接返回到该任务;处理任务打印消息后回到阻塞态等待下次通知;周期任务再次成为最高优先级,打印第二条消息后又进入阻塞态等待下一时段,只剩空闲任务可运行。vHandlerTask(),任务解除阻塞;ISR 因任务是最高优先级就绪态任务而直接返回到它;④ 处理任务打印消息后回到阻塞态等待下次通知;⑤ 周期任务再次成为最高优先级,打印第二条消息后进入阻塞态等待下一时段,只剩空闲任务可运行。9.3.6示例 25:用任务通知替代信号量,方法 2
示例 24 中 xClearCountOnExit 设为 pdTRUE。示例 25 对示例 24 略作修改,演示 xClearCountOnExit 改为 pdFALSE 时的行为。
xClearCountOnExit 为 pdFALSE 时,调用 ulTaskNotifyTake() 只把通知值减 1,而不清零。于是通知计数等于“已发生事件数”与“已处理事件数”之差,可从两方面简化 vHandlerTask() 结构:① 待处理事件数保存在通知值中,无需再用局部变量保存;② 每次 ulTaskNotifyTake() 调用之间只需处理一个事件。清单 150 给出示例 25 使用的 vHandlerTask() 实现。
static void vHandlerTask( void *pvParameters )
{
/* xMaxExpectedBlockTime is set to be a little longer than the maximum expected time
between events. */
const TickType_t xMaxExpectedBlockTime = xInterruptFrequency + pdMS_TO_TICKS( 10 );
/* As per most tasks, this task is implemented within an infinite loop. */
for( ;; )
{
/* Wait to receive a notification sent directly to this task from the
interrupt service routine. The xClearCountOnExit parameter is now pdFALSE,
so the task's notification value will be decremented by ulTaskNotifyTake(),
and not cleared to zero. */
if( ulTaskNotifyTake( pdFALSE, xMaxExpectedBlockTime ) != 0 )
{
/* To get here an event must have occurred. Process the event (in this
case just print out a message). */
vPrintString( "Handler task - Processing event.\r\n" );
}
else
{
/* If this part of the function is reached then an interrupt did not
arrive within the expected time, and (in a real application) it may be
necessary to perform some error recovery operations. */
}
}
}作演示,ISR 也被修改为每次中断发送不止一个任务通知,以此模拟高频发生的多个中断。清单 151 给出示例 25 使用的 ISR 实现。
static uint32_t ulExampleInterruptHandler( void )
{
BaseType_t xHigherPriorityTaskWoken;
xHigherPriorityTaskWoken = pdFALSE;
/* Send a notification to the handler task multiple times. The first ‘give’ will
unblock the task, the following 'gives' are to demonstrate that the receiving
task's notification value is being used to count (latch) events - allowing the
task to process each event in turn. */
vTaskNotifyGiveFromISR( xHandlerTask, &xHigherPriorityTaskWoken );
vTaskNotifyGiveFromISR( xHandlerTask, &xHigherPriorityTaskWoken );
vTaskNotifyGiveFromISR( xHandlerTask, &xHigherPriorityTaskWoken );
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}执行示例 25 的输出见图 80。可见每次中断产生时,vHandlerTask() 都会处理全部三个事件。
9.3.7xTaskNotify() 与 xTaskNotifyFromISR() API 函数
xTaskNotify() 是 xTaskNotifyGive() 的增强版本,可通过以下任一方式更新接收任务的通知值:
- 把通知值加 1:此时
xTaskNotify()等价于xTaskNotifyGive()。 - 在通知值中置位一个或多个位:可用作事件组更轻量、更快的替代。
- 写入全新数值,但仅当接收任务自通知值上次被更新以来已读取过它:可提供与长度为 1 的队列相近的功能。
- 写入全新数值,即使接收任务自上次更新以来尚未读取:可提供与
xQueueOverwrite()相近的功能,这种行为有时称为“邮箱”。
xTaskNotify() 比 xTaskNotifyGive() 更灵活、更强大,也因此稍复杂。xTaskNotifyFromISR() 是可在 ISR 中使用的版本,因此多一个 pxHigherPriorityTaskWoken 参数。调用 xTaskNotify() 总会把接收任务通知状态置为挂起(若尚未挂起)。
BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify,
uint32_t ulValue,
eNotifyAction eAction );
BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify,
uint32_t ulValue,
eNotifyAction eAction,
BaseType_t *pxHigherPriorityTaskWoken );| 参数名 / 返回值 | 说明 |
|---|---|
| xTaskToNotify | 通知所发往任务的句柄;获取方法见 xTaskCreate() 的 pxCreatedTask 参数。 |
| ulValue | ulValue 如何使用取决于 eNotifyAction 值,见表 52。 |
| eNotifyAction | 枚举类型,指定如何更新接收任务通知值,见表 52。 |
| 返回值 | 除表 52 指出的一种情况外,xTaskNotify() 返回 pdPASS。 |
| eNotifyAction 值 | 对接收任务的结果效果 |
|---|---|
| eNoAction | 接收任务通知状态置为挂起,但不更新通知值;不使用 ulValue 参数。该动作可作为二值信号量更快、更轻量的替代。 |
| eSetBits | 接收任务通知值与 ulValue 按位或。例如 ulValue 为 0x01 则置位 0;为 0x06(二进制 0110)则置位 1 和 2。该动作可作为事件组更快、更轻量的替代。 |
| eIncrement | 接收任务通知值加 1;不使用 ulValue 参数。可作为二值/计数信号量更快、更轻量的替代,等价于更简单的 xTaskNotifyGive()。 |
| eSetValueWithoutOverwrite | 调用 xTaskNotify() 前若接收任务已有通知挂起,则不做动作,返回 pdFAIL;若此前无通知挂起,则通知值设为 ulValue 传入值。 |
| eSetValueWithOverwrite | 无论调用前接收任务是否已有通知挂起,通知值都设为 ulValue 传入值。 |
9.3.8xTaskNotifyWait() API 函数
xTaskNotifyWait() 是 ulTaskNotifyTake() 的增强版本:允许任务带可选超时等待调用任务通知状态变为挂起(若尚未挂起);并提供在函数入口、退出时分别清除通知值中位的选项。
BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry,
uint32_t ulBitsToClearOnExit,
uint32_t *pulNotificationValue,
TickType_t xTicksToWait );| 参数名 / 返回值 | 说明 |
|---|---|
| ulBitsToClearOnEntry | 调用 xTaskNotifyWait() 前若调用任务无通知挂起,则在函数入口把 ulBitsToClearOnEntry 中置位的位在通知值中清零。例如为 0x01 清位 0;为 0xffffffff(ULONG_MAX)清全部位,即把值清为 0。 |
| ulBitsToClearOnExit | 若调用任务因收到通知、或调用时本已有通知挂起而退出 xTaskNotifyWait(),则在退出函数前把 ulBitsToClearOnExit 中置位的位清零;清零发生在通知值保存到 *pulNotificationValue 之后。例如为 0x03 清位 0、1;为 0xffffffff 清全部位。 |
| pulNotificationValue | 用于传出任务通知值。复制到 *pulNotificationValue 的值是按 ulBitsToClearOnExit 设置清零之前的通知值。可选参数,不需要时可置 NULL。 |
| xTicksToWait | 任务为等待通知状态变为挂起而停留在阻塞态的最长时间。阻塞时间以节拍为单位;可用 pdMS_TO_TICKS() 换算毫秒。设为 portMAX_DELAY 时无限等待(不超时),前提是 INCLUDE_vTaskSuspend 为 1。 |
| 返回值 | 两种可能:① pdTRUE——因收到通知、或调用时本已有通知挂起而返回;若指定了阻塞时间,任务可能曾进入阻塞态等待,通知状态在到期前置为挂起。② pdFALSE——调用任务未收到任务通知即返回;若 xTicksToWait 非 0,说明任务曾在阻塞态等待,但阻塞时间到期前通知状态仍未挂起。 |
9.3.9外设设备驱动中的任务通知:UART 示例
外设驱动库提供对硬件接口执行常用操作的函数。常见外设包括 UART(通用异步收发器)、SPI 端口、ADC(模数转换器)、以太网端口;库函数通常包括初始化外设、向外设发送数据、从外设接收数据等。
某些外设操作完成耗时较长,例如高精度 ADC 转换、UART 上发送大数据包。这类情况下驱动库函数可轮询(反复读取)外设状态寄存器判断操作何时完成;但这种轮询几乎总是浪费:在没有产生任何有效处理的情况下占用 100% 处理器时间。多任务系统中浪费尤其昂贵:轮询外设的任务可能阻碍低优先级任务执行,而后者确有有效处理要做。
为避免处理时间浪费,高效的、具备 RTOS 意识的设备驱动应中断驱动,并让发起长操作的任务可选择在阻塞态等待操作完成。这样执行长操作的任务处于阻塞态时,低优先级任务可以运行;任何任务只有能有效使用处理时间时才占用它。
具备 RTOS 意识的驱动库常用二值信号量把任务放入阻塞态。清单 154 伪代码演示该技术,给出在 UART 端口发送数据的 RTOS 意识库函数轮廓。清单中:xUART 是描述 UART 外设、保存状态信息的结构体,其 xTxSemaphore 成员为 SemaphoreHandle_t 类型变量,假定信号量已创建;xUART_Send() 不含任何互斥逻辑,若多个任务使用它,互斥须由应用自身管理(例如调用前先取得互斥量);xSemaphoreTake() 用于在 UART 传输发起后把调用任务放入阻塞态;xSemaphoreGiveFromISR() 用于在传输完成(UART 发送结束中断服务程序执行)后把任务移出阻塞态。
/* Driver library function to send data to a UART. */
BaseType_t xUART_Send( xUART *pxUARTInstance, uint8_t *pucDataSource, size_t uxLength )
{
BaseType_t xReturn;
/* Ensure the UART's transmit semaphore is not already available by attempting to take
the semaphore without a timeout. */
xSemaphoreTake( pxUARTInstance->xTxSemaphore, 0 );
/* Start the transmission. */
UART_low_level_send( pxUARTInstance, pucDataSource, uxLength );
/* Block on the semaphore to wait for the transmission to complete. If the semaphore
is obtained then xReturn will get set to pdPASS. If the semaphore take operation times
out then xReturn will get set to pdFAIL. Note that, if the interrupt occurs between
UART_low_level_send() being called, and xSemaphoreTake() being called, then the event
will be latched in the binary semaphore, and the call to xSemaphoreTake() will return
immediately. */
xReturn = xSemaphoreTake( pxUARTInstance->xTxSemaphore, pxUARTInstance->xTxTimeout );
return xReturn;
}
/*-----------------------------------------------------------*/
/* The service routine for the UART's transmit end interrupt, which executes after the
last byte has been sent to the UART. */
void xUART_TransmitEndISR( xUART *pxUARTInstance )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Clear the interrupt. */
UART_low_level_interrupt_clear( pxUARTInstance );
/* Give the Tx semaphore to signal the end of the transmission. If a task is Blocked
waiting for the semaphore then the task will be removed from the Blocked state. */
xSemaphoreGiveFromISR( pxUARTInstance->xTxSemaphore, &xHigherPriorityTaskWoken );
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}清单 154 技术完全可行、也确为常见做法,但有缺点:① 库使用多个信号量,增大 RAM 占用;② 信号量创建后才能使用,因此使用信号量的库必须先显式初始化;③ 信号量是通用对象,适用范围广,其内部逻辑允许任意数量任务在阻塞态等待信号量可用,并在信号量可用时(以确定性方式)选择解除哪个任务阻塞;执行这些逻辑需要有限时间,而清单 154 场景中任一时刻不可能有多于一个任务等待信号量,这部分开销并不必要。
清单 155 演示如何用任务通知替代二值信号量以避免这些缺点。注意:若库使用任务通知,库文档必须明确说明调用库函数可能改变调用任务的通知状态和通知值。清单 155 中:xUART 结构体的 xTxSemaphore 成员被 xTaskToNotify 成员取代,xTaskToNotify 为 TaskHandle_t 类型,保存等待 UART 操作完成的任务句柄;用 xTaskGetCurrentTaskHandle() 获取处于运行态任务的句柄;库不创建任何 FreeRTOS 对象,因此不产生 RAM 开销,也无需显式初始化;通知直接发给等待 UART 操作完成的任务,不执行不必要逻辑。
xUART 结构体的 xTaskToNotify 成员同时被任务和 ISR 访问,须考虑处理器如何更新其值:① 若 xTaskToNotify 由单次内存写操作更新,可在临界区之外更新(如清单 155 所示);当 xTaskToNotify 是 32 位变量(TaskHandle_t 为 32 位类型)、且 FreeRTOS 运行于 32 位处理器时即属此情况。② 若更新 xTaskToNotify 需要不止一次内存写操作,则只能在临界区内更新;否则 ISR 可能在其处于不一致状态时访问。当 xTaskToNotify 是 32 位变量、运行处理器为 16 位处理器时即属此情况,更新全部 32 位需要两次 16 位内存写操作。FreeRTOS 内部 TaskHandle_t 是指针,因此 sizeof(TaskHandle_t) 恒等于 sizeof(void *)。
/* Driver library function to send data to a UART. */
BaseType_t xUART_Send( xUART *pxUARTInstance, uint8_t *pucDataSource, size_t uxLength )
{
BaseType_t xReturn;
/* Save the handle of the task that called this function. The book text contains notes as to
whether the following line needs to be protected by a critical section or not. */
pxUARTInstance->xTaskToNotify = xTaskGetCurrentTaskHandle();
/* Ensure the calling task does not already have a notification pending by calling
ulTaskNotifyTake() with the xClearCountOnExit parameter set to pdTRUE, and a block time of 0
(don't block). */
ulTaskNotifyTake( pdTRUE, 0 );
/* Start the transmission. */
UART_low_level_send( pxUARTInstance, pucDataSource, uxLength );
/* Block until notified that the transmission is complete. If the notification is received
then xReturn will be set to 1 because the ISR will have incremented this task's notification
value to 1 (pdTRUE). If the operation times out then xReturn will be 0 (pdFALSE) because
this task's notification value will not have been changed since it was cleared to 0 above.
Note that, if the ISR executes between the calls to UART_low_level_send() and the call to
ulTaskNotifyTake(), then the event will be latched in the task’s notification value, and the
call to ulTaskNotifyTake() will return immediately.*/
xReturn = ( BaseType_t ) ulTaskNotifyTake( pdTRUE, pxUARTInstance->xTxTimeout );
return xReturn;
}
/*-----------------------------------------------------------*/
/* The ISR that executes after the last byte has been sent to the UART. */
void xUART_TransmitEndISR( xUART *pxUARTInstance )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* This function should not execute unless there is a task waiting to be notified. Test this
condition with an assert. This step is not strictly necessary, but will aid debugging.
configASSERT() is described in section 11.2.*/
configASSERT( pxUARTInstance->xTaskToNotify != NULL );
/* Clear the interrupt. */
UART_low_level_interrupt_clear( pxUARTInstance );
/* Send a notification directly to the task that called xUART_Send(). If the task is Blocked
waiting for the notification then the task will be removed from the Blocked state. */
vTaskNotifyGiveFromISR( pxUARTInstance->xTaskToNotify, &xHigherPriorityTaskWoken );
/* Now there are no tasks waiting to be notified. Set the xTaskToNotify member of the xUART
structure back to NULL. This step is not strictly necessary but will aid debugging. */
pxUARTInstance->xTaskToNotify = NULL;
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}任务通知同样可在接收函数中替代信号量,清单 156 伪代码给出在 UART 端口接收数据的 RTOS 意识库函数轮廓。xUART_Receive() 不含互斥逻辑;UART 接收中断服务程序把收到的字符放入 RAM 缓冲,xUART_Receive() 从该缓冲返回字符;uxWantedBytes 指定要接收的字符数,若 RAM 缓冲尚未含请求数量,调用任务进入阻塞态等待缓冲中字符数增加的通知,while() 循环重复该序列直到缓冲含请求数量或超时;调用任务可能多次进入阻塞态,因此阻塞时间需按 xUART_Receive() 调用以来已流逝的时间调整,确保函数内总时间不超过结构体 xRxTimeout 成员指定的阻塞时间;阻塞时间用 FreeRTOS 辅助函数 vTaskSetTimeOutState() 与 xTaskCheckForTimeOut() 调整。
/* Driver library function to receive data from a UART. */
size_t xUART_Receive( xUART *pxUARTInstance, uint8_t *pucBuffer, size_t uxWantedBytes )
{
size_t uxReceived = 0;
TickType_t xTicksToWait;
TimeOut_t xTimeOut;
/* Record the time at which this function was entered. */
vTaskSetTimeOutState( &xTimeOut );
/* xTicksToWait is the timeout value - it is initially set to the maximum receive
timeout for this UART instance. */
xTicksToWait = pxUARTInstance->xRxTimeout;
/* Save the handle of the task that called this function. The book text contains notes
as to whether the following line needs to be protected by a critical section or not. */
pxUARTInstance->xTaskToNotify = xTaskGetCurrentTaskHandle();
/* Loop until the buffer contains the wanted number of bytes, or a timeout occurs. */
while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes )
{
/* Look for a timeout, adjusting xTicksToWait to account for the time spent in this
function so far. */
if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE )
{
/* Timed out before the wanted number of bytes were available, exit the loop. */
break;
}
/* The receive buffer does not yet contain the required amount of bytes. Wait for a
maximum of xTicksToWait ticks to be notified that the receive interrupt service
routine has placed more data into the buffer. It does not matter if the calling
task already had a notification pending when it called this function, if it did, it
would just iteration around this while loop one extra time. */
ulTaskNotifyTake( pdTRUE, xTicksToWait );
}
/* No tasks are waiting for receive notifications, so set xTaskToNotify back to NULL.
The book text contains notes as to whether the following line needs to be protected by
a critical section or not. */
pxUARTInstance->xTaskToNotify = NULL;
/* Attempt to read uxWantedBytes from the receive buffer into pucBuffer. The actual
number of bytes read (which might be less than uxWantedBytes) is returned. */
uxReceived = UART_read_from_receive_buffer( pxUARTInstance, pucBuffer, uxWantedBytes );
return uxReceived;
}
/*-----------------------------------------------------------*/
/* The interrupt service routine for the UART's receive interrupt */
void xUART_ReceiveISR( xUART *pxUARTInstance )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Copy received data into this UART's receive buffer and clear the interrupt. */
UART_low_level_receive( pxUARTInstance );
/* If a task is waiting to be notified of the new data then notify it now. */
if( pxUARTInstance->xTaskToNotify != NULL )
{
vTaskNotifyGiveFromISR( pxUARTInstance->xTaskToNotify, &xHigherPriorityTaskWoken );
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}9.3.10外设设备驱动中的任务通知:ADC 示例
上一节演示如何用 vTaskNotifyGiveFromISR() 从中断向任务发送任务通知;它使用简单但能力有限,只能发送无值事件,不能携带数据。本节演示如何用 xTaskNotifyFromISR() 随任务通知事件一起发送数据。清单 157 伪代码给出 ADC(模数转换器)RTOS 意识中断服务程序轮廓。清单中:假定至少每 50 毫秒启动一次 ADC 转换;ADC_ConversionEndISR() 是 ADC 转换结束中断的 ISR,每次有新 ADC 值可用时执行;vADCTask() 实现的任务处理 ADC 产生的每个值,假定任务句柄在创建时已存入 xADCTaskToNotify;ADC_ConversionEndISR() 用 xTaskNotifyFromISR(),eAction 参数设为 eSetValueWithoutOverwrite,向 vADCTask() 发送通知并把 ADC 转换结果写入其通知值;vADCTask() 用 xTaskNotifyWait() 等待新 ADC 值可用的通知,并从通知值取回转换结果。
/* A task that uses an ADC. */
void vADCTask( void *pvParameters )
{
uint32_t ulADCValue;
BaseType_t xResult;
/* The rate at which ADC conversions are triggered. */
const TickType_t xADCConversionFrequency = pdMS_TO_TICKS( 50 );
for( ;; )
{
/* Wait for the next ADC conversion result. */
xResult = xTaskNotifyWait(
/* The new ADC value will overwrite the old value, so there is no need
to clear any bits before waiting for the new notification value. */
0,
/* Future ADC values will overwrite the existing value, so there is no
need to clear any bits before exiting xTaskNotifyWait(). */
0,
/* The address of the variable into which the task's notification value
(which holds the latest ADC conversion result) will be copied. */
&ulADCValue,
/* A new ADC value should be received every xADCConversionFrequency
ticks. */
xADCConversionFrequency * 2 );
if( xResult == pdPASS )
{
/* A new ADC value was received. Process it now. */
ProcessADCResult( ulADCValue );
}
else
{
/* The call to xTaskNotifyWait() did not return within the expected time,
something must be wrong with the input that triggers the ADC conversion, or with
the ADC itself. Handle the error here. */
}
}
}
/*-----------------------------------------------------------*/
/* The interrupt service routine that executes each time an ADC conversion completes. */
void ADC_ConversionEndISR( xADC *pxADCInstance )
{
uint32_t ulConversionResult;
BaseType_t xHigherPriorityTaskWoken = pdFALSE, xResult;
/* Read the new ADC value and clear the interrupt. */
ulConversionResult = ADC_low_level_read( pxADCInstance );
/* Send a notification, and the ADC conversion result, directly to vADCTask(). */
xResult = xTaskNotifyFromISR( xADCTaskToNotify, /* xTaskToNotify parameter. */
ulConversionResult, /* ulValue parameter. */
eSetValueWithoutOverwrite, /* eAction parameter. */
&xHigherPriorityTaskWoken );
/* If the call to xTaskNotifyFromISR() returns pdFAIL then the task is not keeping up
with the rate at which ADC values are being generated. configASSERT() is described
in section 11.2.*/
configASSERT( xResult == pdPASS );
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}9.3.11应用内直接使用任务通知
本节通过一个假设应用强化任务通知的能力,该应用包含以下功能:① 经由慢速互联网连接与远端数据服务器通信,向其发送数据、请求数据(下称云服务器);② 请求云服务器数据后,请求任务必须在阻塞态等待所请求数据收到;③ 向云服务器发送数据后,发送任务必须在阻塞态等待云服务器正确收到数据的确认。
软件设计示意见图 81。图中:处理与云服务器多条互联网连接的复杂性被封装在单个 FreeRTOS 任务内;该任务在 FreeRTOS 应用中充当代理服务器,称服务器任务。应用任务通过调用 CloudRead() 从云服务器读数据;CloudRead() 不直接与云服务器通信,而是把读请求经队列发给服务器任务,再以任务通知形式从服务器任务接收所请求数据。应用任务通过调用 CloudWrite() 向云服务器写数据;CloudWrite() 同样不直接通信,而是把写请求经队列发给服务器任务,再以任务通知形式从服务器任务接收写操作结果。
xQueueReceive() 接收命令/事件、ProcessMessage() 处理)、应用任务 1(反复 CloudRead())、应用任务 2(反复 CloudWrite());应用任务与服务器任务之间经队列传递请求,服务器任务经任务通知把数据/状态返回给应用任务;服务器任务经互联网连接云服务器。CloudRead() 与 CloudWrite() 发给服务器任务的结构体见清单 158。
typedef enum CloudOperations
{
eRead, /* Send data to the cloud server. */
eWrite /* Receive data from the cloud server. */
} Operation_t;
typedef struct CloudCommand
{
Operation_t eOperation; /* The operation to perform (read or write). */
uint32_t ulDataID; /* Identifies the data being read or written. */
uint32_t ulDataValue; /* Only used when writing data to the cloud server. */
TaskHandle_t xTaskToNotify;/* The handle of the task performing the operation. */
} CloudCommand_t;CloudRead() 伪代码见清单 159:函数把请求发给服务器任务,再调用 xTaskNotifyWait() 在阻塞态等待所请求数据可用的通知。服务器任务处理读请求的伪代码见清单 160:从云服务器收到数据后,服务器任务解除应用任务阻塞,并以 eAction 设为 eSetValueWithOverwrite 的 xTaskNotify() 把收到的数据发给应用任务。清单 160 为简化场景,假定 GetCloudData() 无需等待从云服务器取值。
/* ulDataID identifies the data to read. pulValue holds the address of the variable into
which the data received from the cloud server is to be written. */
BaseType_t CloudRead( uint32_t ulDataID, uint32_t *pulValue )
{
CloudCommand_t xRequest;
BaseType_t xReturn;
/* Set the CloudCommand_t structure members to be correct for this read request. */
xRequest.eOperation = eRead; /* This is a request to read data. */
xRequest.ulDataID = ulDataID; /* A code that identifies the data to read. */
xRequest.xTaskToNotify = xTaskGetCurrentTaskHandle(); /* Handle of the calling task. */
/* Ensure there are no notifications already pending by reading the notification value
with a block time of 0, then send the structure to the server task. */
xTaskNotifyWait( 0, 0, NULL, 0 );
xQueueSend( xServerTaskQueue, &xRequest, portMAX_DELAY );
/* Wait for a notification from the server task. The server task writes the value
received from the cloud server directly into this task’s notification value, so there is
no need to clear any bits in the notification value on entry to or exit from the
xTaskNotifyWait() function. The received value is written to *pulValue, so pulValue is
passed as the address to which the notification value is written. */
xReturn = xTaskNotifyWait( 0, /* No bits cleared on entry. */
0, /* No bits to clear on exit. */
pulValue, /* Notification value into *pulValue. */
pdMS_TO_TICKS( 250 ) ); /* Wait a maximum of 250ms. */
/* If xReturn is pdPASS, then the value was obtained. If xReturn is pdFAIL, then the
request timed out. */
return xReturn;
}void ServerTask( void *pvParameters )
{
CloudCommand_t xCommand;
uint32_t ulReceivedValue;
for( ;; )
{
/* Wait for the next CloudCommand_t structure to be received from a task. */
xQueueReceive( xServerTaskQueue, &xCommand, portMAX_DELAY );
switch( xCommand.eOperation ) /* Was it a read or write request? */
{
case eRead:
/* Obtain the requested data item from the remote cloud server. */
ulReceivedValue = GetCloudData( xCommand.ulDataID );
/* Call xTaskNotify() to send both a notification and the value received from the
cloud server to the task that made the request. The handle of the task is
obtained from the CloudCommand_t structure. */
xTaskNotify( xCommand.xTaskToNotify, /* The task’s handle is in the structure. */
ulReceivedValue, /* Cloud data sent as notification value. */
eSetValueWithOverwrite );
break;
/* Other switch cases go here. */
}
}
}CloudWrite() 伪代码见清单 161。作演示,CloudWrite() 返回按位状态码,状态码每位赋予唯一含义;清单顶部 #define 给出四个示例状态位。任务先清除四个状态位,把请求发给服务器任务,再调用 xTaskNotifyWait() 在阻塞态等待状态通知。
/* Status bits used by the cloud write operation. */
#define SEND_SUCCESSFUL_BIT
( 0x01 << 0 )
#define OPERATION_TIMED_OUT_BIT
( 0x01 << 1
#define NO_INTERNET_CONNECTION_BIT ( 0x01 << 2 )
#define CANNOT_LOCATE_CLOUD_SERVER_BIT
( 0x01 << 3 )
/* A mask that has the four status bits set. */
#define CLOUD_WRITE_STATUS_BIT_MASK ( SEND_SUCCESSFUL_BIT |
OPERATION_TIMED_OUT_BIT |
NO_INTERNET_CONNECTION_BIT |
CANNOT_LOCATE_CLOUD_SERVER_BIT )
uint32_t CloudWrite( uint32_t ulDataID, uint32_t ulDataValue )
{
CloudCommand_t xRequest;
uint32_t ulNotificationValue;
/* Set the CloudCommand_t structure members to be correct for this write request. */
xRequest.eOperation = eWrite; /* This is a request to write data. */
xRequest.ulDataID = ulDataID; /* A code that identifies the data being written. */
xRequest.ulDataValue = ulDataValue; /* Value of the data written to the cloud server. */
xRequest.xTaskToNotify = xTaskGetCurrentTaskHandle(); /* Handle of the calling task. */
/* Clear the three status bits relevant to the write operation by calling
xTaskNotifyWait() with the ulBitsToClearOnExit parameter set to
CLOUD_WRITE_STATUS_BIT_MASK, and a block time of 0. The current notification value is
not required, so the pulNotificationValue parameter is set to NULL. */
xTaskNotifyWait( 0, CLOUD_WRITE_STATUS_BIT_MASK, NULL, 0 );
/* Send the request to the server task. */
xQueueSend( xServerTaskQueue, &xRequest, portMAX_DELAY );
/* Wait for a notification from the server task. The server task writes a bitwise status
code into this task’s notification value, which is written to ulNotificationValue. */
xTaskNotifyWait( 0, /* No bits cleared on entry. */
CLOUD_WRITE_STATUS_BIT_MASK, /* Clear relevant bits to 0 on exit. */
&ulNotificationValue, /* Notified value. */
pdMS_TO_TICKS( 250 ) ); /* Wait a maximum of 250ms. */
/* Return the status code to the calling task. */
return ( ulNotificationValue & CLOUD_WRITE_STATUS_BIT_MASK );服务器任务处理写请求的伪代码见清单 162:数据发到云服务器后,服务器任务解除应用任务阻塞,并以 eAction 设为 eSetBits 的 xTaskNotify() 把按位状态码发给应用任务。只有 CLOUD_WRITE_STATUS_BIT_MASK 常量定义的位会被改动,因此接收任务可把通知值中其他位用于其他用途。清单 162 为简化场景,假定 SetCloudData() 无需等待从云服务器取得确认。
void ServerTask( void *pvParameters )
{
CloudCommand_t xCommand;
uint32_t ulBitwiseStatusCode;
for( ;; )
{
/* Wait for the next message. */
xQueueReceive( xServerTaskQueue, &xCommand, portMAX_DELAY );
/* Was it a read or write request? */
switch( xCommand.eOperation )
{
case eWrite:
/* Send the data to the remote cloud server. SetCloudData() returns a bitwise
status code that only uses the bits defined by the CLOUD_WRITE_STATUS_BIT_MASK
definition (shown in Listing 161). */
ulBitwiseStatusCode = SetCloudData( xCommand.ulDataID, xCommand.ulDataValue );
/* Send a notification to the task that made the write request. The eSetBits
action is used so any status bits set in ulBitwiseStatusCode will be set in the
notification value of the task being notified. All the other bits remain
unchanged. The handle of the task is obtained from the CloudCommand_t
structure. */
xTaskNotify( xCommand.xTaskToNotify, /* The task’s handle is in the structure. */
ulBitwiseStatusCode, /* Cloud data sent as notification value. */
eSetBits );
break;
/* Other switch cases go here. */
}
}
}