]> rtime.felk.cvut.cz Git - ert_linux.git/blob - ert_linux/ert_linux_multitasking_main.tlc
Fix/add some comments
[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       next.tv_sec += period.tv_sec;\r
185       next.tv_nsec += period.tv_nsec;\r
186       if (next.tv_nsec >= 1000000000) {\r
187         next.tv_sec++;\r
188         next.tv_nsec -= 1000000000;\r
189       }\r
190       clock_gettime(CLOCK_MONOTONIC, &now);\r
191       if (now.tv_sec > next.tv_sec ||\r
192           (now.tv_sec == next.tv_sec && now.tv_nsec > next.tv_nsec)) {\r
193             uint64_T nsec = (now.tv_sec - next.tv_sec) * 1000000000 + now.tv_nsec - next.tv_nsec;\r
194             fprintf(stderr, "Base rate (%<fundamentalStepSize>s) overrun by %d us\n", (int)(nsec/1000));\r
195       }\r
196       clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);\r
197 \r
198     }\r
199 \r
200     simulationFinished = 1;\r
201     /* Final step */\r
202     for (i = %<1 + tid01Eq>; i < %<numSampleTimes>; i++) {\r
203       sem_post(&sub_rate[i].sem);\r
204       sem_post(&sub_rate[i].sem);\r
205     }\r
206   }\r
207 \r
208   /**\r
209    * This is the main function of the model.\r
210    * Multirate - Multitasking case main file\r
211    */\r
212   int_T main(int_T argc, const char_T *argv[])\r
213   {\r
214     const char_T *errStatus;\r
215     int_T i;\r
216     pthread_attr_t attr;\r
217     struct sched_param sched_param;\r
218 \r
219     %if extMode == 1\r
220       /* External mode */\r
221       rtERTExtModeParseArgs(argc, argv);\r
222     %else\r
223       (void)(argc);\r
224       (void *)(argv);\r
225     %endif\r
226 \r
227     /* Initialize model */\r
228     %<modelName>_initialize();\r
229     simulationFinished = 0;\r
230 \r
231     /* Prepare task attributes */\r
232     CHECK0(pthread_attr_init(&attr));\r
233     CHECK0(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));\r
234     CHECK0(pthread_attr_setschedpolicy(&attr, SCHED_FIFO));\r
235 \r
236     %foreach i = numSampleTimes\r
237       %if i == 0 || i == 1 && tid01Eq\r
238         %continue\r
239       %endif\r
240       %assign s = sampleTime%<i>\r
241       %assign o = offset%<i>\r
242 \r
243       /* Initializing the step semaphore of the loop %<i> */\r
244       CHECKE(sem_init(&sub_rate[%<i>].sem, 0, 0));\r
245 \r
246       /* Starting loop %<i> thread for sample time = %<s>s, offset = %<o>s. */\r
247       sched_param.sched_priority = MAX_PRIO - %<i>;\r
248       CHECK0(pthread_attr_setschedparam(&attr, &sched_param));\r
249       CHECK0(pthread_create(&sub_rate[%<i>].thread, &attr, sub_rate%<i>, (void*)%<i>));\r
250 \r
251     %endforeach\r
252 \r
253     /* Starting the base rate thread */\r
254     sched_param.sched_priority = MAX_PRIO;\r
255     CHECK0(pthread_attr_setschedparam(&attr, &sched_param));\r
256     CHECK0(pthread_create(&base_rate_thread, &attr, base_rate, NULL));\r
257     CHECK0(pthread_attr_destroy(&attr));\r
258 \r
259     %if extMode == 1\r
260       /* External mode */\r
261       while(rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {\r
262         rtExtModeOneStep(rtmGetRTWExtModeInfo(RT_MDL), NUMST, (boolean_T *)&rtmGetStopRequested(RT_MDL));\r
263         usleep(%<FEVAL("uint32", fundamentalStepSize * 1000000)>);\r
264       }\r
265     %endif\r
266 \r
267     /* Wait for threads to finish */\r
268     pthread_join(base_rate_thread, NULL);\r
269     %foreach i = numSampleTimes\r
270       %if i == 0 || i == 1 && tid01Eq\r
271         %continue\r
272       %endif\r
273       pthread_join(sub_rate[%<i>].thread, NULL);\r
274     %endforeach\r
275 \r
276     %if extMode == 1\r
277       rtExtModeShutdown(%<numSampleTimes>);\r
278     %endif\r
279 \r
280     /* Terminate model */\r
281     %<modelName>_terminate();\r
282 \r
283     errStatus = rtmGetErrorStatus(%<modelName>_M);\r
284     if(errStatus != NULL && strcmp(errStatus, "Simulation finished")) {\r
285       %%printf("%s\n", rtmGetErrorStatus(%<modelName>_M));\r
286       if(!strcmp(errStatus, "Overrun")) {\r
287         printf("ISR overrun - sampling rate too fast\n");\r
288       }\r
289       return(1);\r
290     }\r
291     return 0;\r
292   }\r
293 \r
294 /* Local Variables: */\r
295 /* compile-command: "make -f %<modelName>.mk" */\r
296 /* End: */\r
297 \r
298 %endfunction\r