]> rtime.felk.cvut.cz Git - ert_linux.git/blob - ert_linux/ert_linux_multitasking_main.tlc
aa40ed1d8f32678d27cef2ea4bad0e33112d620a
[ert_linux.git] / ert_linux / ert_linux_multitasking_main.tlc
1 %%\r
2 %% linux_ert_target_multitasking_main.tlc\r
3 %%\r
4 %% description:\r
5 %%  This TLC script generates ert_main for multi-rate / multi-tasking\r
6 %%  case.\r
7 %%\r
8 %% date: 3nd Feb 2009\r
9 %%\r
10 %% author: Lukas Hamacek, Michal Sojka\r
11 %% e-mail: hamacl1@fel.cvut.cz\r
12 %% Department of Control Engineering\r
13 %% Faculty of Electrical Engineering\r
14 %% Czech Technical University in Prague\r
15 %%\r
16 %% modifications:\r
17 %%  2009/2/3 - Lukas Hamacek\r
18 %%      creation of the file\r
19 %%\r
20 \r
21 %% GENERATEDECLARATIONS\r
22 %%  This function generates main function declarations.\r
23 %%\r
24 \r
25 %assign ::tid01Eq = LibGetTID01EQ()\r
26 \r
27 %function generateDeclarations() Output\r
28 \r
29   /* Multirate - Multitasking case main file */\r
30   #define _POSIX_C_SOURCE 199309L        /* For clock_gettime() */\r
31   #include <stdio.h>                     /* This ert_main.c example uses printf/fflush */\r
32   #include <pthread.h>                   /* Thread library header file */\r
33   #include <sched.h>                     /* OS scheduler header file */\r
34   #include <semaphore.h>                 /* Semaphores library header file */\r
35   #include <time.h>\r
36   #include <stdlib.h>\r
37   #include "%<modelName>.h"              /* Model's header file */\r
38   #include "rtwtypes.h"                  /* MathWorks types */\r
39   %if extMode == 1\r
40     #include "ext_work.h"                  /* External mode header file */\r
41   %endif\r
42 \r
43   /*==================*\r
44    * Required defines *\r
45    *==================*/\r
46 \r
47   #ifndef MODEL\r
48   # error Must specify a model name.  Define MODEL=name.\r
49   #else\r
50   /* create generic macros that work with any model */\r
51   # define EXPAND_CONCAT(name1,name2) name1 ## name2\r
52   # define CONCAT(name1,name2) EXPAND_CONCAT(name1,name2)\r
53   # define MODEL_INITIALIZE CONCAT(MODEL,_initialize)\r
54   # define MODEL_STEP       CONCAT(MODEL,_step)\r
55   # define MODEL_TERMINATE  CONCAT(MODEL,_terminate)\r
56   # define RT_MDL           CONCAT(MODEL,_M)\r
57   #endif\r
58 \r
59   /* Error checking */\r
60   #define STRINGIZE(num) #num\r
61   #define POS(line) __FILE__ ":" STRINGIZE(line)\r
62   #define CHECK0(expr) do { int __err = (expr); if (__err) { fprintf(stderr, "Error: %s returned '%s' at " POS(__LINE__) "\n", #expr, strerror(__err)); exit(1); } } while (0);\r
63   #define CHECKE(expr) do { if ((expr) == -1) { perror(#expr " at " POS(__LINE__)); exit(1); } } while (0);\r
64 \r
65   /**\r
66    * Maximal priority used by base rate thread.\r
67    */\r
68   #define MAX_PRIO (sched_get_priority_min(SCHED_FIFO) + %<numSampleTimes>)\r
69 \r
70   /**\r
71    * Thread handle of the base rate thread.\r
72    * Fundamental sample time = %<fundamentalStepSize>s\r
73    */\r
74   pthread_t base_rate_thread;\r
75 \r
76   /**\r
77    * Thread handles of and semaphores for sub rate threads. The array\r
78    * is indexed by TID, i.e. the first one or two elements are unused.\r
79   %foreach i = numSampleTimes\r
80       %if i == 0 || i == 1 && tid01Eq\r
81       %continue\r
82     %endif\r
83     %assign s = sampleTime%<i>\r
84     %assign o = offset%<i>\r
85    * TID%<i>: sample time = %<s>s, offset = %<o>s\r
86   %endforeach\r
87    */\r
88   struct sub_rate {\r
89   pthread_t thread;\r
90   sem_t     sem;\r
91   } sub_rate[%<numSampleTimes>];\r
92 \r
93   /**\r
94    * Flag if the simulation has been terminated.\r
95    */\r
96   int simulationFinished = 0;\r
97 \r
98 %endfunction\r
99 \r
100 %function printfunc() Output\r
101   /% printf("%s\n", __func__); %/\r
102 %endfunction\r
103 \r
104 %function generateRtOneStep() Output\r
105   %foreach j = numSampleTimes - 1\r
106     %assign i = j + 1\r
107     %if i == 1 && tid01Eq\r
108       %continue\r
109     %endif\r
110     void *sub_rate%<i>(void *arg)\r
111     {\r
112       while(!simulationFinished) {\r
113         sem_wait(&sub_rate[%<i>].sem);    /* sem_val = 1 */\r
114         %<printfunc()>\r
115         %<modelName>_step%<i>();\r
116         sem_wait(&sub_rate[%<i>].sem);    /* sem_val = 0 */\r
117       }\r
118     }\r
119   %endforeach\r
120 %endfunction\r
121 \r
122 \r
123 %% GENERATEMAIN\r
124 %%  This function generates code of the main function function.\r
125 %%\r
126 %function generateMain() Output\r
127   /**\r
128    * This is the thread function of the main loop.\r
129    * Fundamental sample time = %<fundamentalStepSize>s\r
130    */\r
131   void * base_rate()\r
132   {\r
133     %assign  sec = FEVAL("uint32", fundamentalStepSize)\r
134     %assign nsec = FEVAL("uint32", (fundamentalStepSize - FEVAL("floor", fundamentalStepSize))*1000000000)\r
135     struct timespec now, next;\r
136     struct timespec period = { %<sec>, %<nsec> }; /* %<fundamentalStepSize> seconds */\r
137     boolean_T eventFlags[%<numSampleTimes>];             /* Model has %<numSampleTimes> rates */\r
138     int_T taskCounter[%<numSampleTimes>] = %<FcnInitializeTaskCounter()>;\r
139     int_T OverrunFlags[%<numSampleTimes>];\r
140     int step_sem_value;\r
141     int_T i;\r
142 \r
143     %if extMode == 1\r
144       %<SLibGenERTExtModeInit()>\r
145     %endif\r
146 \r
147     clock_gettime(CLOCK_MONOTONIC, &next);\r
148 \r
149     /* Main loop, running until all the threads are terminated */\r
150     while(rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {\r
151       %<printfunc()>\r
152       /* Check subrate overrun, set rates that need to run this time step*/\r
153       %<LibCallSetEventForThisBaseStep("eventFlags")>\\r
154 \r
155       /* Trigger sub-rate threads */\r
156       %foreach i = numSampleTimes\r
157         %if i == 0 || i == 1 && tid01Eq\r
158           %continue\r
159         %endif\r
160         %assign s = sampleTime%<i>\r
161         %assign o = offset%<i>\r
162         /* Sampling rate %<i>, sample time = %<s>, offset = %<o> */\r
163         if (eventFlags[%<i>]) {\r
164           eventFlags[%<i>] = FALSE;\r
165           sem_getvalue(&sub_rate[%<i>].sem, &step_sem_value);\r
166           if (step_sem_value) {\r
167             rtmSetErrorStatus(%<modelName>_M, "Overrun");\r
168             printf("Sub rate %<i> overrun, sample time=%<s>s, offset=%<o>s is too fast\n");\r
169             break;\r
170           }\r
171           sem_post(&sub_rate[%<i>].sem);\r
172           sem_post(&sub_rate[%<i>].sem);\r
173         }\r
174       %endforeach\r
175 \r
176       /* Execute base rate step */\r
177       %<modelName>_step0();\r
178 \r
179       %if extMode == 1\r
180         rtExtModeCheckEndTrigger();\r
181         rtExtModeOneStep(rtmGetRTWExtModeInfo(RT_MDL),\r
182                          NUMST,\r
183                          (boolean_T *)&rtmGetStopRequested(RT_MDL));\r
184       %endif\r
185 \r
186       next.tv_sec += period.tv_sec;\r
187       next.tv_nsec += period.tv_nsec;\r
188       if (next.tv_nsec >= 1000000000) {\r
189         next.tv_sec++;\r
190         next.tv_nsec -= 1000000000;\r
191       }\r
192       clock_gettime(CLOCK_MONOTONIC, &now);\r
193       if (now.tv_sec > next.tv_sec ||\r
194           (now.tv_sec == next.tv_sec && now.tv_nsec > next.tv_nsec)) {\r
195             uint64_T nsec = (now.tv_sec - next.tv_sec) * 1000000000 + now.tv_nsec - next.tv_nsec;\r
196             fprintf(stderr, "Base rate (%<fundamentalStepSize>s) overrun by %d us\n", (int)(nsec/1000));\r
197       }\r
198       clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);\r
199 \r
200     }\r
201 \r
202     simulationFinished = 1;\r
203     /* Final step */\r
204     for (i = %<1 + tid01Eq>; i < %<numSampleTimes>; i++) {\r
205       sem_post(&sub_rate[i].sem);\r
206       sem_post(&sub_rate[i].sem);\r
207     }\r
208   }\r
209 \r
210   /**\r
211    * This is the main function of the model.\r
212    * Multirate - Multitasking case main file\r
213    */\r
214   int_T main(int_T argc, const char_T *argv[])\r
215   {\r
216     const char_T *errStatus;\r
217     int_T i;\r
218     pthread_attr_t attr;\r
219     struct sched_param sched_param;\r
220 \r
221     %if extMode == 1\r
222       /* External mode */\r
223       rtERTExtModeParseArgs(argc, argv);\r
224     %else\r
225       (void)(argc);\r
226       (void *)(argv);\r
227     %endif\r
228 \r
229     /* Initialize model */\r
230     %<modelName>_initialize();\r
231     simulationFinished = 0;\r
232 \r
233     CHECK0(pthread_attr_init(&attr));\r
234     CHECK0(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));\r
235     CHECK0(pthread_attr_setschedpolicy(&attr, SCHED_FIFO));\r
236 \r
237     %foreach i = numSampleTimes\r
238       %if i == 0 || i == 1 && tid01Eq\r
239         %continue\r
240       %endif\r
241       %assign s = sampleTime%<i>\r
242       %assign o = offset%<i>\r
243 \r
244       /* Initializing the step semaphore of the loop %<i> */\r
245       CHECKE(sem_init(&sub_rate[%<i>].sem, 0, 0));\r
246 \r
247       /* Starting loop %<i> thread for sample time = %<s>s, offset = %<o>s. */\r
248       sched_param.sched_priority = MAX_PRIO - %<i>;\r
249       CHECK0(pthread_attr_setschedparam(&attr, &sched_param));\r
250       CHECK0(pthread_create(&sub_rate[%<i>].thread, &attr, sub_rate%<i>, (void*)%<i>));\r
251 \r
252     %endforeach\r
253 \r
254     /* Starting the main loop */\r
255     sched_param.sched_priority = MAX_PRIO;\r
256     CHECK0(pthread_attr_setschedparam(&attr, &sched_param));\r
257     CHECK0(pthread_create(&base_rate_thread, &attr, base_rate, NULL));\r
258 \r
259     /* Wait for threads to finish */\r
260     CHECK0(pthread_attr_destroy(&attr));\r
261     pthread_join(base_rate_thread, NULL);\r
262     %foreach i = numSampleTimes\r
263       %if i == 0 || i == 1 && tid01Eq\r
264         %continue\r
265       %endif\r
266       pthread_join(sub_rate[%<i>].thread, NULL);\r
267     %endforeach\r
268 \r
269     %if extMode == 1\r
270       rtExtModeShutdown(%<numSampleTimes>);\r
271     %endif\r
272 \r
273     /* Terminate model */\r
274     %<modelName>_terminate();\r
275 \r
276     errStatus = rtmGetErrorStatus(%<modelName>_M);\r
277     if(errStatus != NULL && strcmp(errStatus, "Simulation finished")) {\r
278       %%printf("%s\n", rtmGetErrorStatus(%<modelName>_M));\r
279       if(!strcmp(errStatus, "Overrun")) {\r
280         printf("ISR overrun - sampling rate too fast\n");\r
281       }\r
282       return(1);\r
283     }\r
284     return 0;\r
285   }\r
286 \r
287 /* Local Variables: */\r
288 /* compile-command: "make -f %<modelName>.mk" */\r
289 /* End: */\r
290 \r
291 %endfunction\r