4 %% This TLC script generates ert_main.c
7 %% authors: Michal Sojka <sojkam1@fel.cvut.cz>
8 %% Lukas Hamacek <hamacl1@fel.cvut.cz>
10 %% Department of Control Engineering
11 %% Faculty of Electrical Engineering
12 %% Czech Technical University in Prague
15 %% GENERATEDECLARATIONS
16 %% This function generates main function declarations.
19 %assign ::tid01Eq = LibGetTID01EQ()
21 %function generateDeclarations() Output
23 /* Multirate - Multitasking case main file */
24 #define _BSD_SOURCE /* For usleep() */
25 #define _POSIX_C_SOURCE 200112L /* For clock_gettime() & clock_nanosleep() */
26 #include <stdio.h> /* This ert_main.c example uses printf/fflush */
27 #include <pthread.h> /* Thread library header file */
28 #include <sched.h> /* OS scheduler header file */
29 #include <semaphore.h> /* Semaphores library header file */
34 #include <sys/mman.h> /* For mlockall() */
35 #include "%<modelName>.h" /* Model's header file */
36 #include "rtwtypes.h" /* MathWorks types */
38 #include "ext_work.h" /* External mode header file */
51 # error Must specify a model name. Define MODEL=name.
53 /* create generic macros that work with any model */
54 # define EXPAND_CONCAT(name1,name2) name1 ## name2
55 # define CONCAT(name1,name2) EXPAND_CONCAT(name1,name2)
56 # define MODEL_INITIALIZE CONCAT(MODEL,_initialize)
57 # define MODEL_STEP CONCAT(MODEL,_step)
58 # define MODEL_TERMINATE CONCAT(MODEL,_terminate)
59 # define RT_MDL CONCAT(MODEL,_M)
63 #define STRINGIZE(num) #num
64 #define POS(line) __FILE__ ":" STRINGIZE(line)
65 #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);
66 #define CHECKE(expr) do { if ((expr) == -1) { perror(#expr " at " POS(__LINE__)); exit(1); } } while (0);
69 * Maximal priority used by base rate thread.
71 #define MAX_PRIO (sched_get_priority_min(SCHED_FIFO) + %<numSampleTimes>)
74 * Thread handle of the base rate thread.
75 * Fundamental sample time = %<fundamentalStepSize>s
77 pthread_t base_rate_thread;
80 * Thread handles of and semaphores for sub rate threads. The array
81 * is indexed by TID, i.e. the first one or two elements are unused.
82 %foreach i = numSampleTimes
83 %if i == 0 || i == 1 && tid01Eq
86 %assign s = sampleTime%<i>
87 %assign o = offset%<i>
88 * TID%<i>: sample time = %<s>s, offset = %<o>s
94 } sub_rate[%<numSampleTimes>];
97 * Flag if the simulation has been terminated.
99 int simulationFinished = 0;
102 /* Indication that the base rate thread has started */
103 sem_t ext_mode_ready;
107 %function printfunc() Output
108 /% printf("%s\n", __func__); %/
111 %function generateRtOneStep() Output
112 %foreach j = numSampleTimes - 1
114 %if i == 1 && tid01Eq
117 void *sub_rate%<i>(void *arg)
119 while(!simulationFinished) {
120 sem_wait(&sub_rate[%<i>].sem); /* sem_val = 1 */
122 %<modelName>_step%<i>();
123 sem_wait(&sub_rate[%<i>].sem); /* sem_val = 0 */
132 %% This function generates code of the main function function.
134 %function generateMain() Output
136 * This is the thread function of the base rate loop.
137 * Fundamental sample time = %<fundamentalStepSize>s
141 %assign sec = FEVAL("uint32", fundamentalStepSize)
142 %assign nsec = FEVAL("uint32", (fundamentalStepSize - FEVAL("floor", fundamentalStepSize))*1000000000)
143 struct timespec now, next;
144 struct timespec period = { %<sec>, %<nsec> }; /* %<fundamentalStepSize> seconds */
145 boolean_T eventFlags[%<numSampleTimes>]; /* Model has %<numSampleTimes> rates */
146 int_T taskCounter[%<numSampleTimes>] = %<FcnInitializeTaskCounter()>;
147 int_T OverrunFlags[%<numSampleTimes>];
152 %<SLibGenERTExtModeInit()>
153 CHECKE(sem_post(&ext_mode_ready));
156 clock_gettime(CLOCK_MONOTONIC, &next);
158 /* Main loop, running until all the threads are terminated */
159 while(rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {
161 /* Check subrate overrun, set rates that need to run this time step*/
162 %<LibCallSetEventForThisBaseStep("eventFlags")>\
164 /* Trigger sub-rate threads */
165 %foreach i = numSampleTimes
166 %if i == 0 || i == 1 && tid01Eq
169 %assign s = sampleTime%<i>
170 %assign o = offset%<i>
171 /* Sampling rate %<i>, sample time = %<s>, offset = %<o> */
172 if (eventFlags[%<i>]) {
173 eventFlags[%<i>] = FALSE;
174 sem_getvalue(&sub_rate[%<i>].sem, &step_sem_value);
175 if (step_sem_value) {
176 rtmSetErrorStatus(%<modelName>_M, "Overrun");
177 printf("Sub rate %<i> overrun, sample time=%<s>s, offset=%<o>s is too fast\n");
180 sem_post(&sub_rate[%<i>].sem);
181 sem_post(&sub_rate[%<i>].sem);
185 /* Execute base rate step */
186 %if solverMode == "SingleTasking"
189 %<modelName>_step0();
193 rtExtModeCheckEndTrigger();
197 next.tv_sec += period.tv_sec;
198 next.tv_nsec += period.tv_nsec;
199 if (next.tv_nsec >= 1000000000) {
201 next.tv_nsec -= 1000000000;
203 clock_gettime(CLOCK_MONOTONIC, &now);
204 if (now.tv_sec > next.tv_sec ||
205 (now.tv_sec == next.tv_sec && now.tv_nsec > next.tv_nsec)) {
206 uint32_T usec = (now.tv_sec - next.tv_sec) * 1000000 + (now.tv_nsec - next.tv_nsec)/1000;
207 fprintf(stderr, "Base rate (%<fundamentalStepSize>s) overrun by %d us\n", usec);
212 clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);
216 simulationFinished = 1;
218 for (i = %<1 + tid01Eq>; i < %<numSampleTimes>; i++) {
219 sem_post(&sub_rate[i].sem);
220 sem_post(&sub_rate[i].sem);
225 * This is the main function of the model.
226 * Multirate - Multitasking case main file
228 int_T main(int_T argc, const char_T *argv[])
230 const char_T *errStatus;
233 struct sched_param sched_param;
237 /* rtERTExtModeParseArgs(argc, argv); */
238 rtExtModeParseArgs(argc, argv, NULL);
239 CHECKE(sem_init(&ext_mode_ready, 0, 0));
245 CHECKE(mlockall(MCL_CURRENT | MCL_FUTURE));
247 /* Initialize model */
248 %<modelName>_initialize();
249 simulationFinished = 0;
251 /* Prepare task attributes */
252 CHECK0(pthread_attr_init(&attr));
253 CHECK0(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
254 CHECK0(pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
256 %foreach i = numSampleTimes
257 %if i == 0 || i == 1 && tid01Eq
260 %assign s = sampleTime%<i>
261 %assign o = offset%<i>
263 /* Initializing the step semaphore of the loop %<i> */
264 CHECKE(sem_init(&sub_rate[%<i>].sem, 0, 0));
266 /* Starting loop %<i> thread for sample time = %<s>s, offset = %<o>s. */
267 sched_param.sched_priority = MAX_PRIO - %<i>;
268 CHECK0(pthread_attr_setschedparam(&attr, &sched_param));
269 CHECK0(pthread_create(&sub_rate[%<i>].thread, &attr, sub_rate%<i>, (void*)%<i>));
273 /* Starting the base rate thread */
274 sched_param.sched_priority = MAX_PRIO;
275 CHECK0(pthread_attr_setschedparam(&attr, &sched_param));
276 CHECK0(pthread_create(&base_rate_thread, &attr, base_rate, NULL));
277 CHECK0(pthread_attr_destroy(&attr));
281 CHECKE(sem_wait(&ext_mode_ready));
282 while(rtmGetErrorStatus(%<modelName>_M) == NULL && !rtmGetStopRequested(%<modelName>_M)) {
283 rtExtModeOneStep(rtmGetRTWExtModeInfo(RT_MDL), NUMST, (boolean_T *)&rtmGetStopRequested(RT_MDL));
284 usleep(%<FEVAL("uint32", fundamentalStepSize * 1000000)>);
288 /* Wait for threads to finish */
289 pthread_join(base_rate_thread, NULL);
290 %foreach i = numSampleTimes
291 %if i == 0 || i == 1 && tid01Eq
294 pthread_join(sub_rate[%<i>].thread, NULL);
298 rtExtModeShutdown(%<numSampleTimes>);
301 /* Terminate model */
302 %<modelName>_terminate();
304 errStatus = rtmGetErrorStatus(%<modelName>_M);
305 if(errStatus != NULL && strcmp(errStatus, "Simulation finished")) {
306 %%printf("%s\n", rtmGetErrorStatus(%<modelName>_M));
307 if(!strcmp(errStatus, "Overrun")) {
308 printf("ISR overrun - sampling rate too fast\n");
315 /* Local Variables: */
316 /* compile-command: "make -f %<modelName>.mk" */