-
Notifications
You must be signed in to change notification settings - Fork 16
/
BlockFactory.cpp
857 lines (742 loc) · 28.1 KB
/
BlockFactory.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
/*
* Copyright (C) 2018 Istituto Italiano di Tecnologia (IIT)
* All rights reserved.
*
* This software may be modified and distributed under the terms of the
* GNU Lesser General Public License v2.1 or any later version.
*/
#define S_FUNCTION_LEVEL 2
#define S_FUNCTION_NAME BlockFactory
#include "BlockFactory/Core/Block.h"
#include "BlockFactory/Core/FactorySingleton.h"
#include "BlockFactory/Core/Log.h"
#include "BlockFactory/Core/Parameter.h"
#include "BlockFactory/Core/Parameters.h"
#include "BlockFactory/Simulink/SimulinkBlockInformation.h"
#include <matrix.h>
#include <simstruc.h>
#include <simstruc_types.h>
#include <sl_sample_time_defs.h>
#include <tmwtypes.h>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
static const size_t NumPWork = 2;
const bool ForwardLogsToStdErr = true;
static void catchLogMessages(bool status, SimStruct* S);
static blockfactory::core::ClassFactorySingleton::ClassFactoryPtr
getFactoryForThisBlockType(SimStruct* S);
// ==========
// S-FUNCTION
// ==========
// Function: MDL_CHECK_PARAMETERS
#define MDL_CHECK_PARAMETERS
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
static void mdlCheckParameters(SimStruct* S)
{
UNUSED_ARG(S);
// TODO: still to find a way to call Block implementation
}
#endif /*MDL_CHECK_PARAMETERS*/
#define MDL_SET_INPUT_PORT_DIMENSION_INFO
static void mdlSetInputPortDimensionInfo(SimStruct* S, int_T port, const DimsInfo_T* dimsInfo)
{
// If the port is set as dynamic and the proposed dimension is not dynamic (hence calculated by
// the signal propagation) accept it
if (ssGetInputPortWidth(S, port) == DYNAMICALLY_SIZED) {
if (dimsInfo->width != DYNAMICALLY_SIZED) {
if (!ssSetInputPortDimensionInfo(S, port, dimsInfo)) {
bfError << "Failed to set proposed sizes.";
catchLogMessages(false, S);
return;
}
}
}
}
#define MDL_SET_OUTPUT_PORT_DIMENSION_INFO
static void mdlSetOutputPortDimensionInfo(SimStruct* S, int_T port, const DimsInfo_T* dimsInfo)
{
// If the port is set as dynamic and the proposed dimension is not dynamic (hence calculated by
// the signal propagation) accept it
if (ssGetOutputPortWidth(S, port) == DYNAMICALLY_SIZED) {
if (dimsInfo->width != DYNAMICALLY_SIZED) {
if (!ssSetOutputPortDimensionInfo(S, port, dimsInfo)) {
bfError << "Failed to set proposed sizes.";
catchLogMessages(false, S);
return;
}
}
}
}
// Function: mdlInitializeSizes ===============================================
// Abstract:
// The sizes information is used by Simulink to determine the S-function
// block's characteristics (number of inputs, s, states, etc.).
static void mdlInitializeSizes(SimStruct* S)
{
// Initialize the Log singleton
blockfactory::core::Log::getSingleton().clear();
if (ssGetSFcnParamsCount(S) < 1) {
bfError << "The block type parameter must be specified";
catchLogMessages(false, S);
return;
}
// Get the factory object from the singleton
auto factory = getFactoryForThisBlockType(S);
if (!factory) {
bfError << "Failed to get the factory";
catchLogMessages(false, S);
return;
}
// Allocate the block from the factory. Since this object is supposed to be deleted
// by the end of this function scope, SharedLibraryClass can be used and provides RAII.
shlibpp::SharedLibraryClass<blockfactory::core::Block> block(*factory);
// Notify errors
if (!block.isValid()) {
std::string className(mxArrayToString(ssGetSFcnParam(S, 0)));
bfError << "Could not create an object of type " + className;
catchLogMessages(false, S);
return;
}
// We cannot save data in PWork during the initializeSizes phase.
// Two PWorks:
// 0: pointer to a Block implementation
// 1: pointer to a BlockInformation implementation
ssSetNumPWork(S, NumPWork);
// Setup the block parameters' properties
ssSetNumSFcnParams(S, block->numberOfParameters());
ssSetSFcnParamTunable(S, 0, false);
for (unsigned i = 0; i < ssGetNumSFcnParams(S); ++i) {
bool tunable = block->parameterAtIndexIsTunable(i);
ssSetSFcnParamTunable(S, i, tunable);
}
#if defined(MATLAB_MEX_FILE)
if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) {
mdlCheckParameters(S);
if (ssGetErrorStatus(S)) {
catchLogMessages(false, S);
return;
}
}
else {
int_T numOfExpectedParams = ssGetNumSFcnParams(S);
int_T numOfBlockParams = ssGetSFcnParamsCount(S);
bfError << "Number of parameters (" << numOfBlockParams
<< ") different from those expected (" << numOfExpectedParams << ")";
catchLogMessages(false, S);
return;
}
#endif
blockfactory::mex::SimulinkBlockInformation blockInfo(S);
bool ok = block->configureSizeAndPorts(&blockInfo);
catchLogMessages(ok, S);
if (!ok) {
return;
}
for (auto i = 0; i < ssGetNumInputPorts(S); ++i) {
// Set explicitly the inputs port to be SS_NOT_REUSABLE_AND_GLOBAL (which actually
// is already the default value). Since the toolbox supports contiguous input signals,
// this option should not be changed.
ssSetInputPortOptimOpts(S, i, SS_NOT_REUSABLE_AND_GLOBAL);
// Set input signals to be allocated in a contiguous memory storage
ssSetInputPortRequiredContiguous(S, i, true);
}
ssSetNumSampleTimes(S, 1);
ssSetSimStateCompliance(S, USE_CUSTOM_SIM_STATE); //??
ssSetNumDiscStates(S, block->numberOfDiscreteStates());
ssSetNumContStates(S, 0); // block->numberOfContinuousStates());
uint_T options = SS_OPTION_WORKS_WITH_CODE_REUSE | SS_OPTION_EXCEPTION_FREE_CODE
| SS_OPTION_ALLOW_INPUT_SCALAR_EXPANSION | SS_OPTION_USE_TLC_WITH_ACCELERATOR
| SS_OPTION_CALL_TERMINATE_ON_EXIT;
// also ?
// SS_OPTION_RUNTIME_EXCEPTION_FREE_CODE
std::vector<std::string> additionalOptions = block->additionalBlockOptions();
for (const auto& additionalOption : additionalOptions) {
double option;
if (!blockInfo.optionFromKey(additionalOption, option)) {
bfError << "Failed to get option from key.";
catchLogMessages(false, S);
return;
}
// Store the parsed option
options |= static_cast<uint32_t>(option);
}
// Set the options
ssSetOptions(S, options);
}
// Function: mdlInitializeSampleTimes =========================================
// Abstract:
// This function is used to specify the sample time(s) for your
// S-function. You must register the same number of sample times as
// specified in ssSetNumSampleTimes.
static void mdlInitializeSampleTimes(SimStruct* S)
{
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
ssSetModelReferenceSampleTimeDefaultInheritance(S);
}
// Function: mdlStart =======================================================
// Abstract:
// This function is called once at start of model execution. If you
// have states that should be initialized once, this is the place
// to do it.
#define MDL_START
static void mdlStart(SimStruct* S)
{
// Get the factory object from the singleton
auto factory = getFactoryForThisBlockType(S);
if (!factory) {
bfError << "Failed to get the factory";
catchLogMessages(false, S);
return;
}
// Allocate the block from the factory and store its pointer in the PWork
blockfactory::core::Block* block = factory->create();
ssSetPWorkValue(S, 0, block);
// Allocate the BlockInformation object and store its pointer in the PWork
blockfactory::core::BlockInformation* blockInfo =
new blockfactory::mex::SimulinkBlockInformation(S);
ssSetPWorkValue(S, 1, blockInfo);
if (!block || !blockInfo) {
bfError << "Failed to create objects before storing them in the PWork.";
catchLogMessages(false, S);
return;
}
// Increase the reference counter of the factory
// NOTE: the counter starts at 1!
factory->addRef();
// Call the initialize() method
bool ok = block->initialize(blockInfo);
catchLogMessages(ok, S);
}
#define MDL_UPDATE
#if defined(MDL_UPDATE) && defined(MATLAB_MEX_FILE)
static void mdlUpdate(SimStruct* S, int_T tid)
{
UNUSED_ARG(tid);
if (ssGetNumPWork(S) != NumPWork) {
bfError << "PWork should contain " << NumPWork << " elements.";
catchLogMessages(false, S);
return;
}
// Get the Block object
blockfactory::core::Block* block =
static_cast<blockfactory::core::Block*>(ssGetPWorkValue(S, 0));
// Get the SimulinkBlockInformation object
blockfactory::mex::SimulinkBlockInformation* blockInfo;
blockInfo = static_cast<blockfactory::mex::SimulinkBlockInformation*>(ssGetPWorkValue(S, 1));
if (!block || !blockInfo) {
bfError << "Failed to get pointers from the PWork vector.";
catchLogMessages(false, S);
return;
}
// Call the updateDiscreteState() method
bool ok = block->updateDiscreteState(blockInfo);
catchLogMessages(ok, S);
}
#endif
// Initialize the state vectors of this C MEX S-function
#define MDL_INITIALIZE_CONDITIONS
#if defined(MDL_INITIALIZE_CONDITIONS) && defined(MATLAB_MEX_FILE)
static void mdlInitializeConditions(SimStruct* S)
{
if (ssGetNumPWork(S) != NumPWork) {
bfError << "PWork should contain " << NumPWork << " elements.";
catchLogMessages(false, S);
return;
}
// Get the Block object
blockfactory::core::Block* block =
static_cast<blockfactory::core::Block*>(ssGetPWorkValue(S, 0));
// Get the SimulinkBlockInformation object
blockfactory::mex::SimulinkBlockInformation* blockInfo;
blockInfo = static_cast<blockfactory::mex::SimulinkBlockInformation*>(ssGetPWorkValue(S, 1));
if (!block || !blockInfo) {
bfError << "Failed to get pointers from the PWork vector.";
catchLogMessages(false, S);
return;
}
// Call the initializeInitialConditions() method
bool ok = block->initializeInitialConditions(blockInfo);
catchLogMessages(ok, S);
}
#endif
#define MDL_DERIVATIVES
#if defined(MDL_DERIVATIVES) && defined(MATLAB_MEX_FILE)
static void mdlDerivatives(SimStruct* /*S*/)
{
/* Add mdlDerivatives code here */
}
#endif
// Function: mdlOutputs =======================================================
// Abstract:
// In this function, you compute the outputs of your S-function
// block.
static void mdlOutputs(SimStruct* S, int_T tid)
{
UNUSED_ARG(tid);
if (ssGetNumPWork(S) != NumPWork) {
bfError << "PWork should contain " << NumPWork << " elements.";
catchLogMessages(false, S);
return;
}
// Get the Block object
blockfactory::core::Block* block =
static_cast<blockfactory::core::Block*>(ssGetPWorkValue(S, 0));
// Get the SimulinkBlockInformation object
blockfactory::mex::SimulinkBlockInformation* blockInfo;
blockInfo = static_cast<blockfactory::mex::SimulinkBlockInformation*>(ssGetPWorkValue(S, 1));
if (!block || !blockInfo) {
bfError << "Failed to get pointers from the PWork vector.";
catchLogMessages(false, S);
return;
}
// Call the output() method
bool ok = block->output(blockInfo);
catchLogMessages(ok, S);
}
static void mdlTerminate(SimStruct* S)
{
if (!ssGetPWork(S)) {
return;
}
if (ssGetNumPWork(S) != NumPWork) {
bfError << "PWork should contain " << NumPWork << " elements.";
catchLogMessages(false, S);
return;
}
// Get the Block object
blockfactory::core::Block* block =
static_cast<blockfactory::core::Block*>(ssGetPWorkValue(S, 0));
// Get the SimulinkBlockInformation object
blockfactory::mex::SimulinkBlockInformation* blockInfo;
blockInfo = static_cast<blockfactory::mex::SimulinkBlockInformation*>(ssGetPWorkValue(S, 1));
// Get the factory object from the singleton
auto factory = getFactoryForThisBlockType(S);
// TODO:
assert(factory);
if (!factory) {
bfError << "Failed to get the factory";
catchLogMessages(false, S);
return;
}
// If the block exist, delete it.
// Note that it might not exist, e.g. when the initialization fails not all blocks
// are created, but in any case the terminate method is called for all of them.
if (factory && block) {
if (block->terminate(blockInfo)) {
// Delete the block using the factory
factory->destroy(block);
block = nullptr;
// NOTE: The counter starts at 1. This means that when it is equal to 1
// all the classes allocated from this factory have been destroyed.
factory->removeRef();
if (factory->getReferenceCount() == 1) {
// Only this object and the one inside the singleton
assert(factory.use_count() == 2);
factory.reset();
const std::string className(mxArrayToString(ssGetSFcnParam(S, 0)));
const std::string blockLibraryName(mxArrayToString(ssGetSFcnParam(S, 1)));
// Delete the factory object
if (!blockfactory::core::ClassFactorySingleton::getInstance().destroyFactory(
{blockLibraryName, className})) {
bfError << "Failed to destroy the factory";
catchLogMessages(false, S);
// Do not return since other actions need to be performed
}
}
}
else {
bfError << "Failed to terminate block.";
catchLogMessages(false, S);
// Do not return since other actions need to be performed
}
}
// Delete the BlockInformation object from the PWork vector
delete blockInfo;
// Clean the PWork vector
ssSetPWorkValue(S, 0, nullptr);
ssSetPWorkValue(S, 1, nullptr);
// Report warnings if any
catchLogMessages(true, S);
}
// ===============
// UTILS FUNCTIONS
// ===============
static void catchLogMessages(bool status, SimStruct* S)
{
// Initialize static buffers
const unsigned bufferLen = 1024;
std::string prefix{};
#ifndef NDEBUG
// Get the path of the block
const char_T* blockPath = ssGetPath(S);
prefix = "\n==> ";
prefix += blockPath;
#endif // NDEBUG
// Notify warnings
if (!blockfactory::core::Log::getSingleton().getWarnings().empty()) {
// Get the warnings
std::string warningMsg = prefix + blockfactory::core::Log::getSingleton().getWarnings();
// Trim the message if needed
if (warningMsg.length() >= bufferLen) {
warningMsg = warningMsg.substr(0, bufferLen - 1);
}
// Forward to Simulink
char warningBuffer[bufferLen];
sprintf(warningBuffer, "%s", warningMsg.c_str());
ssWarning(S, warningBuffer);
if (ForwardLogsToStdErr) {
fprintf(stderr, "%s", warningBuffer);
}
// Clean the notified warnings
blockfactory::core::Log::getSingleton().clearWarnings();
}
// Notify errors
if (!status) {
// Get the errors
std::string errorMsg = prefix + blockfactory::core::Log::getSingleton().getErrors();
// Trim the message if needed
if (errorMsg.length() >= bufferLen) {
errorMsg = errorMsg.substr(0, bufferLen - 1);
}
// Forward to Simulink
char errorBuffer[bufferLen];
sprintf(errorBuffer, "%s", errorMsg.c_str());
ssSetErrorStatus(S, errorBuffer);
if (ForwardLogsToStdErr) {
fprintf(stderr, "%s", errorBuffer);
}
// Clean the notified errors
blockfactory::core::Log::getSingleton().clearErrors();
return;
}
}
static blockfactory::core::ClassFactorySingleton::ClassFactoryPtr
getFactoryForThisBlockType(SimStruct* S)
{
// Get the class name and the library name from the parameter
const std::string className(mxArrayToString(ssGetSFcnParam(S, 0)));
const std::string blockLibraryName(mxArrayToString(ssGetSFcnParam(S, 1)));
// Get the block factory
auto factory = blockfactory::core::ClassFactorySingleton::getInstance().getClassFactory(
{blockLibraryName, className});
if (!factory) {
bfError << "Failed to get factory object (className=" << className
<< ",libName=" << blockLibraryName << ")";
return {};
}
if (!factory->isValid()) {
bfError << "Factory error (" << static_cast<std::uint32_t>(factory->getStatus())
<< "): " << factory->getError().c_str();
return {};
}
return factory;
}
// =============
// RTW FUNCTIONS
// =============
#if defined(MATLAB_MEX_FILE)
#define MDL_RTW
template <typename T>
std::vector<real_T> toRTWNumericVector(const std::vector<T>& vectorInput)
{
std::vector<real_T> output;
output.reserve(vectorInput.size());
output.assign(vectorInput.begin(), vectorInput.end());
return output;
}
std::string toRTWStringVector(const std::vector<std::string>& stringInput)
{
std::string output;
for (unsigned i = 0; i < stringInput.size(); ++i) {
if (i == 0) {
output += "[\"" + stringInput[i] + "\"";
}
else {
output += ", \"" + stringInput[i] + "\"";
}
}
output += "]";
return output;
}
const std::pair<std::string, std::string>
parameterTypeToString(const blockfactory::core::ParameterType& type)
{
switch (type) {
case blockfactory::core::ParameterType::INT:
return {"ParameterType::INT", "int"};
case blockfactory::core::ParameterType::BOOL:
return {"ParameterType::BOOL", "bool"};
case blockfactory::core::ParameterType::DOUBLE:
return {"ParameterType::DOUBLE", "double"};
case blockfactory::core::ParameterType::STRING:
return {"ParameterType::STRING", "std::string"};
case blockfactory::core::ParameterType::CELL_INT:
return {"ParameterType::CELL_INT", "int"};
case blockfactory::core::ParameterType::CELL_BOOL:
return {"ParameterType::CELL_BOOL", "bool"};
case blockfactory::core::ParameterType::CELL_DOUBLE:
return {"ParameterType::CELL_DOUBLE", "double"};
case blockfactory::core::ParameterType::CELL_STRING:
return {"ParameterType::CELL_STRING", "std::string"};
case blockfactory::core::ParameterType::STRUCT_INT:
return {"ParameterType::STRUCT_INT", "int"};
case blockfactory::core::ParameterType::STRUCT_BOOL:
return {"ParameterType::STRUCT_BOOL", "bool"};
case blockfactory::core::ParameterType::STRUCT_DOUBLE:
return {"ParameterType::STRUCT_DOUBLE", "double"};
case blockfactory::core::ParameterType::STRUCT_STRING:
return {"ParameterType::STRUCT_STRING", "std::string"};
case blockfactory::core::ParameterType::STRUCT_CELL_INT:
return {"ParameterType::STRUCT_CELL_INT", "int"};
case blockfactory::core::ParameterType::STRUCT_CELL_BOOL:
return {"ParameterType::STRUCT_CELL_BOOL", "bool"};
case blockfactory::core::ParameterType::STRUCT_CELL_DOUBLE:
return {"ParameterType::STRUCT_CELL_DOUBLE", "double"};
case blockfactory::core::ParameterType::STRUCT_CELL_STRING:
return {"ParameterType::STRUCT_CELL_STRING", "std::string"};
}
return {};
}
template <typename T>
bool writeParameterToRTW(const blockfactory::core::Parameter<T> param, SimStruct* S)
{
if (param.getMetadata().cols == blockfactory::core::ParameterMetadata::DynamicSize
|| param.getMetadata().rows == blockfactory::core::ParameterMetadata::DynamicSize) {
bfError << "Storing in the rtw file dynamically-sized parameters is not supported.";
return false;
}
if (param.isScalar()) {
return ssWriteRTWParamSettings(
S,
8,
SSWRITE_VALUE_NUM,
"index",
static_cast<real_T>(param.getMetadata().index),
SSWRITE_VALUE_QSTR,
"name",
param.getMetadata().name.c_str(),
SSWRITE_VALUE_NUM,
"isScalar",
static_cast<real_T>(param.isScalar()),
SSWRITE_VALUE_NUM,
"rows",
static_cast<real_T>(param.getMetadata().rows),
SSWRITE_VALUE_NUM,
"cols",
static_cast<real_T>(param.getMetadata().cols),
SSWRITE_VALUE_QSTR,
"type",
parameterTypeToString(param.getMetadata().type).first.c_str(),
SSWRITE_VALUE_QSTR,
"storage",
parameterTypeToString(param.getMetadata().type).second.c_str(),
SSWRITE_VALUE_NUM,
"valueScalar",
static_cast<real_T>(param.getScalarParameter()));
}
else {
const std::vector<real_T> vectorRealT = toRTWNumericVector(param.getVectorParameter());
return ssWriteRTWParamSettings(
S,
8,
SSWRITE_VALUE_NUM,
"index",
static_cast<real_T>(param.getMetadata().index),
SSWRITE_VALUE_QSTR,
"name",
param.getMetadata().name.c_str(),
SSWRITE_VALUE_NUM,
"isScalar",
static_cast<real_T>(param.isScalar()),
SSWRITE_VALUE_NUM,
"rows",
static_cast<real_T>(param.getMetadata().rows),
SSWRITE_VALUE_NUM,
"cols",
static_cast<real_T>(param.getMetadata().cols),
SSWRITE_VALUE_QSTR,
"type",
parameterTypeToString(param.getMetadata().type).first.c_str(),
SSWRITE_VALUE_QSTR,
"storage",
parameterTypeToString(param.getMetadata().type).second.c_str(),
SSWRITE_VALUE_VECT,
"valueVector",
vectorRealT.data(),
param.getVectorParameter().size());
}
}
// Specialize the template for std::string
template <>
bool writeParameterToRTW(const blockfactory::core::Parameter<std::string> param, SimStruct* S)
{
if (param.getMetadata().cols == blockfactory::core::ParameterMetadata::DynamicSize
|| param.getMetadata().rows == blockfactory::core::ParameterMetadata::DynamicSize) {
bfError << "Storing in the rtw file dynamically-sized parameters is not supported.";
return false;
}
if (param.isScalar()) {
return ssWriteRTWParamSettings(
S,
8,
SSWRITE_VALUE_NUM,
"index",
static_cast<real_T>(param.getMetadata().index),
SSWRITE_VALUE_QSTR,
"name",
param.getMetadata().name.c_str(),
SSWRITE_VALUE_NUM,
"isScalar",
static_cast<real_T>(param.isScalar()),
SSWRITE_VALUE_NUM,
"rows",
static_cast<real_T>(param.getMetadata().rows),
SSWRITE_VALUE_NUM,
"cols",
static_cast<real_T>(param.getMetadata().cols),
SSWRITE_VALUE_QSTR,
"type",
parameterTypeToString(param.getMetadata().type).first.c_str(),
SSWRITE_VALUE_QSTR,
"storage",
parameterTypeToString(param.getMetadata().type).second.c_str(),
SSWRITE_VALUE_QSTR,
"valueScalar",
param.getScalarParameter().c_str());
}
else {
const std::string serializedVectorOfStrings = toRTWStringVector(param.getVectorParameter());
return ssWriteRTWParamSettings(
S,
8,
SSWRITE_VALUE_NUM,
"index",
static_cast<real_T>(param.getMetadata().index),
SSWRITE_VALUE_QSTR,
"name",
param.getMetadata().name.c_str(),
SSWRITE_VALUE_NUM,
"isScalar",
static_cast<real_T>(param.isScalar()),
SSWRITE_VALUE_NUM,
"rows",
static_cast<real_T>(param.getMetadata().rows),
SSWRITE_VALUE_NUM,
"cols",
static_cast<real_T>(param.getMetadata().cols),
SSWRITE_VALUE_QSTR,
"type",
parameterTypeToString(param.getMetadata().type).first.c_str(),
SSWRITE_VALUE_QSTR,
"storage",
parameterTypeToString(param.getMetadata().type).second.c_str(),
SSWRITE_VALUE_VECT_STR,
"valueVector",
serializedVectorOfStrings.c_str(),
param.getMetadata().cols);
}
}
bool writeRTW(SimStruct* S, const blockfactory::core::Parameters& params)
{
// RTW Parameters record metadata
// ==============================
// The first entry in the parameter record (SFcnParamSettings[0]) contains
// information useful to parse the others
// Get the number or parameters
const unsigned numberOfParameters = params.getNumberOfParameters();
// Get the class name
std::string className;
params.getParameter("className", className);
// Get the plugin library name
std::string libName;
params.getParameter("libName", libName);
// Create the record
ssWriteRTWParamSettings(S,
3,
SSWRITE_VALUE_NUM,
"numberOfParameters",
static_cast<real_T>(numberOfParameters),
SSWRITE_VALUE_QSTR,
"className",
className.c_str(),
SSWRITE_VALUE_QSTR,
"libName",
libName.c_str());
// RTW Parameters
// ==============
bool ok = true;
for (const auto& param : params.getIntParameters()) {
ok = ok && writeParameterToRTW(param, S);
}
for (const auto& param : params.getBoolParameters()) {
ok = ok && writeParameterToRTW(param, S);
}
for (const auto& param : params.getDoubleParameters()) {
ok = ok && writeParameterToRTW(param, S);
}
for (const auto& param : params.getStringParameters()) {
ok = ok && writeParameterToRTW(param, S);
}
if (!ok) {
bfError << "Failed to write parameters to RTW file.";
return false;
}
return true;
}
static void mdlRTW(SimStruct* S)
{
if (ssGetNumPWork(S) > 0 && ssGetPWork(S)) {
// Get the block object from the PWork
blockfactory::core::Block* block =
static_cast<blockfactory::core::Block*>(ssGetPWorkValue(S, 0));
bool ok;
blockfactory::core::Parameters params;
if (!block) {
bfError << "Unable to get the class from the PWork vector.";
catchLogMessages(false, S);
return;
}
// Get the parameters from the block
ok = block->getParameters(params);
catchLogMessages(ok, S);
if (!ok) {
bfError << "Failed to get parameters from the block during the code "
<< "generation process";
catchLogMessages(false, S);
return;
}
// Use parameters metadata to populate the rtw file used by the coder
ok = writeRTW(S, params);
catchLogMessages(ok, S);
if (!ok) {
bfError << "Failed to write parameters to the RTW file during the code "
<< "generation process";
catchLogMessages(false, S);
return;
}
// Store the PWork vector in the rtw file
ok = ssWriteRTWWorkVect(S, "PWork", 1, "blockPWork", ssGetNumPWork(S));
catchLogMessages(ok, S);
if (!ok) {
bfError << "Failed to store the PWork vector during the code "
<< "generation process";
catchLogMessages(false, S);
return;
}
}
}
#endif
// Required S-function trailer
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include <simulink.c> /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif