-
Notifications
You must be signed in to change notification settings - Fork 3
/
rtmain.cpp
1219 lines (1076 loc) · 35.6 KB
/
rtmain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
COPYRIGHT (C) 2003 Lorenzo Dozio (dozio@aero.polimi.it)
Paolo Mantegazza (mantegazza@aero.polimi.it)
Roberto Bucher (roberto.bucher@supsi.ch)
Daniele Gasperini (daniele.gasperini@elet.polimi.it)
Modified August 2009 by Henrik Slotholt (rtai@slotholt.net)
Modified 2014-2016 by Roland Hopferwieser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#define RTAIROS_VERSION "1.1"
#define RTAIROS_NAME "RTAI-ROS"
#define _XOPEN_SOURCE 600
#define DEFAULT_STACKING 30000
#define DEFAULT_CPUMAP 0xF
extern "C" {
#include <popt.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/io.h>
#include <pthread.h>
#include <math.h>
#include <semaphore.h>
#include <unistd.h>
#include "tmwtypes.h"
#include "rtmodel.h"
#include "rt_sim.h"
#include "rt_nonfinite.h"
#include "mdl_info.h"
#include "bio_sig.h"
#include "simstruc.h"
#include <rtai_netrpc.h>
#include <rtai_msg.h>
#include <rtai_mbx.h>
#include <rtai_shm.h>
#include <rtai_sem.h>
#include <rtai_fifos.h>
}
#undef RT // FIX for boost
#include "ros_defines.h"
#include <ros/ros.h>
#define RT
/* Check compatibility of generated code */
#include "build_config.h"
# if COMPAT_VERSION != 1
# error "Generated code is incompatible with this version"
#endif
#define EXPAND_CONCAT(name1,name2) name1 ## name2
#define CONCAT(name1,name2) EXPAND_CONCAT(name1,name2)
#define RT_MODEL CONCAT(MODEL,_rtModel)
#if TID01EQ == 1
#define FIRST_TID 1
#else
#define FIRST_TID 0
#endif
#ifndef RT
# error "must define RT"
#endif
#ifndef MODEL
# error "must define MODEL"
#endif
#ifndef NUMST
# error "must define number of sample times, NUMST"
#endif
#ifndef NCSTATES
# error "must define NCSTATES"
#endif
extern "C" void MdlInitializeSizes(void);
extern "C" void MdlInitializeSampleTimes(void);
extern "C" void MdlStart(void);
extern "C" void MdlOutputs(int_T tid);
extern "C" void MdlUpdate(int_T tid);
extern "C" void MdlTerminate(void);
#define INITIALIZE_SIZES(M) MdlInitializeSizes()
#define INITIALIZE_SAMPLE_TIMES(M) MdlInitializeSampleTimes()
#define START(M) MdlStart()
#define OUTPUTS(M,tid) MdlOutputs(tid)
#define UPDATED(M,tid) MdlUpdate(tid)
#define TERMINATE(M) MdlTerminate()
#if NCSTATES > 0
extern "C" void rt_ODECreateIntegrationData(RTWSolverInfo *si);
extern "C" void rt_ODEUpdateContinuousStates(RTWSolverInfo *si);
#else
#define rt_ODECreateIntegrationData(si) rtsiSetSolverName(si,"FixedStepDiscrete")
#define rt_ODEUpdateContinuousStates(si) rtsiSetT(si,rtsiGetSolverStopTime(si))
#endif
#define XSTR(x) #x
#define STR(x) XSTR(x)
extern "C" RT_MODEL *MODEL(void);
RT_MODEL *rtM;
#define RTAILAB_VERSION "3.5.1"
#define MAX_NTARGETS 1000
#define MAX_NAMES_SIZE 256
#define RUN_FOREVER -1.0
#define POLL_PERIOD 100000000
#define CONNECT_TO_TARGET 0
#define DISCONNECT_TO_TARGET 1
#define START_TARGET 2
#define STOP_TARGET 3
#define UPDATE_PARAM 4
#define MAX_DATA_SIZE 512
#define rt_MainTaskPriority 97
#define rt_HostInterfaceTaskPriority 96
#define rt_RosInterfaceTaskPriority 95
typedef struct rtTargetParamInfo {
char modelName[MAX_NAMES_SIZE];
char blockName[MAX_NAMES_SIZE];
char paramName[MAX_NAMES_SIZE];
unsigned int nRows;
unsigned int nCols;
unsigned int dataType;
unsigned int dataClass;
double dataValue[MAX_DATA_SIZE];
} rtTargetParamInfo;
static sem_t err_sem;
RT_TASK *rt_MainTask;
static pthread_t rt_HostInterfaceThread;
static RT_TASK *rt_HostInterfaceTask;
static pthread_t rt_BaseRateThread;
static RT_TASK *rt_BaseRateTask;
#ifdef MULTITASKING
static pthread_t *rt_SubRateThreads;
static RT_TASK **rt_SubRateTasks;
#endif
static pthread_t rosThread;
const char *HostInterfaceTaskName = "IFTASK";
const char *TargetScopeMbxID = "RTS";
const char *TargetALogMbxID = "RAL";
const char *TargetLogMbxID = "RTL";
const char *TargetLedMbxID = "RTE";
const char *TargetMeterMbxID = "RTM";
const char *TargetSynchronoscopeMbxID = "RTY";
const char *RosTaskID = "ROS";
const char *RosShmID = "SHM";
const char *RosSemID = "SEM";
volatile int Verbose = 0;
static volatile int UseSoftRT = 0;
volatile int WaitToStart = 0;
static volatile int IsRunning = 0;
static volatile int ExternalTimer = 0;
static volatile int OneShot = 0;
static volatile int Priority = 0;
static volatile int CpuMap = 0xF;
static volatile int StackInc = 30000;
static volatile int endBaseRate = 0;
static volatile int endInterface = 0;
static float FinalTime = RUN_FOREVER;
static RTIME rt_BaseRateTick;
#ifdef MULTITASKING
static volatile int endSubRate = 0;
#endif
static int EnableHostInterface = 0;
static int rosInitOptions = ros::init_options::NoSigintHandler;
static volatile int endex;
volatile bool endRos = 0;
static volatile bool startRos = 0;
#ifdef TASKDURATION
RTIME RTTSKinit=0, RTTSKend=0;
#endif
#define MAX_RTAI_SCOPES 1000
#define MAX_RTAI_LOGS 1000
#define MAX_RTAI_LEDS 1000
#define MAX_RTAI_METERS 1000
#define MAX_RTAI_SYNCHS 1000
SimStruct *rtaiScope[MAX_RTAI_SCOPES];
SimStruct *rtaiALog[MAX_RTAI_LOGS];
SimStruct *rtaiLog[MAX_RTAI_LOGS];
SimStruct *rtaiLed[MAX_RTAI_LEDS];
SimStruct *rtaiMeter[MAX_RTAI_METERS];
SimStruct *rtaiSynchronoscope[MAX_RTAI_SYNCHS];
rosBlockConfig_t rosBlockConfigs[MAX_ROS_BLOCKS];
unsigned int numRosBlocks = 0;
const char* rosNode = STR(CONFIG_NODE);
const char* rosNamespace = STR(CONFIG_NAMESPACE);
const char* progDesc = STR(CONFIG_DESCRIPTION);
double rosRate = CONFIG_RATE;
unsigned int pubQueueSize = CONFIG_PUBLISHER_QUEUE_SIZE;
unsigned int subQueueSize = CONFIG_SUBSCRIBER_QUEUE_SIZE;
unsigned int exposeParams = CONFIG_EXPOSE_PARAMS;
#define MAX_COMEDI_DEVICES 10
void *ComediDev[MAX_COMEDI_DEVICES];
int ComediDev_InUse[MAX_COMEDI_DEVICES] = {0};
int ComediDev_AIInUse[MAX_COMEDI_DEVICES] = {0};
int ComediDev_AOInUse[MAX_COMEDI_DEVICES] = {0};
int ComediDev_DIOInUse[MAX_COMEDI_DEVICES] = {0};
/*
static void (*WaitTimingEvent)(unsigned long);
static void (*SendTimingEvent)(unsigned long);
static unsigned long TimingEventArg;
static void DummyWait(void) { }
static void DummySend(void) { }
*/
#include "RosInterface.h"
static inline void strncpyz(char *dest, const char *src, size_t n)
{
if (src != NULL) {
strncpy(dest, src, n);
n = strlen(src);
} else
n = 0;
dest[n] = '\0';
}
/* This function is hacked from /usr/src/linux/include/asm-i386/system.h */
static inline void set_double(double *to, double *from)
{
unsigned long l = ((unsigned long *)from)[0];
unsigned long h = ((unsigned long *)from)[1];
__asm__ __volatile__ (
"1: movl (%0), %%eax; movl 4(%0), %%edx; lock; cmpxchg8b (%0); jnz 1b" : : "D"(to), "b"(l), "c"(h) : "ax", "dx", "memory");
}
#define RT_MODIFY_PARAM_VALUE_IF(rtcase, rttype) \
case rtcase: \
for (paramIdx = 0; paramIdx < nParams; paramIdx++) { \
rttype *param = (rttype *)(pMap[mapOffset + paramIdx]); \
switch (ptinfoGetClass(ptRec)) { \
case rt_SCALAR: \
set_double((double *)param, (double *)_newVal); \
if (Verbose) { \
printf("%s : %G\n", mmiGetBlockTuningBlockName(mmi,i), (double)*param); \
} \
break; \
case rt_VECTOR: \
param[matIdx] = ((double *) _newVal)[0]; \
if (Verbose) { \
for (colIdx = 0; colIdx < nCols; colIdx++) { \
printf("%s : %G\n", mmiGetBlockTuningBlockName(mmi,i), (double)param[colIdx]); \
} \
} \
break; \
case rt_MATRIX_ROW_MAJOR: \
param[matIdx] = ((double *) _newVal)[0]; \
if (Verbose) { \
for (rowIdx = 0; rowIdx < nRows; rowIdx++) { \
for(colIdx = 0; colIdx < nCols; colIdx++){ \
printf("%s : %G\n", mmiGetBlockTuningBlockName(mmi,i), (double)param[rowIdx*nCols+colIdx]); \
} \
} \
} \
break; \
case rt_MATRIX_COL_MAJOR: \
param[matIdx] = ((double *) _newVal)[0]; \
if (Verbose) { \
for (rowIdx = 0; rowIdx < nRows; rowIdx++) { \
for(colIdx = 0; colIdx < nCols; colIdx++) { \
printf("%s : %G\n", mmiGetBlockTuningBlockName(mmi,i), (double)param[colIdx*nRows+rowIdx]); \
} \
} \
} \
break; \
default: \
return(1); \
} \
} \
break;
int_T rt_ModifyParameterValue(void *mpi, int i, int matIdx, void *_newVal)
{
ModelMappingInfo *mmi;
ParameterTuning *ptRec;
void * const *pMap;
uint_T nRows;
uint_T nCols;
uint_T nParams;
uint_T mapOffset;
uint_T paramIdx;
uint_T rowIdx;
uint_T colIdx;
mmi = (ModelMappingInfo *)mpi;
ptRec = (ParameterTuning*)mmiGetBlockTuningParamInfo(mmi,i);
pMap = mmiGetParametersMap(mmi);
nRows = ptinfoGetNumRows(ptRec);
nCols = ptinfoGetNumCols(ptRec);
nParams = ptinfoGetNumInstances(ptRec);
mapOffset = ptinfoGetParametersOffset(ptRec);
switch (ptinfoGetDataTypeEnum(ptRec)) {
RT_MODIFY_PARAM_VALUE_IF(SS_DOUBLE, real_T)
RT_MODIFY_PARAM_VALUE_IF(SS_SINGLE, real32_T)
RT_MODIFY_PARAM_VALUE_IF(SS_INT8, int8_T)
RT_MODIFY_PARAM_VALUE_IF(SS_UINT8, uint8_T)
RT_MODIFY_PARAM_VALUE_IF(SS_INT16, int16_T)
RT_MODIFY_PARAM_VALUE_IF(SS_UINT16, uint16_T)
RT_MODIFY_PARAM_VALUE_IF(SS_INT32, int32_T)
RT_MODIFY_PARAM_VALUE_IF(SS_UINT32, uint32_T)
RT_MODIFY_PARAM_VALUE_IF(SS_BOOLEAN, boolean_T)
default:
return(1);
}
return(0);
}
#define RT_GET_PARAM_INFO_IF(rtcase, rttype) \
case rtcase: \
for (paramIdx = 0; paramIdx < nParams; paramIdx++) { \
rttype *param = (rttype *)(pMap[mapOffset + paramIdx]); \
switch (ptinfoGetClass(ptRec)) { \
case rt_SCALAR: \
rtpi->dataValue[0] = *param; \
break; \
case rt_VECTOR: \
for (colIdx = 0; colIdx < nCols; colIdx++) { \
rtpi->dataValue[colIdx] = param[colIdx]; \
} \
break; \
case rt_MATRIX_ROW_MAJOR: \
for (rowIdx = 0; rowIdx < nRows; rowIdx++) { \
for (colIdx = 0; colIdx < nCols; colIdx++) { \
rtpi->dataValue[rowIdx*nCols+colIdx] = param[rowIdx*nCols+colIdx]; \
} \
} \
break; \
case rt_MATRIX_COL_MAJOR: \
for (rowIdx = 0; rowIdx < nRows; rowIdx++) { \
for (colIdx = 0; colIdx < nCols; colIdx++) { \
rtpi->dataValue[colIdx*nRows+rowIdx] = param[colIdx*nRows+rowIdx]; \
} \
} \
break; \
default: \
return(1); \
} \
} \
break;
int_T rt_GetParameterInfo(void *mpi, rtTargetParamInfo *rtpi, int i)
{
ModelMappingInfo *mmi;
ParameterTuning *ptRec;
void * const *pMap;
uint_T nRows;
uint_T nCols;
uint_T nParams;
uint_T mapOffset;
uint_T paramIdx;
uint_T rowIdx;
uint_T colIdx;
uint_T dataType;
uint_T dataClass;
mmi = (ModelMappingInfo *)mpi;
ptRec = (ParameterTuning*)mmiGetBlockTuningParamInfo(mmi,i);
pMap = mmiGetParametersMap(mmi);
nRows = ptinfoGetNumRows(ptRec);
nCols = ptinfoGetNumCols(ptRec);
nParams = ptinfoGetNumInstances(ptRec);
mapOffset = ptinfoGetParametersOffset(ptRec);
dataType = ptinfoGetDataTypeEnum(ptRec);
dataClass = ptinfoGetClass(ptRec);
strncpyz(rtpi->modelName, STR(MODEL), MAX_NAMES_SIZE);
strncpyz(rtpi->blockName, mmiGetBlockTuningBlockName(mmi,i), MAX_NAMES_SIZE);
strncpyz(rtpi->paramName, mmiGetBlockTuningParamName(mmi,i), MAX_NAMES_SIZE);
rtpi->dataType = dataType;
rtpi->dataClass = dataClass;
rtpi->nRows = nRows;
rtpi->nCols = nCols;
switch (ptinfoGetDataTypeEnum(ptRec)) {
RT_GET_PARAM_INFO_IF(SS_DOUBLE, real_T)
RT_GET_PARAM_INFO_IF(SS_SINGLE, real32_T)
RT_GET_PARAM_INFO_IF(SS_INT8, int8_T)
RT_GET_PARAM_INFO_IF(SS_UINT8, uint8_T)
RT_GET_PARAM_INFO_IF(SS_INT16, int16_T)
RT_GET_PARAM_INFO_IF(SS_UINT16, uint16_T)
RT_GET_PARAM_INFO_IF(SS_INT32, int32_T)
RT_GET_PARAM_INFO_IF(SS_UINT32, uint32_T)
RT_GET_PARAM_INFO_IF(SS_BOOLEAN, boolean_T)
default:
return(1);
}
return(0);
}
#ifdef MULTITASKING
static void *rt_SubRate(int *arg)
{
int sample, i;
char myname[7];
int rt_SubRateTaskPriority;
sample = arg[0];
rt_SubRateTaskPriority = arg[1];
rt_allow_nonroot_hrt();
for (i = 0; i < MAX_NTARGETS; i++) {
sprintf(myname, "TSR%d", i);
if (!rt_get_adr(nam2num(myname))) break;
}
if (!(rt_SubRateTasks[sample] = rt_task_init_schmod(nam2num(myname), rt_SubRateTaskPriority, 0, 0, SCHED_FIFO, CpuMap))) {
printf("Cannot init rt_SubRateTask #%d\n", sample);
return (void *)1;
}
// sem_post(&err_sem);
iopl(3);
rt_task_use_fpu(rt_SubRateTasks[sample], 1);
rt_grow_and_lock_stack(StackInc);
if (!UseSoftRT) {
rt_make_hard_real_time();
}
while (!endSubRate) {
rt_task_suspend(rt_SubRateTasks[sample]);
if (endSubRate) break;
OUTPUTS(rtM, sample);
UPDATED(rtM, sample);
rt_SimUpdateDiscreteTaskTime(rtmGetTPtr(rtM), rtmGetTimingData(rtM), sample);
}
if (!UseSoftRT) {
rt_make_soft_real_time();
}
rt_task_delete(rt_SubRateTasks[sample]);
return (void *)(rt_SubRateTasks[sample] = 0);
}
#endif
static void *rt_BaseRate(void *args)
{
real_T tnext;
char myname[7];
int i;
#ifdef MULTITASKING
int_T sample, *sampleHit = rtmGetSampleHitPtr(rtM);
#endif
int rt_BaseRateTaskPriority = *((int *)args);
rt_allow_nonroot_hrt();
for (i = 0; i < MAX_NTARGETS; i++) {
sprintf(myname, "TBR%d", i);
if (!rt_get_adr(nam2num(myname))) break;
}
if (!(rt_BaseRateTask = rt_task_init_schmod(nam2num(myname), rt_BaseRateTaskPriority, 0, 0, SCHED_FIFO, CpuMap))) {
printf("Cannot init rt_BaseRateTask\n");
return (void *)1;
}
sem_post(&err_sem);
iopl(3);
rt_task_use_fpu(rt_BaseRateTask, 1);
rt_grow_and_lock_stack(StackInc);
if (!UseSoftRT) {
rt_make_hard_real_time();
}
rt_rpc(rt_MainTask,0,(void *)myname);
rt_task_make_periodic(rt_BaseRateTask, rt_get_time() + rt_BaseRateTick, rt_BaseRateTick);
while (!endBaseRate) {
#ifdef TASKDURATION
RTTSKend=rt_get_cpu_time_ns();
#endif
// WaitTimingEvent(TimingEventArg);
if (!ExternalTimer) rt_task_wait_period();
if (endBaseRate) break;
#ifdef TASKDURATION
RTTSKinit=rt_get_cpu_time_ns();
#endif
#ifdef MULTITASKING
tnext = rt_SimUpdateDiscreteEvents(rtmGetNumSampleTimes(rtM), rtmGetTimingData(rtM), rtmGetSampleHitPtr(rtM), rtmGetPerTaskSampleHitsPtr(rtM));
rtsiSetSolverStopTime(rtmGetRTWSolverInfo(rtM), tnext);
for (sample = FIRST_TID + 1; sample < NUMST; sample++) {
if (sampleHit[sample]) {
rt_task_resume(rt_SubRateTasks[sample]);
}
}
OUTPUTS(rtM, FIRST_TID);
UPDATED(rtM, FIRST_TID);
if (rtmGetSampleTime(rtM, 0) == CONTINUOUS_SAMPLE_TIME) {
rt_ODEUpdateContinuousStates(rtmGetRTWSolverInfo(rtM));
} else {
rt_SimUpdateDiscreteTaskTime(rtmGetTPtr(rtM), rtmGetTimingData(rtM), 0);
}
#if FIRST_TID == 1
rt_SimUpdateDiscreteTaskTime(rtmGetTPtr(rtM), rtmGetTimingData(rtM), 1);
#endif
#else
tnext = rt_SimGetNextSampleHit();
rtsiSetSolverStopTime(rtmGetRTWSolverInfo(rtM), tnext);
OUTPUTS(rtM, 0);
UPDATED(rtM, 0);
rt_SimUpdateDiscreteTaskSampleHits(rtmGetNumSampleTimes(rtM), rtmGetTimingData(rtM), rtmGetSampleHitPtr(rtM), rtmGetTPtr(rtM));
if (rtmGetSampleTime(rtM,0) == CONTINUOUS_SAMPLE_TIME) {
rt_ODEUpdateContinuousStates(rtmGetRTWSolverInfo(rtM));
}
#endif
}
if (!UseSoftRT) {
rt_make_soft_real_time();
}
rt_task_delete(rt_BaseRateTask);
return 0;
}
static void *rt_HostInterface(void *args)
{
RT_TASK *task;
unsigned int IRequest;
char Request;
long len;
rt_allow_nonroot_hrt();
if (!(rt_HostInterfaceTask = rt_task_init_schmod(nam2num(HostInterfaceTaskName), rt_HostInterfaceTaskPriority, 0, 0, SCHED_FIFO, 0xFF))) {
printf("Cannot init rt_HostInterfaceTask\n");
return (void *)1;
}
sem_post(&err_sem);
while (!endInterface) {
task = rt_receive(0, &IRequest);
Request = (char)(IRequest);
if (endInterface) break;
switch (Request) {
case 'c': {
ModelMappingInfo *MMI;
uint_T nBlockParams;
{ int Reply;
MMI = (ModelMappingInfo *)rtmGetModelMappingInfo(rtM);
nBlockParams = mmiGetNumBlockParams(MMI);
Reply = (IsRunning << 16) | (nBlockParams & 0xffff); /* max 2^16-1 blocks */
rt_return(task, Reply);
}
{ uint_T i;
rtTargetParamInfo rtParameters;
rt_receivex(task, &rtParameters, sizeof(char), &len);
rt_GetParameterInfo(MMI, &rtParameters, 0);
rt_returnx(task, &rtParameters, sizeof(rtParameters));
for (i = 0; i < nBlockParams; i++) {
rt_receivex(task, &rtParameters, sizeof(char), &len);
rt_GetParameterInfo(MMI, &rtParameters, i);
rt_returnx(task, &rtParameters, sizeof(rtParameters));
}
}
{ int scopeIdx, Reply;
float samplingTime;
int ntraces;
while (1) {
rt_receivex(task, &scopeIdx, sizeof(int), &len);
if (scopeIdx < 0) {
Reply = scopeIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
ntraces = ssGetNumInputPorts(rtaiScope[scopeIdx]);
rt_returnx(task, &ntraces, sizeof(int));
rt_receivex(task, &scopeIdx, sizeof(int), &len);
rt_returnx(task, (char *)ssGetModelName(rtaiScope[scopeIdx]), MAX_NAMES_SIZE*sizeof(char));
while(1) {
int j;
rt_receivex(task, &j, sizeof(int), &len);
if(j < 0) break;
char traceName[10];
sprintf(traceName, "Trace %d", j+1);
rt_returnx(task, traceName, strlen(traceName)+1); // return null terminated string
}
samplingTime = ssGetSampleTime(rtaiScope[scopeIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
{ int logIdx, Reply;
float samplingTime;
int nrow, ncol, *dim;
while (1) {
rt_receivex(task, &logIdx, sizeof(int), &len);
if (logIdx < 0) {
Reply = logIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
dim = ssGetInputPortDimensions(rtaiLog[logIdx],0);
nrow = dim[0];
ncol = dim[1];
rt_returnx(task, &nrow, sizeof(int));
rt_receivex(task, &logIdx, sizeof(int), &len);
rt_returnx(task, &ncol, sizeof(int));
rt_receivex(task, &logIdx, sizeof(int), &len);
rt_returnx(task, (char *)ssGetModelName(rtaiLog[logIdx]), MAX_NAMES_SIZE*sizeof(char));
rt_receivex(task, &logIdx, sizeof(int), &len);
samplingTime = ssGetSampleTime(rtaiLog[logIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
{ int alogIdx, Reply; /* section added to support automatic log block taken from log code */
float samplingTime;
int nrow, ncol, *dim;
while (1) {
rt_receivex(task, &alogIdx, sizeof(int), &len);
if (alogIdx < 0) {
Reply = alogIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
dim = ssGetInputPortDimensions(rtaiALog[alogIdx],0);
nrow = dim[0];
ncol = dim[1];
rt_returnx(task, &nrow, sizeof(int));
rt_receivex(task, &alogIdx, sizeof(int), &len);
rt_returnx(task, &ncol, sizeof(int));
rt_receivex(task, &alogIdx, sizeof(int), &len);
rt_returnx(task, (char *)ssGetModelName(rtaiALog[alogIdx]), MAX_NAMES_SIZE*sizeof(char));
rt_receivex(task, &alogIdx, sizeof(int), &len);
samplingTime = ssGetSampleTime(rtaiALog[alogIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
{ int ledIdx, Reply;
float samplingTime;
int n_leds;
while (1) {
rt_receivex(task, &ledIdx, sizeof(int), &len);
if (ledIdx < 0) {
Reply = ledIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
n_leds = ssGetNumInputPorts(rtaiLed[ledIdx]);
rt_returnx(task, &n_leds, sizeof(int));
rt_receivex(task, &ledIdx, sizeof(int), &len);
rt_returnx(task, (char *)ssGetModelName(rtaiLed[ledIdx]), MAX_NAMES_SIZE*sizeof(char));
rt_receivex(task, &ledIdx, sizeof(int), &len);
samplingTime = ssGetSampleTime(rtaiLed[ledIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
{ int meterIdx, Reply;
float samplingTime;
while (1) {
rt_receivex(task, &meterIdx, sizeof(int), &len);
if (meterIdx < 0) {
Reply = meterIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
rt_returnx(task, (char *)ssGetModelName(rtaiMeter[meterIdx]), MAX_NAMES_SIZE*sizeof(char));
rt_receivex(task, &meterIdx, sizeof(int), &len);
samplingTime = ssGetSampleTime(rtaiMeter[meterIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
{ int synchIdx, Reply;
float samplingTime;
while (1) {
rt_receivex(task, &synchIdx, sizeof(int), &len);
if (synchIdx < 0) {
Reply = synchIdx;
rt_returnx(task, &Reply, sizeof(int));
break;
} else {
rt_returnx(task, (char *)ssGetModelName(rtaiSynchronoscope[synchIdx]), MAX_NAMES_SIZE*sizeof(char));
rt_receivex(task, &synchIdx, sizeof(int), &len);
samplingTime = ssGetSampleTime(rtaiSynchronoscope[synchIdx],0);
rt_returnx(task, &samplingTime, sizeof(float));
}
}
}
break;
}
case 's': { int Reply = 1;
rt_task_resume(rt_MainTask);
rt_return(task, Reply);
break;
}
case 't': { int Reply = 0;
rt_return(task, Reply);
endex = 1;
break;
}
case 'p': { ModelMappingInfo *MMI;
int index;
int Reply;
int matIdx;
double newv;
rt_return(task, IsRunning);
Reply = 0;
rt_receivex(task, &index, sizeof(int), &len);
rt_returnx(task, &Reply, sizeof(int));
Reply = 1;
MMI = (ModelMappingInfo *)rtmGetModelMappingInfo(rtM);
rt_receivex(task, &newv, sizeof(double), &len);
rt_returnx(task, &Reply, sizeof(int));
rt_receivex(task, &matIdx, sizeof(int), &len);
rt_ModifyParameterValue(MMI, index, matIdx, &newv);
rt_returnx(task, &Reply, sizeof(int));
break;
}
case 'g': { uint_T i;
uint_T nBlockParams;
rtTargetParamInfo rtParameters;
ModelMappingInfo *MMI;
rt_return(task, IsRunning);
MMI = (ModelMappingInfo *)rtmGetModelMappingInfo(rtM);
nBlockParams = mmiGetNumBlockParams(MMI);
for (i = 0; i < nBlockParams; i++) {
rt_receivex(task, &rtParameters, sizeof(char), &len);
rt_GetParameterInfo(MMI, &rtParameters, i);
rt_returnx(task, &rtParameters, sizeof(rtParameters));
}
break;
}
case 'd': { int ParamCnt;
int Reply;
rt_return(task, IsRunning);
Reply = 0;
rt_receivex(task, &ParamCnt, sizeof(int), &len);
rt_returnx(task, &Reply, sizeof(int));
{ int i;
ModelMappingInfo *MMI;
struct {
int index;
int mat_index;
double value;
} BatchParams[ParamCnt];
Reply = 1;
MMI = (ModelMappingInfo *)rtmGetModelMappingInfo(rtM);
rt_receivex(task, &BatchParams, sizeof(BatchParams), &len);
for (i = 0; i < ParamCnt; i++) {
rt_ModifyParameterValue(MMI, BatchParams[i].index, BatchParams[i].mat_index, &BatchParams[i].value);
}
}
rt_returnx(task, &ParamCnt, sizeof(int));
break;
}
case 'm': { float ttime = (float)rtmGetT(rtM);
int Reply;
rt_return(task, IsRunning);
rt_receivex(task, &Reply, sizeof(int), &len);
rt_returnx(task, &ttime, sizeof(float));
}
default:
break;
}
}
rt_task_delete(rt_HostInterfaceTask);
return 0;
}
static int_T rt_Main(RT_MODEL * (*model_name)(void), int_T priority)
{
const char *status;
RTIME rt_BaseTaskPeriod;
struct timespec rt_MainTaskPollPeriod = { 0, POLL_PERIOD };
struct timespec err_timeout;
int msg, i;
char myname[7];
SEM *hard_timers_cnt = NULL;
#ifdef MULTITASKING
int sample, *taskarg;
#endif
rt_allow_nonroot_hrt();
for (i = 0; i < MAX_NTARGETS; i++) {
sprintf(myname, "TMN%d", i);
if (!rt_get_adr(nam2num(myname))) break;
}
if (!(rt_MainTask = rt_task_init_schmod(nam2num(myname), rt_MainTaskPriority, 0, 0, SCHED_FIFO, 0xFF))) {
fprintf(stderr, "Cannot init rt_MainTask\n");
return 1;
}
sem_init(&err_sem, 0, 0);
iopl(3);
rt_InitInfAndNaN(sizeof(real_T));
rtM = model_name();
if (rtM == NULL) {
fprintf(stderr, "Memory allocation error during target registration.\n");
goto finish;
}
if (rtmGetErrorStatus(rtM) != NULL) {
fprintf(stderr, "Error during target registration: %s.\n", rtmGetErrorStatus(rtM));
goto finish;
}
if (FinalTime > 0.0 || FinalTime == RUN_FOREVER) {
rtmSetTFinal(rtM, (real_T)FinalTime);
}
INITIALIZE_SIZES(rtM);
INITIALIZE_SAMPLE_TIMES(rtM);
status = rt_SimInitTimingEngine(rtmGetNumSampleTimes(rtM), rtmGetStepSize(rtM), rtmGetSampleTimePtr(rtM), rtmGetOffsetTimePtr(rtM), rtmGetSampleHitPtr(rtM), rtmGetSampleTimeTaskIDPtr(rtM), rtmGetTStart(rtM), &rtmGetSimTimeStep(rtM), &rtmGetTimingData(rtM));
if (status != NULL) {
fprintf(stderr, "Failed to initialize target sample time engine: %s.\n", status);
goto finish;
}
rt_ODECreateIntegrationData(rtmGetRTWSolverInfo(rtM));
START(rtM);
if (rtmGetErrorStatus(rtM) != NULL) {
fprintf(stderr, "Failed in target initialization.\n");
TERMINATE(rtM);
fprintf(stderr, "Target is terminated.\n");
goto finish;
}
if (EnableHostInterface) {
if ((pthread_create(&rt_HostInterfaceThread, NULL, rt_HostInterface, NULL)) != 0) {
fprintf(stderr, "Failed to create HostInterfaceThread.\n");
TERMINATE(rtM);
fprintf(stderr, "Target is terminated.\n");
goto finish;
}
err_timeout.tv_sec = (long int)(time(NULL)) + 1;
err_timeout.tv_nsec = 0;
if ((sem_timedwait(&err_sem, &err_timeout)) != 0) {
TERMINATE(rtM);
fprintf(stderr, "Target is terminated.\n");
goto finish;
}
}
#ifdef MULTITASKING
rt_SubRateTasks = malloc(NUMST*sizeof(RT_TASK *));
rt_SubRateThreads = malloc(NUMST*sizeof(pthread_t));
taskarg = malloc(2*NUMST*sizeof(int));
for (sample = FIRST_TID + 1; sample < NUMST; sample++) {
taskarg[0] = sample;
taskarg[1] = priority + sample;
pthread_create(rt_SubRateThreads + sample, NULL, (void *)rt_SubRate, (void *)taskarg);
taskarg += 2;
}
#endif
if ((pthread_create(&rt_BaseRateThread, NULL, rt_BaseRate, &priority)) != 0) {
fprintf(stderr, "Failed to create BaseRateThread.\n");
endInterface = 1;
if (EnableHostInterface) {
rt_send(rt_HostInterfaceTask, 0);
pthread_join(rt_HostInterfaceThread, NULL);
}
TERMINATE(rtM);
fprintf(stderr, "Target is terminated.\n");
goto finish;
}
err_timeout.tv_sec = (long int)(time(NULL)) + 1;
err_timeout.tv_nsec = 0;
if ((sem_timedwait(&err_sem, &err_timeout)) != 0) {
endInterface = 1;
if (EnableHostInterface) {
rt_send(rt_HostInterfaceTask, 0);
pthread_join(rt_HostInterfaceThread, NULL);
}
TERMINATE(rtM);
fprintf(stderr, "Target is terminated.\n");
goto finish;
}
RosInterface rosInt;
if (ros::master::check()) {
if ((pthread_create(&rosThread, NULL, &RosInterface::thread, &rosInt)) != 0) {
fprintf(stderr, "Failed to create ROS thread.\n");
}
} else {
ROS_ERROR("Failed to contact master [%s]. ROS thread disabled!", ros::master::getURI().c_str());
}
rt_BaseTaskPeriod = (RTIME)(1000000000.0*rtmGetStepSize(rtM));
if (!ExternalTimer) {
// WaitTimingEvent = (void *)rt_task_wait_period;
if (!(hard_timers_cnt = (SEM *)rt_get_adr(nam2num("HTMRCN")))) {
if (OneShot) {
rt_set_oneshot_mode();
start_rt_timer(0);
rt_BaseRateTick = nano2count(rt_BaseTaskPeriod);
} else {
rt_set_periodic_mode();
rt_BaseRateTick = start_rt_timer(nano2count(rt_BaseTaskPeriod));
}
hard_timers_cnt = rt_sem_init(nam2num("HTMRCN"), 0);
} else {
rt_BaseRateTick = nano2count(rt_BaseTaskPeriod);
rt_sem_signal(hard_timers_cnt);
}
} else {
// WaitTimingEvent = (void *)DummyWait;
// SendTimingEvent = (void *)DummySend;
}
if (Verbose) {
int j;
printf("\nTarget info\n");
printf("===========\n");
printf(" Model name : %s\n", STR(MODEL));
printf(" Base sample time : %f [s]\n", rtmGetStepSize(rtM));
printf(" Number of sample times : %d\n", rtmGetNumSampleTimes(rtM));
for (j = 0; j < rtmGetNumSampleTimes(rtM); j++) {
printf(" Sample Time %d : %f [s]\n", j, rtmGetSampleTimePtr(rtM)[j]);
}
printf("\n");
}
if (WaitToStart) {
if (Verbose) {
printf("Target is waiting to start.\n");
}
rt_task_suspend(rt_MainTask);
}
rt_receive(0, &msg);
rt_return(rt_BaseRateTask,0);
IsRunning = 1;
if (Verbose) {
printf("Target is running.\n");
}