]> rtime.felk.cvut.cz Git - pes-rpp/rpp-simulink.git/blob - rpp/rpp/rpp_mrmain.tlc
Do not exit when overrun is detected
[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                         %% Commented out so that overrun does stop the whole execution
171                         %% rtmSetErrorStatus(%<modelName>_M, "Overrun");
172                         overrun_flag = TRUE;
173                         break;
174                     }
175                     if (xSemaphoreGive(sub_rate[i].sem) == pdFALSE) {
176                         rpp_sci_printk("ERROR: Task %d semaphore 1 give.\n", i);
177                         while (1) ;
178                     }
179                     if (xSemaphoreGive(sub_rate[i].sem) == pdFALSE) {
180                         rpp_sci_printk("ERROR: Task %d semaphore 2 give.\n", i);
181                         while (1) ;
182                     }
183                 }
184               }
185
186             steps_control++;
187
188             %if extMode == 1
189               rtExtModeCheckEndTrigger();
190             %endif
191
192         }
193         simulationFinished = 1;
194
195         /* Final step */
196         for (i = %<tid01Eq>; i < NUM_SAMPLE_TIMES; i++) {
197             xSemaphoreGive(sub_rate[i].sem);
198             xSemaphoreGive(sub_rate[i].sem);
199         }
200
201         /* In case of shutdown, delete this task */
202         vTaskDelete(NULL);
203     }
204
205     %foreach j = numSampleTimes - tid01Eq
206         %assign i = j + tid01Eq
207         /**
208          * Model step logic execution task for sample time %<CompiledModel.SampleTime[i].ClockTickStepSize>.
209          */
210         void working_task%<i>(void *p)
211         {
212             steps_working[%<i>] = 0;
213
214             while(!simulationFinished) {
215                 xSemaphoreTake(sub_rate[%<i>].sem, portMAX_DELAY); /* Sem_val = 1 */
216                 %<LibCallModelStep(i)>\
217                 steps_working[%<i>]++;
218                 xSemaphoreTake(sub_rate[%<i>].sem, portMAX_DELAY);  /* Sem_val = 0 */
219             }
220
221             %% /* In case of shutdown, delete this task */
222             vTaskDelete(NULL);
223         }
224     %endforeach
225
226     %if extMode == 1
227         void ext_mode_comm_task(void* p)
228         {
229             drv_sci_set_crlf_conv_en(FALSE); /* Disable CR->CRLF conversion */
230
231             %<SLibGenERTExtModeInit()>
232             xSemaphoreGive(ext_mode_ready);
233
234             while (rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {
235                 rtExtModeOneStep(rtmGetRTWExtModeInfo(%<modelName>_M), %<numSampleTimes>, (boolean_T *)&rtmGetStopRequested(%<modelName>_M));
236             }
237             rtExtModeShutdown(%<numSampleTimes>);
238             /* In case of shutdown, delete this task */
239             vTaskDelete(NULL);
240         }
241     %endif
242
243     /**
244      * Hardware initialization, task spawning and OS scheduler start.
245      */
246     void main(void)
247     {
248         /* Initialize RPP board */
249          /* Initialize RPP board */
250         %if EXISTS(::rpp_ain_present)
251             rpp_adc_init();
252         %endif
253         %if EXISTS(::rpp_aout_present)
254             rpp_dac_init();
255         %endif
256         %if EXISTS(::rpp_din_present)
257             rpp_din_init();
258         %endif
259         %if EXISTS(::rpp_hbr_present)
260             rpp_hbr_init();
261         %endif
262         %if EXISTS(::rpp_irc_present)
263             rpp_irc_init();
264         %endif
265         %if EXISTS(::rpp_lout_present)
266             rpp_lout_init();
267         %endif
268         %if EXISTS(::rpp_mout_present)
269             rpp_mout_init();
270         %endif
271         %if EXISTS(::rpp_sdr_present)
272             rpp_sdr_init();
273         %endif
274         %if EXISTS(::rpp_gio_in_present) || EXISTS(::rpp_gio_out_present)
275             rpp_gio_init(RPP_GIO_PORT_ALL);
276         %endif
277         rpp_sci_init();
278
279         // Speed up the SCI
280         rpp_sci_setup(115200);
281
282         /* Initialize model */
283         %<LibCallModelInitialize()>\
284
285         %if rppPrintMeta
286             %assign model_info = SPRINTF("'%s' - %s (TLC %s)\\r\\n", LibGetMdlPubHdrBaseName(), TLC_TIME, TLC_VERSION)
287             rpp_sci_printk("%<model_info>");
288         %endif
289
290         %if extMode == 1
291           vSemaphoreCreateBinary(ext_mode_ready);
292           xSemaphoreTake(ext_mode_ready, 0);
293         %endif
294
295         %foreach j = numSampleTimes - tid01Eq
296             %assign i = j + tid01Eq
297             %assign s = CompiledModel.SampleTime[i].PeriodAndOffset[0]
298             %assign o = CompiledModel.SampleTime[i].PeriodAndOffset[1]
299
300             /* Initializing the step semaphore of the loop %<i> */
301             sub_rate[%<i>].sem = xSemaphoreCreateCounting(2, 0);
302             if (sub_rate[%<i>].sem == NULL) {
303                 rpp_sci_printk("ERROR: Can not create semaphore for task %<i>.\r\n");
304                 while (1) ;
305             }
306
307             /* Starting loop %<i> thread for sample time = %<s>s, offset = %<o>s. */
308             if (xTaskCreate(working_task%<i>,
309                             "working_task%<i>",
310                             %<rppModelTaskStack>,
311                             NULL,
312                             WORKING%<i>_PRIORITY,
313                             &sub_rate[%<i>].thread ) != pdPASS) {
314                 rpp_sci_printk("ERROR: Cannot spawn working task %<i>.\r\n");
315                 while (1);
316             }
317         %endforeach
318
319         /* Create tasks to step model and model task */
320
321         if (xTaskCreate(control_task,
322                         "control_task",
323                         %<rppModelTaskStack>,
324                         NULL,
325                         CONTROL_PRIORITY,
326                         NULL) != pdPASS) {
327             rpp_sci_printk("ERROR: Cannot spawn control task.\r\n");
328             while (1);
329         }
330
331         %if extMode == 1
332           /* External mode */
333           rtParseArgsForExtMode(0, NULL);
334
335           if (xTaskCreate(ext_mode_comm_task, "ext_mode_comm_task", 1024, NULL, EXTMODE_PRIORITY, NULL) != pdPASS) {
336             rpp_sci_printk("ERROR: Cannot spawn model task.\r\n");
337             while (1);
338           }
339         %endif
340
341         /* Start FreeRTOS Scheduler */
342         vTaskStartScheduler();
343
344         /* We should never get here */
345         %<LibCallModelTerminate()>\
346         rpp_sci_printk("ERROR: Problem allocating memory for idle task.\r\n");
347         while (1);
348     }
349
350
351     #if configUSE_MALLOC_FAILED_HOOK == 1
352     /**
353      * FreeRTOS malloc() failed hook.
354      */
355      void vApplicationMallocFailedHook(void) {
356        rpp_sci_printk("ERROR: Memory allocation failed.\r\n");
357        while (1);
358      }
359     #endif
360
361
362     #if configCHECK_FOR_STACK_OVERFLOW > 0
363     /**
364      * FreeRTOS stack overflow hook.
365      */
366     void vApplicationStackOverflowHook(xTaskHandle xTask, signed portCHAR *pcTaskName)
367     {
368       rpp_sci_printk("ERROR: Stack overflow : \"%s\".\r\n", pcTaskName);
369       while (1);
370     }
371     #endif
372
373     %closefile tmpBuf
374     %<LibSetSourceFileSection(cFile, "Functions", tmpBuf)>
375     %%%%%%%%
376
377 %endfunction