]> rtime.felk.cvut.cz Git - pes-rpp/rpp-simulink.git/blob - rpp/rpp/rpp_mrmain.tlc
b6b5e56f206fbd77abc32dab44ffe791cfcf2931
[pes-rpp/rpp-simulink.git] / rpp / rpp / rpp_mrmain.tlc
1 %% Copyright (C) 2013-2015 Czech Technical University in Prague
2 %%
3 %% Authors:
4 %%     - Carlos Jenkins <carlos@jenkins.co.cr>
5 %%     - Michal Sojka <sojkam1@fel.cvut.cz>
6 %%     - Michal Horn <hornmich@fel.cvut.cz>
7 %%
8 %% This document contains proprietary information belonging to Czech
9 %% Technical University in Prague. Passing on and copying of this
10 %% document, and communication of its contents is not permitted
11 %% without prior written authorization.
12 %%
13 %% File : rpp_mrmain.tlc
14 %% Abstract:
15 %%     Custom TLC file to generate an RPP "main" file.
16 %%
17 %%     This file generates the "main" file for the RPP target on top of the RPP
18 %%     library and the FreeRTOS operating system.
19 %%
20 %%     The mr prefix is standard to mark Multi Tasking main, which is the case. See
21 %%     rpp_file_process.m description above for more information about this.
22 %%
23 %% References:
24 %%     Example in <matlabroot>/rtw/c/tlc/mw/bareboard_mrmain.tlc
25
26
27 %selectfile NULL_FILE
28
29 %function FcnMultiTaskingMain() void
30
31     %if GenerateSampleERTMain
32         %assign CompiledModel.GenerateSampleERTMain = TLC_FALSE
33     %endif
34
35
36     %assign cFile = LibCreateSourceFile("Source", "Custom", "ert_main")
37
38
39     %%%%%%%%
40     %openfile tmpBuf
41
42     /* Model includes */
43     #include "%<LibGetMdlPubHdrBaseName()>.h"
44
45     /* RPP runtime includes */
46     #include "rpp_simulink_runtime.h"
47
48     %if extMode == 1
49       /* External mode header file */
50       #include "ext_work.h"
51       #include <drv/sci.h>
52     %endif
53
54     %closefile tmpBuf
55     %<LibSetSourceFileSection(cFile, "Includes", tmpBuf)>
56     %%%%%%%%
57
58
59     %%%%%%%%
60     %openfile tmpBuf
61
62     /* Definitions */
63     #define STEP_SIZE_MILLIS (%<CompiledModel.FundamentalStepSize>*1000.0)
64     #define NUM_SAMPLE_TIMES    %<numSampleTimes>
65     #define CONTROL_PRIORITY (configMAX_PRIORITIES - 1)
66
67     %% Worker task priority assignment - rate transition block
68     %% requires rate monotonic priority assignment
69     %foreach i = numSampleTimes - tid01Eq
70         #define WORKING%<i + tid01Eq>_PRIORITY    (configMAX_PRIORITIES - %<2 + i>)
71     %endforeach
72
73     %if extMode == 1
74       #define EXTMODE_PRIORITY 1
75     %else
76       #define IDLE_PRIORITY 0
77       #define EXTMODE_PRIORITY IDLE_PRIORITY /* Extmode not used */
78     %endif
79
80     %foreach i = numSampleTimes - tid01Eq
81         %assign j = i + tid01Eq
82         #if (WORKING%<j>_PRIORITY <= EXTMODE_PRIORITY) || (WORKING%<j>_PRIORITY >= CONTROL_PRIORITY)
83         #error Too many tasks. Increase configMAX_PRIORITIES.
84         #endif
85     %endforeach
86
87     %closefile tmpBuf
88     %<LibSetSourceFileSection(cFile, "Defines", tmpBuf)>
89     %%%%%%%%
90
91
92     %%%%%%%%
93     %openfile tmpBuf
94     typedef struct sub_rate_st {
95         xTaskHandle      thread;
96         xSemaphoreHandle sem;
97     } sub_rate_t;
98
99     %if extMode == 1
100       static xSemaphoreHandle ext_mode_ready = NULL;
101     %endif
102     static uint32_t steps_control = 0;
103     static uint32_t steps_working[NUM_SAMPLE_TIMES];
104     boolean_t overrun_flag = FALSE;
105     static sub_rate_t sub_rate[NUM_SAMPLE_TIMES];
106     static boolean_t simulationFinished = 0;
107
108     %closefile tmpBuf
109     %<LibSetSourceFileSection(cFile, "Declarations", tmpBuf)>
110     %%%%%%%%
111
112
113     %%%%%%%%
114     %openfile tmpBuf
115
116     /**
117      * Model step control and overrun detection task.
118      */
119     void control_task(void* p)
120     {
121         uint32_t i;
122
123         %% Variables used by LibCallSetEventForThisBaseStep (static => zero initialized)
124         static uint32_t taskCounter[NUM_SAMPLE_TIMES];
125         static boolean_t eventFlags[NUM_SAMPLE_TIMES];
126         static boolean_t OverrunFlags[NUM_SAMPLE_TIMES];
127
128         (void)OverrunFlags; /* Not used in multitasking mode, but required by TLC macro */
129
130         steps_control = 0;
131       %if extMode == 1
132         xSemaphoreTake(ext_mode_ready, portMAX_DELAY);
133       %endif
134
135       static const portTickType freq_ticks = STEP_SIZE_MILLIS / portTICK_RATE_MS;
136       portTickType last_wake_time = xTaskGetTickCount();
137
138     %% This condition has been added because of the warning:
139     %% "ert_main.c", line 46: warning #238-D: controlling expression is constant
140     %% caused by the expression (void*) 0 passed to the while statement. The rtmGetStopRequested
141     %% macro is defined to this constant if and only if the GenerateSampleERTMain is not set. So
142     %% The condition is not needed in this case as well.
143     %%
144     %% See <MATLAB_ROOT>/rtw/c/tlc/mw/rtmspecmacs.tlc at line 198.
145
146     %if !GenerateSampleERTMain
147         while (rtmGetErrorStatus(%<modelName>_M) == NULL) {
148     %else
149         while (rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {
150     %endif
151             /* Wait until next step */
152             vTaskDelayUntil(&last_wake_time, freq_ticks);
153
154             /* Check subrate overrun, set rates that need to run this time step*/
155             %<LibCallSetEventForThisBaseStep("eventFlags")>\
156
157             /* Trigger sub-rate threads */
158             %foreach j = numSampleTimes - tid01Eq
159                 %assign i = j + tid01Eq
160                 %assign s = CompiledModel.SampleTime[i].PeriodAndOffset[0]
161                 %assign o = CompiledModel.SampleTime[i].PeriodAndOffset[1]
162                 /* Sampling rate %<i>, sample time = %<s>, offset = %<o> */
163             %endforeach
164
165               for (i = %<tid01Eq>; i < NUM_SAMPLE_TIMES; i++) {
166                 if (i == 0 || eventFlags[i]) {
167                     eventFlags[i] = FALSE;
168                     uint32_t step_sem_value = uxQueueMessagesWaiting(sub_rate[i].sem);
169                     if (step_sem_value) {
170                         rtmSetErrorStatus(%<modelName>_M, "Overrun");
171                         overrun_flag = TRUE;
172                         break;
173                     }
174                     if (xSemaphoreGive(sub_rate[i].sem) == pdFALSE) {
175                         rpp_sci_printk("ERROR: Task %d semaphore 1 give.\n", i);
176                         while (1) ;
177                     }
178                     if (xSemaphoreGive(sub_rate[i].sem) == pdFALSE) {
179                         rpp_sci_printk("ERROR: Task %d semaphore 2 give.\n", i);
180                         while (1) ;
181                     }
182                 }
183               }
184
185             steps_control++;
186
187             %if extMode == 1
188               rtExtModeCheckEndTrigger();
189             %endif
190
191         }
192         simulationFinished = 1;
193
194         /* Final step */
195         for (i = %<tid01Eq>; i < NUM_SAMPLE_TIMES; i++) {
196             xSemaphoreGive(sub_rate[i].sem);
197             xSemaphoreGive(sub_rate[i].sem);
198         }
199
200         /* In case of shutdown, delete this task */
201         vTaskDelete(NULL);
202     }
203
204     %foreach j = numSampleTimes - tid01Eq
205         %assign i = j + tid01Eq
206         /**
207          * Model step logic execution task for sample time %<CompiledModel.SampleTime[i].ClockTickStepSize>.
208          */
209         void working_task%<i>(void *p)
210         {
211             steps_working[%<i>] = 0;
212
213             while(!simulationFinished) {
214                 xSemaphoreTake(sub_rate[%<i>].sem, portMAX_DELAY); /* Sem_val = 1 */
215                 %<LibCallModelStep(i)>\
216                 steps_working[%<i>]++;
217                 xSemaphoreTake(sub_rate[%<i>].sem, portMAX_DELAY);  /* Sem_val = 0 */
218             }
219
220             %% /* In case of shutdown, delete this task */
221             vTaskDelete(NULL);
222         }
223     %endforeach
224
225     %if extMode == 1
226         void ext_mode_comm_task(void* p)
227         {
228             drv_sci_set_crlf_conv_en(FALSE); /* Disable CR->CRLF conversion */
229
230             %<SLibGenERTExtModeInit()>
231             xSemaphoreGive(ext_mode_ready);
232
233             while (rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {
234                 rtExtModeOneStep(rtmGetRTWExtModeInfo(%<modelName>_M), %<numSampleTimes>, (boolean_T *)&rtmGetStopRequested(%<modelName>_M));
235             }
236             rtExtModeShutdown(%<numSampleTimes>);
237             /* In case of shutdown, delete this task */
238             vTaskDelete(NULL);
239         }
240     %endif
241
242     /**
243      * Hardware initialization, task spawning and OS scheduler start.
244      */
245     void main(void)
246     {
247         /* Initialize RPP board */
248          /* Initialize RPP board */
249         %if EXISTS(::rpp_ain_present)
250             rpp_adc_init();
251         %endif
252         %if EXISTS(::rpp_aout_present)
253             rpp_dac_init();
254         %endif
255         %if EXISTS(::rpp_din_present)
256             rpp_din_init();
257         %endif
258         %if EXISTS(::rpp_hbr_present)
259             rpp_hbr_init();
260         %endif
261         %if EXISTS(::rpp_irc_present)
262             rpp_irc_init();
263         %endif
264         %if EXISTS(::rpp_lout_present)
265             rpp_lout_init();
266         %endif
267         %if EXISTS(::rpp_mout_present)
268             rpp_mout_init();
269         %endif
270         %if EXISTS(::rpp_sdr_present)
271             rpp_sdr_init();
272         %endif
273         %if EXISTS(::rpp_gio_in_present) || EXISTS(::rpp_gio_out_present)
274             rpp_gio_init(RPP_GIO_PORT_ALL);
275         %endif
276         rpp_sci_init();
277
278         // Speed up the SCI
279         rpp_sci_setup(115200);
280
281         /* Initialize model */
282         %<LibCallModelInitialize()>\
283
284         %if rppPrintMeta
285             %assign model_info = SPRINTF("'%s' - %s (TLC %s)\\r\\n", LibGetMdlPubHdrBaseName(), TLC_TIME, TLC_VERSION)
286             rpp_sci_printk("%<model_info>");
287         %endif
288
289         %if extMode == 1
290           vSemaphoreCreateBinary(ext_mode_ready);
291           xSemaphoreTake(ext_mode_ready, 0);
292         %endif
293
294         %foreach j = numSampleTimes - tid01Eq
295             %assign i = j + tid01Eq
296             %assign s = CompiledModel.SampleTime[i].PeriodAndOffset[0]
297             %assign o = CompiledModel.SampleTime[i].PeriodAndOffset[1]
298
299             /* Initializing the step semaphore of the loop %<i> */
300             sub_rate[%<i>].sem = xSemaphoreCreateCounting(2, 0);
301             if (sub_rate[%<i>].sem == NULL) {
302                 rpp_sci_printk("ERROR: Can not create semaphore for task %<i>.\r\n");
303                 while (1) ;
304             }
305
306             /* Starting loop %<i> thread for sample time = %<s>s, offset = %<o>s. */
307             if (xTaskCreate(working_task%<i>,
308                             "working_task%<i>",
309                             %<rppModelTaskStack>,
310                             NULL,
311                             WORKING%<i>_PRIORITY,
312                             &sub_rate[%<i>].thread ) != pdPASS) {
313                 rpp_sci_printk("ERROR: Cannot spawn working task %<i>.\r\n");
314                 while (1);
315             }
316         %endforeach
317
318         /* Create tasks to step model and model task */
319
320         if (xTaskCreate(control_task,
321                         "control_task",
322                         %<rppModelTaskStack>,
323                         NULL,
324                         CONTROL_PRIORITY,
325                         NULL) != pdPASS) {
326             rpp_sci_printk("ERROR: Cannot spawn control task.\r\n");
327             while (1);
328         }
329
330         %if extMode == 1
331           /* External mode */
332           rtParseArgsForExtMode(0, NULL);
333
334           if (xTaskCreate(ext_mode_comm_task, "ext_mode_comm_task", 1024, NULL, EXTMODE_PRIORITY, NULL) != pdPASS) {
335             rpp_sci_printk("ERROR: Cannot spawn model task.\r\n");
336             while (1);
337           }
338         %endif
339
340         /* Start FreeRTOS Scheduler */
341         vTaskStartScheduler();
342
343         /* We should never get here */
344         %<LibCallModelTerminate()>\
345         rpp_sci_printk("ERROR: Problem allocating memory for idle task.\r\n");
346         while (1);
347     }
348
349
350     #if configUSE_MALLOC_FAILED_HOOK == 1
351     /**
352      * FreeRTOS malloc() failed hook.
353      */
354      void vApplicationMallocFailedHook(void) {
355        rpp_sci_printk("ERROR: Memory allocation failed.\r\n");
356        while (1);
357      }
358     #endif
359
360
361     #if configCHECK_FOR_STACK_OVERFLOW > 0
362     /**
363      * FreeRTOS stack overflow hook.
364      */
365     void vApplicationStackOverflowHook(xTaskHandle xTask, signed portCHAR *pcTaskName)
366     {
367       rpp_sci_printk("ERROR: Stack overflow : \"%s\".\r\n", pcTaskName);
368       while (1);
369     }
370     #endif
371
372     %closefile tmpBuf
373     %<LibSetSourceFileSection(cFile, "Functions", tmpBuf)>
374     %%%%%%%%
375
376 %endfunction