How to create FMU slave and initialise FMU in C using Modelica's fmi headers - c

I'm creating a simple FMI demo system to try out FMI where I have 1 simulator connected to an FMU which computes the state of the system (represented as a number calculated from a closed-form equation) and another FMU that controls the system via a parameter in the closed-form equation. So the system looks something like
FMU-system <--> Simulator <--> FMU-control
In every iteration, I'm updating the system state based on 1 equation, and passing it to the control, which returns a parameter to be passed to the system.
I'm using FMI 2.0.3, and have read the specification. Right now I have 3 files, 1 to act as a simulator and 2 to act as the FMUs. But I'm having difficulties with the implementation of the FMUs and the initialisation of the simulator.
To initialise the FMU, my understanding is I need to call fmi2Instantiate which has this signature.
fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuResourceLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn);
But I don't know what to pass in the function for the GUID, resource location and callback function. How should I implement the callback function and initialisation?
Then to implement the FMU, my understanding is I need to implement fmi2SetReal, fmi2GetReal and fmi2DoStep, but I can't figure out how to implement them in terms of code. These are the signatures
fmi2Status setReal(fmi2Component c, fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
fmi2Status getReal(fmi2Component c, fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
fmi2Status doStep(fmi2Component c, fmi2Real currentCommunicationPoint, fmi2Real communicationStepSize, fmi2Boolean noSetFMUStatePriorToCurrentPoint)
But I can't figure out how to implement these functions. Is fmi2Component c meaningless here? And I suppose I have to do the system state computation for the FMU-system in doStep. How should I update the state and pass the code here?
Sorry if this is too many questions but I was trying to look for a tutorial too and I couldn't find any.

https://github.com/traversaro/awesome-fmi
This is a curated list of Functional Mock-up Interface (FMI) libraries, tools and resources.
There are non commercial tools available. Check them out, you will get idea to implement these functions for your application.

A good starting point to implement FMI support are the open source Reference FMUs (which recently also got a simple FMU simulator) and fmpy:
https://github.com/CATIA-Systems/FMPy
https://github.com/modelica/Reference-FMUs/tree/main/fmusim

Related

LLVM Loop Simplify Pass

I am probably misunderstanding some basic concept how LLVM & passes work, anyhow here is my question:
I am currently working on a pass where I extend the runOnModule (https://llvm.org/doxygen/classllvm_1_1ModulePass.html) function. I would like to run LoopSimplify first on the IR, but I do not seem to understand how to do that. There is a run(Function &F, FunctionAnalysisManager &AM) function as described on https://llvm.org/doxygen/classllvm_1_1LoopSimplifyPass.html and as far as I understand it I can call it on every function in my module. But for that I need a member of that class (LoopSimplify) to call it on which I do not know where to get from and also some FunctionAnalysisManager. What are they for and how do they need to look like? It is not like I can just feed it some empty constructs right?
I want to do this for the following guarantee:
"Loop pre-header insertion guarantees that there is a single, non-critical
entry edge from outside of the loop to the loop header. This simplifies a
number of analyses and transformations, such as LICM." as described in https://llvm.org/doxygen/LoopSimplify_8h_source.html.
While I support the directions to integrate your pass into using the pass manager, nonetheless, there is a way to force LoopSimplify to run by making your pass require it. This is also used in many of the LLVM provided passes, such as Scalar/LoopVersioningLICM.cpp
// This header includes LoopSimplifyID as an extern
#include "llvm/Transforms/Utils.h"
...
void YourPass::getAnalysisUsage(AnalysisUsage& AU) const {
AU.addRequiredID(LoopSimplifyID);
}
Doing so will force the pass to be run prior to your pass, no need to invoke it. However, if you need interface with this or another pass, you can request its analysis:
getAnalysis<LoopSimplifyPass>(F); // Where F is a function&

How to design generic backward compatible API for embedded software application library interface in C?

I am tasked to assist with the design of a dynamic library (exposed with a C interface) aimed to be used in embed software application on various embed platform (Android,Windows,Linux).
Main requirements are speed , and decoupling.
For the decoupling part : one of our requirement is to be able to facilitate integration and so permit backward compatibility and resilience.
My library have some entry points that should be called by the integrating software (like an initialize constructor to provide options as where to log, how to behave etc...) and could also call some callback in the application (an event to inform when task is finished).
So I have come with several propositions but as each of one not seems great I am searching advice on a better or standard ways to achieve decoupling an d backward compatibility than this 3 ways that I have come up :
First an option that I could think of is to have a generic interface call for my exposed entry points for example with a hashmap of key/values for the parameters of my functions so in pseudo code it gives something like :
myLib.Initialize(Key_Value_Option_Array_Here);
Another option is to provide a generic function to provide all the options to the library :
myLib.SetOption(Key_Of_Option, Value_OfOption);
myLib.SetCallBack(Key_Of_Callbak, FunctionPointer);
When presenting my option my collegue asked me why not use a google protobuf argument as interface between the library and the embed software : but it seems weird to me, as their will be a performance hit on each call for serialization and deserialization.
Are there any more efficient or standard way that you coud think of?
You could have a struct for optional arguments:
typedef struct {
uint8_t optArg1;
float optArg2;
} MyLib_InitOptArgs_T;
void MyLib_Init(int16_t arg1, uint32_t arg2, MyLib_InitOptArgs_T const * optionalArgs);
Then you could use compound literals on function call:
MyLib_Init(1, 2, &(MyLib_InitOptArgs_T){ .optArg2=1.2f });
All non-specified values would have zero-ish value (0, NULL, NaN), and would be considered unused. Similarly, when passing NULL for struct pointer, all optional arguments would be considered unused.
Downside with this method is that if you expect to have many new arguments in the future, structure could grow too big. But whether that is an issue, depends on what your limits are.
Another option is to simply have multiple smaller initialization functions for initializating different subsystems. This could be combined with the optional arguments system above.

Difference between Data_Wrap_Struct and TypedData_Wrap_Struct?

I'm wrapping a C struct in a Ruby C extension but I can't find the differente between Data_Wrap_Struct and TypedData_Wrap_Struct in the docs, what's the difference between the two functions?
It's described pretty well in the official documentation.
The tl;dr is that Data_Wrap_Struct is deprecated and just lets you set the class and the mark/free functions for the wrapped data. TypedData_Wrap_Struct instead lets you set the class and then takes a pointer to a rb_data_type_struct structure that allows for more advanced options to be set for the wrapping:
the mark/free functions as before, but also
an internal label to identify the wrapped type
a function for calculating memory consumption
arbitrary data (basically letting you wrap data at a class level)
additional flags for garbage collection optimization
Check my unofficial documentation for a couple examples of how this is used.

How to insert print for each function of C language for debugging?

I am studying and debugging one software. There are thousands of functions in this software. I plan to add printf() at the entry and exit point of each function. It will take a lot of time.
Is there one tool/script to do this?
I may use '__cyg_profile_func_enter'. But it can only get address. But I have to run another script to get function name. I also hope to get value of input parameters of this function too.
You should give a try to AOP : Aspect Oriented Programming. Personnaly I've only tried with Java and Spring AOP but there's an API for C too : AspectC (https://sites.google.com/a/gapp.msrg.utoronto.ca/aspectc/home). From what I've seen, it's not the only one.
From what I've red about this library, you can add an pointcut before compiling with AspectC :
// before means it's a before function aspect
// call means it's processed when a function is called
// args(...) means it applies to any function with any arguments
// this->funcName is the name of the function handled by AspectC
before(): call(args(...)) {
printf("Entering %s\n", this->funcName);
}
(not tried by myself but extracted from the reference page https://sites.google.com/a/gapp.msrg.utoronto.ca/aspectc/tutorial)
This is only a basic overview of what can be done and you still have to deal with the compilation (documented in the page linked before) but it looks like it could possibly help you. Give a try with a simple POC maybe.

Using Windows Forms and VC++ with Unmanaged Static Libraries

I am currently trying to write a UI for a Data Acquistion System in Visual Studio C++ 2010, and I am having a lot of trouble dealing with the interfacing of the third party libraries I am using and Windows Forms. The two libraries I am using are DAQX, a C library for a Data Acqustion System, and VITCam, a C++ library for a 1394 High Speed Camera. It's extremely frustrating trying to work with these libraries and any UI library that VS has to offer, as none of the function arguments ever get along.
DAQX uses windows types like WORD and DWORD, in normal C fashion, and when I'm writing a normal program, no UI involved, it works fine, but Windows Forms seems to hate anytime I want to make a simple DWORD Array inside the class.
VITCam is even worse. I can open the camera fine, but I am completely lost when it comes to trying to put the image on the screen somehow. I haven't uncovered an equivalanet, easy to follow way for putting it to the screen as to how the documentation puts it:
CDC* pDC=GetDC(); // obtain the device context for your window...
// move the image data
::SetDIBitsToDevice(pDC->m_hDC,0,0,
(int) (MyCam.GetDispBuf()->bmiHeader.biWidth),
(int) (MyCam.GetDispBuf()->bmiHeader.biHeight),
0,0,0,(WORD) (WORD) MyCam.GetDispBuf()->bmiHeader.biHeight,
MyCam.GetDispPixels(),MyCam.GetDispBuf(),
DIB_RGB_COLORS);
I can barely follow it as is. So, without doing to much blathering, How do most people work with static unmanaged libraries that were not developed with Windows Forms in mind? I've tried MFC as the VITCam documentations mentioned it, but it makes very little sense and isn't as intuitive as Windows Forms feels.
Edit:
This is the error message I get when trying to use a normal (at least to me) array.
Error 1 error C4368: cannot define 'buffer' as a member of managed 'WirelessHeadImpact::Form1': mixed types are not supported
And it points to this line:
private:
WORD buffer[BUFFSIZE*CHANCOUNT];
What I had before was this:
static array<WORD>^ _buffer;
And within a function I create the former array, pass it to the function, then return the latter after looping through and updating the array.
WORD buffer[BUFFSIZE*CHANCOUNT];
DWORD scansCollected = 0;
while (total_scans < SCANS) {
daqAdcTransferBufData(_handle, buffer, BUFFSIZE, DabtmWait, &scansCollected);
if (scansCollected > 0) {
for (WORD i=0;i<scansCollected;i++) {
_buffer[i] = buffer[i];
}
mixed type support is removed in Visual C++ 2005. If you want to associate a DWORD array to a managed class, use new (not gcnew) to allocate the array itself on the native heap and save the pointer of the array in the class.
by the way, you cannot pass addresses of objects on the managed heap to a native function without pinning the object, otherwise the GC is free to move the object at any time. If you want to pass a managed value to a native function, make sure your pass by value or the object is pinned.
It helps the readers if you post the actual error message you are getting, instead of having to guess out from your question.

Resources