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