remove arbitrary files

parent ad3d7f5f
<?xml version="1.0" encoding="UTF-8"?>
<fmiModelDescription fmiVersion="2.0" modelName="bip_example" guid="123456789" description="LEC" generationTool="Manually" generationDateAndTime="2022-02-24T12:43:32Z">
<CoSimulation modelIdentifier="bip_example" needsExecutionTool="true" canBeInstantiatedOnlyOncePerProcess="true" canNotUseMemoryManagementFunctions="true" canGetAndSetFMUstate="false" canSerializeFMUstate="false" providesDirectionalDerivative="false" canHandleVariableCommunicationStepSize="true" canInterpolateInputs="false" maxOutputDerivativeOrder="0" canRunAsynchronuously="false"/>
<UnitDefinitions>
<Unit name="s"/>
</UnitDefinitions>
<ModelVariables>
<ScalarVariable name="ROOT.environment._id__inputIndex" valueReference="100" description="input index" causality="local" initial="exact" variability="discrete">
<Integer start="1"/>
<Annotations><Tool name="Amesim"><VarAnnot index="1"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.camera._id__inputIndex" valueReference="102" description="Current index frame for camera" causality="local" variability="discrete">
<Integer min="0" max="10"/>
<Annotations><Tool name="Amesim"><VarAnnot index="3"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.perception._id__inputIndex" valueReference="103" description="Current index frame for perception" causality="local" variability="discrete">
<Integer min="0" max="10"/>
<Annotations><Tool name="Amesim"><VarAnnot index="4"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.perception._id__result" valueReference="104" description="Detection result" causality="output" variability="discrete">
<Integer />
<Annotations><Tool name="Amesim"><VarAnnot index="5"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.controller._id__speed" valueReference="105" description="Vehicle speed" causality="local" variability="discrete" initial="exact">
<Integer min="0" max="270" start="70"/>
<Annotations><Tool name="Amesim"><VarAnnot index="6"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.controller._id__speedLimit" valueReference="106" description="Speed limit" causality="local" variability="discrete">
<Integer min="0" max="120"/>
<Annotations><Tool name="Amesim"><VarAnnot index="7"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.controller._id__deltaSpeed" valueReference="107" description="Delta speed" causality="local" variability="discrete" initial="exact">
<Integer start="0"/>
<Annotations><Tool name="Amesim"><VarAnnot index="8"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.controller._id__zero" valueReference="108" description="Zero" causality="parameter" variability="fixed" initial="exact">
<Integer start="0"/>
<Annotations><Tool name="Amesim"><VarAnnot index="9"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.brake._id__deltaSpeed" valueReference="109" description="Delta speed" causality="local" variability="discrete" initial="exact">
<Integer start="0"/>
<Annotations><Tool name="Amesim"><VarAnnot index="10"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.throttle._id__deltaSpeed" valueReference="110" description="Delta speed" causality="local" variability="discrete" initial="exact">
<Integer start="0"/>
<Annotations><Tool name="Amesim"><VarAnnot index="11"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.speedSensor._id__speed" valueReference="111" description="Vehicle speed" causality="local" variability="discrete">
<Integer min="0" max="120"/>
<Annotations><Tool name="Amesim"><VarAnnot index="12"/></Tool></Annotations>
</ScalarVariable>
<ScalarVariable name="ROOT.speedSensor._id__deltaSpeed" valueReference="112" description="Delta speed" causality="local" variability="discrete" initial="exact">
<Integer start="0"/>
<Annotations><Tool name="Amesim"><VarAnnot index="13"/></Tool></Annotations>
</ScalarVariable>
</ModelVariables>
<ModelStructure>
<Outputs>
<Unknown index="2" dependencies=""/>
<Unknown index="5" dependencies=""/>
</Outputs>
<InitialUnknowns>
<Unknown index="5" dependencies=""/>
</InitialUnknowns>
</ModelStructure>
</fmiModelDescription>
import os
import sys
import cv2
import numpy as np
import onnxruntime
#import pyautogui
CLASSES = [100, 120, 20, 30, 40, 15, 50, 60, 70, 80]
def preprocess(img, input_size, swap=(2, 0, 1)):
if len(img.shape) == 3:
padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114
else:
padded_img = np.ones(input_size, dtype=np.uint8) * 114
r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
resized_img = cv2.resize(
img,
(int(img.shape[1] * r), int(img.shape[0] * r)),
interpolation=cv2.INTER_LINEAR,
).astype(np.uint8)
padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
padded_img = padded_img.transpose(swap)
padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
return padded_img, r
def nms(boxes, scores, nms_thr):
"""Single class NMS implemented in Numpy."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= nms_thr)[0]
order = order[inds + 1]
return keep
def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
"""Multiclass NMS implemented in Numpy"""
if class_agnostic:
nms_method = multiclass_nms_class_agnostic
else:
nms_method = multiclass_nms_class_aware
return nms_method(boxes, scores, nms_thr, score_thr)
def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
"""Multiclass NMS implemented in Numpy. Class-aware version."""
final_dets = []
num_classes = scores.shape[1]
for cls_ind in range(num_classes):
cls_scores = scores[:, cls_ind]
valid_score_mask = cls_scores > score_thr
if valid_score_mask.sum() == 0:
continue
else:
valid_scores = cls_scores[valid_score_mask]
valid_boxes = boxes[valid_score_mask]
keep = nms(valid_boxes, valid_scores, nms_thr)
if len(keep) > 0:
cls_inds = np.ones((len(keep), 1)) * cls_ind
dets = np.concatenate(
[valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
)
final_dets.append(dets)
if len(final_dets) == 0:
return None
return np.concatenate(final_dets, 0)
def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
"""Multiclass NMS implemented in Numpy. Class-agnostic version."""
cls_inds = scores.argmax(1)
cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
valid_score_mask = cls_scores > score_thr
if valid_score_mask.sum() == 0:
return None
valid_scores = cls_scores[valid_score_mask]
valid_boxes = boxes[valid_score_mask]
valid_cls_inds = cls_inds[valid_score_mask]
keep = nms(valid_boxes, valid_scores, nms_thr)
if keep:
dets = np.concatenate(
[valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], 1
)
return dets
def demo_postprocess(outputs, img_size, p6=False):
grids = []
expanded_strides = []
if not p6:
strides = [8, 16, 32]
else:
strides = [8, 16, 32, 64]
hsizes = [img_size[0] // stride for stride in strides]
wsizes = [img_size[1] // stride for stride in strides]
for hsize, wsize, stride in zip(hsizes, wsizes, strides):
xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
grids.append(grid)
shape = grid.shape[:2]
expanded_strides.append(np.full((*shape, 1), stride))
grids = np.concatenate(grids, 1)
expanded_strides = np.concatenate(expanded_strides, 1)
outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
return outputs
#img = pyautogui.screenshot(region = [1, 66, 800, 700])
#origin_img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
origin_img = cv2.imread(sys.argv[2])
img, ratio = preprocess(origin_img, [640, 640])
session = onnxruntime.InferenceSession(sys.argv[1])
ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
output = session.run(None, ort_inputs)
predictions = demo_postprocess(output[0], [640, 640])[0]
boxes = predictions[:, :4]
scores = predictions[:, 4:5] * predictions[:, 5:]
boxes_xyxy = np.ones_like(boxes)
boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2]/2.
boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3]/2.
boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2]/2.
boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3]/2.
boxes_xyxy /= ratio
dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
if dets is not None:
final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]
cls_ind = int(final_cls_inds[0])
score = final_scores[0]
if score > 0.9:
print(CLASSES[cls_ind])
# for SPEEDCONTROLMODULE/modelDetection/imageDetection example
mkdir bip_example
mkdir bip_example/binaries
mkdir bip_example/binaries/linux64
mkdir bip_example/resources
cp $1/libProject.so bip_example/binaries/linux64
cp -r $1/Signs bip_example/resources
cp -r $1/ext-cpp bip_example/resources
cp ../bip_example/modelDescription.xml bip_example
mv bip_example/binaries/linux64/libProject.so bip_example/binaries/linux64/bip_example.so
g++ src/DEPLOY_TEMPLATE.cpp -I includes -Lbip_example -ldl -o master -Wl,--export-dynamic
./master
/*
FMI Interface for FMU generated by FMICodeGenerator.
This file is part of FMICodeGenerator (https://github.com/ghorwin/FMICodeGenerator)
BSD 3-Clause License
Copyright (c) 2018, Andreas Nicolai
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FMI_templateH
#define FMI_templateH
#include <InstanceData.h>
/*! This class wraps all data needed for a single instance of the FMU. */
class FMI_template : public InstanceData {
public:
/*! Initializes empty instance. */
FMI_template();
/*! Destructor, writes out cached results from Therakles. */
~FMI_template();
/*! Initializes model */
void init();
/*! This function triggers a state-update of the embedded model whenever our cached input
data differs from the input data in the model.
*/
void updateIfModified();
/*! Called from fmi2DoStep(). */
virtual void integrateTo(double tCommunicationIntervalEnd);
virtual void doStep();
// Functions for getting/setting the state
/*! This function computes the size needed for full serizalization of
the FMU and stores the size in m_fmuStateSize.
\note The size includes the leading 8byte for the 64bit integer size
of the memory array (for testing purposes).
*/
virtual void computeFMUStateSize();
/*! Copies the internal state of the FMU to the memory array pointed to by FMUstate.
Memory array always has size m_fmuStateSize.
*/
virtual void serializeFMUstate(void * FMUstate);
/*! Copies the content of the memory array pointed to by FMUstate to the internal state of the FMU.
Memory array always has size m_fmuStateSize.
*/
virtual bool deserializeFMUstate(void * FMUstate);
/*! Cached current time point of the FMU, defines starting point for time integration in co-simulation mode. */
double m_currentTimePoint;
}; // class FMI_template
#endif // FMI_templateH
\ No newline at end of file
/*
Generic FMI Interface Implementation
This file is part of FMICodeGenerator (https://github.com/ghorwin/FMICodeGenerator)
BSD 3-Clause License
Copyright (c) 2018, Andreas Nicolai
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef InstanceDataH
#define InstanceDataH
#include <vector>
#include <map>
#include <set>
#include <string>
#include "fmi2FunctionTypes.h"
#include "Launcher.hpp"
/*! This class wraps data needed for FMUs and implements common functionality.
In order to use this in your own InstanceData structure, you must inherit this
file and implement the following functions:
\code
class MyFMIClass : public InstanceDataCommon {
public:
// Initializes InstanceData
void init();
// Re-implement if you want ModelExchange support
virtual void updateIfModified();
// Re-implement if you want CoSim support
virtual void integrateTo(double tCommunicationIntervalEnd);
};
\endcode
Also, you must define the constant with some GUID and implement the static function create().
\code
const char * const InstanceData::GUID = "{471a3b52-4923-44d8-ab4a-fcdb813c7322}";
InstanceData * InstanceData::create() {
return new MyFMIClass;
}
\endcode
in your MyFMIClass.cpp file.
*/
class InstanceData {
public:
/*! Global unique ID that identifies this FMU.
Must match the GUID in the ModelDescription file.
\note This GUID is model-specific, so you must define this static symbol
in the cpp file of your derived class.
*/
static const char * const GUID;
/*! Factory function, needs to be implemented in user code.
\note Only the model-specific implementation knows the concrete type of the class
derived from abstract InterfaceData class, and so this function must be
implemented in the model-specific code.
*/
static InstanceData * create();
/*! Initializes empty instance.
\note You must initialize all input and output variables here, since input
variable can be set and output variables can be requested, even before
entering initialization mode (i.e. before a call to init()).
*/
InstanceData();
/*! Destructor, resource cleanup. */
virtual ~InstanceData();
/*! Re-implement this function in derived classes to perform initialization
of the model during the initialization phase.
*/
virtual void init() {}
/*! This function triggers a state-update of the embedded model whenever our cached input
data differs from the input data in the model.
Re-implement in models that support model exchange.
\note You should check the state of m_externalInputVarsModified and only
update the results of this flag is true. Afterwards set this flag to false.
*/
virtual void updateIfModified() {}
/*! Called from fmi2DoStep().
Re-implement in models that support co-simulation.
*/
virtual void integrateTo(double tCommunicationIntervalEnd) { (void)tCommunicationIntervalEnd; }
virtual void doStep() {}
/*! Send a logging message to FMU environment if logger is present.*/
void logger(fmi2Status state, fmi2String category, fmi2String msg);
/*! Send a logging message to FMU environment if logger is present.
This function copies the error message (which may be a temporary string object) into the
persistent member variable m_lastError and passes a pointer to this string through the
logger function.
*/
void logger(fmi2Status state, fmi2String category, const std::string & msg) {
m_lastError = msg;
logger(state, category, m_lastError.c_str());
}
/*! Sets a new input parameter of type double. */
void setReal(int varID, double value);
/*! Sets a new input parameter of type int. */
void setInt(int varID, int value);
/*! Sets a new input parameter of type string. */
void setString(int varID, fmi2String value);
/*! Sets a new input parameter of type bool. */
void setBool(int varID, bool value);
/*! Retrieves an output parameter of type double. */
void getReal(int varID, double & value);
/*! Retrieves an output parameter of type int. */
void getInt(int varID, int & value);
/*! Retrieves an output parameter of type string. */
void getString(int varID, fmi2String & value);
/*! Retrieves an output parameter of type bool. */
void getBool(int varID, bool & value);
/*! Called from fmi2CompletedIntegratorStep(): only ModelExchange. */
void completedIntegratorStep();
/*! Called from completedIntegratorStep(): only ModelExchange.
Re-implement with your own code.
*/
virtual void completedIntegratorStep(double t_stepEnd, double * yInput) { (void)t_stepEnd; (void)yInput; }
/*! Re-implement for getFMUState()/setFMUState() support.
This function computes the size needed for full serizalization of
the FMU and stores the size in m_fmuStateSize.
\note The size includes the leading 8byte for the 64bit integer size
of the memory array (for testing purposes).
If serialization is not supported, the function will set an fmu size of 0.
*/
virtual void computeFMUStateSize() { m_fmuStateSize = 0; } // default implementation sets zero size = no serialization
/*! Re-implement for getFMUState() support.
Copies the internal state of the FMU to the memory array pointed to by FMUstate.
Memory array always has size m_fmuStateSize.
*/
virtual void serializeFMUstate(void * FMUstate) { (void)FMUstate; }
/*! Re-implement for setFMUState() support.
Copies the content of the memory array pointed to by FMUstate to the internal state of the FMU.
Memory array always has size m_fmuStateSize.
\return Returns false if checks during deserialization fail.
*/
virtual bool deserializeFMUstate(void * FMUstate) { (void)FMUstate; return true; }
/*! Called from either doStep() or terminate() in CoSimulation mode whenever
a communication interval has been completed and all related buffers can be cleared/output files can be
written.
*/
virtual void clearBuffers() {}
Launcher* m_launcher;
/*! Stores the FMU callback functions for later use.
It is usable between fmi2Instantiate and fmi2Terminate.*/
const fmi2CallbackFunctions* m_callbackFunctions;
/*! True if in initialization mode. */
bool m_initializationMode;
/*! Name of the instance inside the FMU environment.*/
std::string m_instanceName;
/*! Resource root path as set via fmi2Instantiate(). */
std::string m_resourceLocation;
/*! Logging enabled flag as set via fmi2Instantiate(). */
bool m_loggingOn;
/*! Logging categories supported by the master. */
std::vector<std::string> m_loggingCategories;
/*! If true, this is a ModelExchange FMU. */
bool m_modelExchange;
std::map<int,int> m_boolVar;
std::map<int,double> m_realVar;
std::map<int,int> m_integerVar;
std::map<int,std::string> m_stringVar;
/*! Time point in [s] received by last call to fmi2SetTime(). */
double m_tInput;
/*! Model state vector as received by last call to fmi2SetContinuousStates(). */
std::vector<double> m_yInput;
/*! Model derivatives vector as updated by last call to updateIfModified(). */
std::vector<double> m_ydot;
/*! Signals that one of the real parameter inputs have been changed.
This flag is reset whenever updateIfModified() has been called.
The flag is set in any of the setXXXParameter() functions.
*/
bool m_externalInputVarsModified;
/*! Holds the size of the FMU when serialized in memory.
This value does not change after full initialization of the solver so it can be cached.
Initially it will be zero so functions can check if initialization is properly done.
*/
size_t m_fmuStateSize;
/*! Holds pointers to all currently stored FMU states.
Pointers get added in function fmi2GetFMUstate(), and removed in fmi2FreeFMUstate().
Unreleased memory gets deallocated in destructor.
*/
std::set<void*> m_fmuStates;
/*! Persistent string pointing to last error message.
\warning DO not change/resize string manually, only through logger() function.
*/
std::string m_lastError;
}; // class InstanceData
#endif // InstanceDataH
\ No newline at end of file
#ifndef fmi2TypesPlatform_h
#define fmi2TypesPlatform_h
/* Standard header file to define the argument types of the
functions of the Functional Mock-up Interface 2.0.3
This header file must be utilized both by the model and
by the simulation engine.
Revisions:
- Sep. 29, 2019: License changed to 2-clause BSD License (without extensions)
- Apr. 9, 2014: All prefixes "fmi" renamed to "fmi2" (decision from April 8)
- Mar 31, 2014: New datatype fmiChar introduced.
- Feb. 17, 2013: Changed fmiTypesPlatform from "standard32" to "default".
Removed fmiUndefinedValueReference since no longer needed
(because every state is defined in ScalarVariables).
- March 20, 2012: Renamed from fmiPlatformTypes.h to fmiTypesPlatform.h
- Nov. 14, 2011: Use the header file "fmiPlatformTypes.h" for FMI 2.0
both for "FMI for model exchange" and for "FMI for co-simulation"
New types "fmiComponentEnvironment", "fmiState", and "fmiByte".
The implementation of "fmiBoolean" is change from "char" to "int".
The #define "fmiPlatform" changed to "fmiTypesPlatform"
(in order that #define and function call are consistent)
- Oct. 4, 2010: Renamed header file from "fmiModelTypes.h" to fmiPlatformTypes.h"
for the co-simulation interface
- Jan. 4, 2010: Renamed meModelTypes_h to fmiModelTypes_h (by Mauss, QTronic)
- Dec. 21, 2009: Changed "me" to "fmi" and "meModel" to "fmiComponent"
according to meeting on Dec. 18 (by Martin Otter, DLR)
- Dec. 6, 2009: Added meUndefinedValueReference (by Martin Otter, DLR)
- Sept. 9, 2009: Changes according to FMI-meeting on July 21:
Changed "version" to "platform", "standard" to "standard32",
Added a precise definition of "standard32" as comment
(by Martin Otter, DLR)
- July 19, 2009: Added "me" as prefix to file names, added meTrue/meFalse,
and changed meValueReferenced from int to unsigned int
(by Martin Otter, DLR).
- March 2, 2009: Moved enums and function pointer definitions to
ModelFunctions.h (by Martin Otter, DLR).
- Dec. 3, 2008 : First version by Martin Otter (DLR) and
Hans Olsson (Dynasim).
Copyright (C) 2008-2011 MODELISAR consortium,
2012-2021 Modelica Association Project "FMI"
All rights reserved.
This file is licensed by the copyright holders under the 2-Clause BSD License
(https://opensource.org/licenses/BSD-2-Clause):
----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------
*/
/* Platform (unique identification of this header file) */
#define fmi2TypesPlatform "default"
/* Type definitions of variables passed as arguments
Version "default" means:
fmi2Component : an opaque object pointer
fmi2ComponentEnvironment: an opaque object pointer
fmi2FMUstate : an opaque object pointer
fmi2ValueReference : handle to the value of a variable
fmi2Real : double precision floating-point data type
fmi2Integer : basic signed integer data type
fmi2Boolean : basic signed integer data type
fmi2Char : character data type
fmi2String : a pointer to a vector of fmi2Char characters
('\0' terminated, UTF8 encoded)
fmi2Byte : smallest addressable unit of the machine, typically one byte.
*/
typedef void* fmi2Component; /* Pointer to FMU instance */
typedef void* fmi2ComponentEnvironment; /* Pointer to FMU environment */
typedef void* fmi2FMUstate; /* Pointer to internal FMU state */
typedef unsigned int fmi2ValueReference;
typedef double fmi2Real ;
typedef int fmi2Integer;
typedef int fmi2Boolean;
typedef char fmi2Char;
typedef const fmi2Char* fmi2String;
typedef char fmi2Byte;
/* Values for fmi2Boolean */
#define fmi2True 1
#define fmi2False 0
#endif /* fmi2TypesPlatform_h */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string>
#include <fmi2Functions.h>
#include <fmi2FunctionTypes.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int ret = EXIT_SUCCESS;
fmi2Real tstart = 0.0;
fmi2Real tcur = tstart;
fmi2Real hstep = 0.2;
fmi2Real tend = 7.0;
void *handle;
fmi2InstantiateTYPE* (fmi2Instantiate);
fmi2EnterInitializationModeTYPE* (fmi2EnterInitializationMode);
fmi2ExitInitializationModeTYPE* (fmi2ExitInitializationMode);
fmi2SetIntegerTYPE* (fmi2SetInteger);
fmi2GetIntegerTYPE* (fmi2GetInteger);
fmi2DoStepTYPE* (fmi2DoStep);
void (*set_inverted_map)(int,string);
char *error;
handle = dlopen ("bip_example/binaries/linux64/bip_example.so", RTLD_LAZY);
if (!handle) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}
dlerror(); /* Clear any existing error */
fmi2Instantiate = (fmi2InstantiateTYPE*) dlsym(handle, "fmi2Instantiate");
fmi2EnterInitializationMode = (fmi2EnterInitializationModeTYPE*) dlsym(handle, "fmi2EnterInitializationMode");
fmi2ExitInitializationMode = (fmi2ExitInitializationModeTYPE*) dlsym(handle, "fmi2ExitInitializationMode");
fmi2SetInteger = (fmi2SetIntegerTYPE*) dlsym(handle, "fmi2SetInteger");
fmi2GetInteger = (fmi2GetIntegerTYPE*) dlsym(handle, "fmi2GetInteger");
fmi2DoStep = (fmi2DoStepTYPE*) dlsym(handle, "fmi2DoStep");
set_inverted_map = (void (*)(int, std::string)) dlsym(handle, "set_inverted_map");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}
cout<<"CALL fmi2Instantiate...\n";
fmi2Component c = (*fmi2Instantiate)("prModel", fmi2CoSimulation , "prModel", "resource/location", NULL, true, true);
(*set_inverted_map)(100, "ROOT.environment._id__inputIndex");
//(*set_inverted_map)(101, "ROOT.environment._id__time");
(*set_inverted_map)(102, "ROOT.camera._id__inputIndex");
(*set_inverted_map)(103, "ROOT.perception._id__inputIndex");
(*set_inverted_map)(104, "ROOT.perception._id__result");
(*set_inverted_map)(105, "ROOT.controller._id__speed");
(*set_inverted_map)(106, "ROOT.controller._id__speedLimit");
(*set_inverted_map)(107, "ROOT.controller._id__deltaSpeed");
(*set_inverted_map)(108, "ROOT.controller._id__zero");
(*set_inverted_map)(109, "ROOT.brake._id__deltaSpeed");
(*set_inverted_map)(110, "ROOT.throttle._id__deltaSpeed");
(*set_inverted_map)(111, "ROOT.speedSensor._id__speed");
(*set_inverted_map)(112, "ROOT.speedSensor._id__deltaSpeed");
const unsigned int vr[] = {100,/*101,*/ 102,103,104,105,106,107,108,109,110,111,112};
const int values[] = {1,/*10,*/ 0,0,0,0,0,0,0,0,0,100,0};
cout<<"CALL fmi2SetInteger...\n";
(*fmi2SetInteger)(c, vr, 12, values);
cout<<"CALL fmi2EnterInitializationMode...\n";
(*fmi2EnterInitializationMode)(c);
cout<<"CALL fmi2ExitInitializationMode...\n";
(*fmi2ExitInitializationMode)(c);
tcur = tstart;
while(tcur<tend){
fmi2Boolean newStep = fmi2True;
fmi2Integer val[12];
cout<<"tcur: "<<tcur<<'\n';
cout<<"CALL fmi2DoStep...\n";
fmi2DoStep(c, tcur,hstep, newStep);
cout<<"CALL fmi2GetInteger...\n";
fmi2GetInteger(c, vr, 12, val);
tcur += hstep;
}
cout<<"Simulation finished.\n";
dlclose(handle);
return ret;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment