1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "freertos/FreeRTOS.h"
5 #include "freertos/task.h"
6 #include "freertos/semphr.h"
7 #include "freertos/stream_buffer.h"
8 #include "freertos/message_buffer.h"
9 #include "unity.h"
10 #include "test_utils.h"
11 
12 typedef struct {
13     StreamBufferHandle_t sb;
14     SemaphoreHandle_t end_test;
15     bool send_fail;
16     bool receive_fail;
17     bool produce_isr;
18 }test_context;
19 
producer_task(void * arg)20 static void producer_task(void *arg)
21 {
22     test_context *tc  = arg;
23     uint8_t produced = 0;
24     printf("Starting sender task... \n");
25 
26     while(produced < 100) {
27 
28         if(!tc->produce_isr) {
29             BaseType_t result = xStreamBufferSend(tc->sb, &produced, 1, 0);
30             if(!result) {
31                 tc->send_fail = true;
32                 xSemaphoreGive(tc->end_test);
33                 vTaskDelete(NULL);
34             } else {
35                 produced++;
36             }
37         }
38 
39         vTaskDelay(1);
40     }
41 
42     tc->send_fail = false;
43     vTaskDelete(NULL);
44 }
45 
receiver_task(void * arg)46 static void receiver_task(void *arg)
47 {
48     test_context *tc = arg;
49     uint8_t expected_consumed = 0;
50     printf("Starting receiver task... \n");
51 
52     for(;;){
53          uint8_t read_byte = 0xFF;
54          uint32_t result = xStreamBufferReceive(tc->sb, &read_byte, 1, 1000);
55 
56          if((read_byte != expected_consumed) || !result) {
57             tc->receive_fail = true;
58             xSemaphoreGive(tc->end_test);
59             vTaskDelete(NULL);
60          } else {
61              expected_consumed++;
62              if(expected_consumed == 99) {
63                  break;
64              }
65          }
66     }
67 
68     tc->receive_fail = false;
69     xSemaphoreGive(tc->end_test);
70     vTaskDelete(NULL);
71 }
72 
73 TEST_CASE("Send-receive stream buffer test", "[freertos]")
74 {
75     BaseType_t result;
76     test_context tc;
77 
78     tc.sb = xStreamBufferCreate(128, 1);
79     tc.end_test = xSemaphoreCreateBinary();
80 
81     TEST_ASSERT(tc.sb);
82     TEST_ASSERT(tc.end_test);
83 
84     tc.send_fail = false;
85     tc.receive_fail = false;
86     tc.produce_isr = false;
87 
88     result = xTaskCreatePinnedToCore(producer_task, "sender", 4096, &tc, UNITY_FREERTOS_PRIORITY + 2, NULL, 0);
89     TEST_ASSERT(result == pdTRUE);
90     result = xTaskCreatePinnedToCore(receiver_task, "receiver", 4096, &tc, UNITY_FREERTOS_PRIORITY + 1, NULL, 1);
91     TEST_ASSERT(result == pdTRUE);
92 
93     result = xSemaphoreTake(tc.end_test, 2000);
94     TEST_ASSERT(result == pdTRUE);
95 
96     vTaskDelay(1);
97 
98     TEST_ASSERT(tc.send_fail == false);
99     TEST_ASSERT(tc.receive_fail == false);
100 
101     vStreamBufferDelete(tc.sb);
102     vSemaphoreDelete(tc.end_test);
103 }
104