FESA3 C++ Code Snippets

Working with devices in the server-part

// Since server actions are only executed for a specific device,
// we directly can use the argument "pDev", which is passed to the execute-method
pDev->myField.set(someValue,pEvt->getMultiplexingContext());

// In Server-Actions the global-device can be accessed by using the service-locator
MyClassServiceLocator_->getGlobalDevice()->myField.set(someValue,pEvt->getMultiplexingContext());

For the complete API of the class "device" and it's relatives, check the doxygen documentation.

Working with devices in the RT-part

// In a RT-Action we can iterate over the whole device-collection like that:
std::vector<Device*>::iterator device;
for(device=deviceCol_.begin();device!=deviceCol_.end();++device)
{
   // perform some action with the device
   (*device)->myField.set(someValue,pEvt->getMultiplexingContext());
}

// In RT-Action global-fields can be accessed by using the service-locator
MyClassServiceLocator_->getGlobalDevice()->myField.set(someValue,pEvt->getMultiplexingContext());

For the complete API of the class "device" and it's relatives, check the doxygen documentation.

Working with devices in the specificInit methods

#include <fesa-core/Synchronization/NoneContext.h>
#include <MyClass/GeneratedCode/DeviceFactory.h>  // replace the name of your class with MyClass

//Since an empty context is needed to access any field, you can make use of the fesa-internal-type "NoneContext"
fesa::NoneContext context;

// In the method "specificInit" of the RT/Server-DeviceClass a member "devCol_" is not provided to access devices.
// For now, we have to use the DeviceFactory to obtain device-references outside of the Server/RTAction
// Later this job will be done by the ServiceLocator
const std::vector<Device*> devCol = DeviceFactory::getInstance()->getDeviceCollection();
GlobalDevice* globalDev = DeviceFactory::getInstance()->getGlobalDevice();

std::vector<Device*>::const_iterator device;
for(device= devCol.begin();device!=devCol.end();++device)
{
    std::cout << "DeviceName: " << (*device)->getName() << std::endl;
    (*device)->myField.set(someValue,&context);
}

Working with FESA scalar-fields

int32_t myData = (*device)->myField.get(pEvt->getMultiplexingContext());
myData ++;
(*device)->myField.set(myData,pEvt->getMultiplexingContext());

For the complete API of scalar-fields and it's relatives, check the doxygen documentation.

Working with FESA array-fields

uint32_t index = 1;

//Get a cell-value
const int32_t myData = (*device)->myArrayField.getCell(index,pEvt->getMultiplexingContext());

//Set a cell-value
int32_t myNewData= 123;
(*device)->myArrayField.setCell(myNewData,index,pEvt->getMultiplexingContext());

// Set data to a array-field:
uint32_t sizeOfmyData = 4;
int32_t myData[sizeOfmyData];
myData[1] = 15;
(*device)->myArrayField.set(myData,sizeOfmyData,pEvt->getMultiplexingContext());

// Get data from a array-field:
uint32_t dim;
const int32_t* myData = (*device)->myArrayField.get(dim,pEvt->getMultiplexingContext());

For the complete API of array-fields and it's relatives, check the doxygen documentation.

Working with FESA 2D-array-fields

uint32_t index1 = 1;
uint32_t index2 = 1;
uint32_t dim1 = 3;
uint32_t dim2 = 2;

//Get a cell-value
const int32_t myData = (*device)->my2DArray.getCell(index1,index2,pEvt->getMultiplexingContext());

//Set a cell-value
int32_t myNewData
(*device)->my2DArray.setCell(myNewData,index1,index2,pEvt->getMultiplexingContext());

//Get a row
const int32_t* myData =  (*device)->my2DArray.getRow(index1,dim1,pEvt->getMultiplexingContext());

//Set a row/column
uint32_t index = 1;
int32_t myDataColumn[dim2];
int32_t myDataRow[dim1];
(*device)->my2DArray.setColumn(myDataColumn,index,dim2,pEvt->getMultiplexingContext());
(*device)->my2DArray.setRow(myDataRow,index,dim1,pEvt->getMultiplexingContext());

//Get the complete array2D
// Currently this method does not work for 2D-arrays because of some internal bug ... please use getCell(..) for now !
// uint32_t dim1;
// uint32_t dim2;
// const int32_t** myDataAll = (*device)->my2DArray.get(dim1,dim2,pEvt->getMultiplexingContext());

For the complete API of 2D-array-fields and it's relatives, check the doxygen documentation.

Working with FESA char-array-fields (strings)

std::string myString;
(*device)->myCharArray.set(myString.c_str(),pEvt->getMultiplexingContext());

const char* myCharArrayPointer = (*device)->myCharArray.get(pEvt->getMultiplexingContext());

For the complete API of string-fields and it's relatives, check the doxygen documentation.

Working with FESA 2D-char-array-fields (string-arrays)

uint32_t index = 0;
std::string myString = "MyString";
(*device)-->myCharArray2D.setString(myString.c_str(), index,pEvt->getMultiplexingContext());

const char* myCharArrayPointer = (*device)->myCharArray2D.getString(index,pEvt->getMultiplexingContext());

uint32_t size;
const char** my2DCharArrayPointer = (*device)->myCharArray2D.get(size,pEvt->getMultiplexingContext());
std::cout << "Number of strings: " << size << std::endl;
std::cout << "First String: " <<  my2DCharArrayPointer[0] << std::endl;

For the complete API of string-array-fields and it's relatives, check the doxygen documentation.

Working with variable-sized 2D char arrays

// In the design document
<value-item name="aVarV" direction="OUT">
     <array2D type="char">
         <variable-dim1>
             <min>0</min>
             <max>4000</max>
         </variable-dim1>
        <custom-constant-dim2 constant-name-ref="MAX_STRING_LENGTH" />
     </array2D>
</value-item>

// C++ code:
string aVarTemp[MAX_SIZE];    // declaration of array

// setting part of the array
for(int i=0; i < some_size; i++)        // some_size <= MAX_SIZE
     aVarTemp[i] = "some string";


// filling variable-sized string array
fesa::NoneContext context;
const std::vector<Device*> devCol =
DeviceFactory::getInstance()->getDeviceCollection();

std::vector<Device*>::const_iterator device; for(device= devCol.begin();device!=devCol.end();++device) {
     (*device)->aVarV.set(reinterpret_cast<const char**>(&aVarTemp), some_size, &context);
}

Working with variable-sized arrays

In the design document define the minimum and maximum border for the field.

<field multiplexed="false" name="aVarF">
  <array type="int16_t">
    <variable-dim>
      <min>0</min>
      <max>20</max>
    </variable-dim>
   </array>
</field>

In the instance document instantiate the field within the device-instance element:

<device-instance name="TestDevice0">
  <configuration>
    <description value=""/>
    <accelerator value="NONE"/>
    <timingDomain value="NONE"/>
    <mainMuxCriterion value="NONE"/>
  ...
 </configuration>
 <acquisition>
   <aVarF>
     <dim value="25"/>
   </aVarF>
 </acquisition>
  ... 
 

Now the variable-sized array may be filled, e.g.

   fesa::NoneContext context;
   const std::vector<Device*> devCol = DeviceFactory::getInstance()->getDeviceCollection();
   GlobalDevice* globalDev = DeviceFactory::getInstance()->getGlobalDevice();

   std::vector<Device*>::const_iterator device;
   for(device= devCol.begin();device!=devCol.end();++device)
   {
      std::cout << "max size = " << (*device)->aVarF.getMaxSize() << std::endl; // this is the value as defined in the instance document
      for(int i(0); i<20; i++) {
         std::cout << "set var: " << i << std::endl;
         (*device)->aVarF.setCell(i, i, &context);
      }
   }
 

Working with bit-enum-fields

// generated code in TypeDefinition.h (just an example):
namespace MyBitEnum
{
   enum MyBitEnum
   {
      isActive=1,
      isValid=2,
      hasPower=4
   }; // 3 bits 
}

// Access the field in Server/RT-Actions:
int32_t value = MyBitEnum::isActive | MyBitEnum::hasPower;
(*device)->myBitEnumField.set( value, pCtxt );

int32_t newValue = (*device)->myBitEnumField.get(pEvt->getMultiplexingContext());

Fill the GSI-Multiplexing-context-field

// easy method (cyclestamp, cylcename and acquisitionstamp are obtained from MultiplexingContext, when available)
// This method will only work when using the TimingEventSource, since this is the only source which provides iterrupt-stamps which can be used as acquisition-stamp
(*device)->acquisitionContext.insert(pCtxt);

// advanced method ( usage of self-defined acquisition-stamp )
//stamp should be in Nanoseconds - UTC
int64_t stamp = 12345678;
(*device)->acquisitionContext.insert(pCtxt,acquisitionStamp);

Report an error by using the GSI-error_collection-field

std::string errorString= "Put in your error-text here";
int32_t error_code= 4711;
(*device)->error_collection.addError(error_code,errorString,pEvt->getMultiplexingContext(),*device);

For the complete API of the class "GSIErrorCollectionField" and it's relatives, check the doxygen documentation.

Usage of the GSI-detailed-status-field

// You can either directly use an index
(*device)->detailedStatus.lower(0,pEvt->getMultiplexingContext());
(*device)->detailedStatus.raise(1,pEvt->getMultiplexingContext());

// Or make use of the labels which you defined in detailedStatus_labels
(*device)->detailedStatus.lower("MyLabelBit4",pEvt->getMultiplexingContext());
(*device)->detailedStatus.raise("MyLabelBit5",pEvt->getMultiplexingContext());

</verbatim> The field directly inherits from the Array-Field, so ofc you as well can make use of all the methods from the baseclass !

Usage of class-specific custom-types

// Take a look into "generated/cpp/MyClassName/GeneratedCode/TypeDefinition.h" to see all custom-types, defined by your class
(*device)->control.set(DEVICE_CONTROL::LOCAL,pEvt->getMultiplexingContext());

Usage of client-data in server-actions

//In a Set-Server-Acttion you may want to retrieve the data and the filter, which was send by the client:
bool myData = data.myValueItemName.get();
bool myData = filter.myFilterItemName.get();

//In a Get-Server-Action you may want to fill the data-container which will be send to the client.
int32_t myData = 1234;
data.myValueItemName.set(myData );

Usage of external headers and libraries

# Modify the file "Makefile.specific" of your class / deploy-unit, according to your needs
SOME_LIBRARY_HOME= /path/to/the/library
COMPILER_FLAGS += -I$(SOME_LIBRARY_HOME)/include
LINKER_FLAGS += -L$(SOME_LIBRARY_HOME)/lib/$(CPU) -lsome-library

Usage of the FESA-Logger

std::ostringstream message;
message << "Put your logg-message here " ;
LOG_ERROR_IF(logger, message.str());
// Depending on how important your logg-message is, you should use one of the following macros:
// LOG_TRACE_IF(logger, message.str());
// LOG_DEBUG_IF(logger, message.str());
// LOG_INFO_IF(logger, message.str());
// LOG_WARNING_IF(logger, message.str());
// LOG_ERROR_IF(logger, message.str());

// Diagnostic-Information can be logged like this (see link below for more information)
LOG_DIAG_IF("MyTopic",message.str());

  • Use the application-arguments -v and -vv to control the verbosity of your FESA-Software
  • If needed you as well can re-configure the logging-configuration by providing a foreign config-file (Application-Argument -cfglog )
  • Information on where the log-files are stored can be found here.
  • Here you can find some Information about diagnostic-logging in the next fesa-release
  • As well check doxygen documentation of the complete logger API.

How to trigger an on-demand-event manually

// First you have to choose "@automatic = false" on your action/triggered-event-source in the class-design 
// In the server/rt-action, you can fire the event with the following command:
AbstractAction::triggerOnDemandEventSource("MyOnDemandEventSource",pEvt->getMultiplexingContext(),0);

If required, you as well can add some payload-information to the event. Check the payload-section for more infrmation!

For the complete API of the class "AbstractAction" and it's relatives, check the doxygen documentation.

How to trigger a property-notification manually

// The same code can be used in Server- and RT-actions
// Make sure that the names of the property/device you want to notify are correct
// For inherited or composed classes, dont use the className::propertyName format! It is sufficient to only put the property-name.  
std::string notifiedProperty = "MyProperty";
std::string notifiedDevice = "MyDevice";

// You can add any number of property/device-combinations by using the following method:
registerManualNotification(notifiedProperty,notifiedDevice);

//If you are finished with adding properties/devices, send the notification by using the method below
sendManualNotification(pEvt->getMultiplexingContext());

Throwing Exceptions to clients

Prefably the type "FesaException" should be used here. ( However as well any type of RDAException will do. ) Either an object of this type can be created directly, or the class developer can inherit from the class, in order to define a class-specific exception-type.
std::string errorMessage = "Something went wrong here!";
//Currently at GSI there are no standards regarding the error-codes
std::string errorCode = "4711";
// errorCategory should be "FESACLASS_" as prefix an the classname.
std::string errorCategory = "FESACLASS_MyFesaClass";

throw fesa::FesaException(errorMessage,__FILE__,__LINE__,errorCode,errorCategory);

Enable/Disable logical events and event-sources

// By the use of the service-locator, events and sources can be enabled/disabled everywhere in the user-code
// "this->" is not needed here, it just helps to trigger the eclipse-auto-completion

this->serviceLocator_->enableEventSource("MySource");
this->serviceLocator_->disableEventSource("MySource");

// The second argument is deprecated and will be removed in comming fesa-versions
this->serviceLocator_->enableRTEvent("MyLogicalEvent","");
this->serviceLocator_->disableRTEvent("MyLogicalEvent","")

Trigger ther persistence of setting-fields by hand

// The following command will write the values of all setting-fields to a file which have the flag "persistent = true".
// "this->" is not needed here, it just helps to trigger the eclipse-auto-completion

this->serviceLocator_->triggerPersistency();

Working with Event-Payload

OnDemand Payload

// In the action which triggers the OnDemandEvent, you can add a payload. The data-format is an char-array
std::string payload = "myPayload";
AbstractAction::triggerOnDemandEventSource("MyOnDemandEventSource",pEvt->getMultiplexingContext(),payload.c_str(),payload.size(),0);

// In the RT-Action you than can read-out the defined payload like that:
#include <fesa-core/RealTime/RTEventPayload.h>
....
std::string payload = pEvt->getPayload()->getValue<char>();

Timing Payload

How to use WhiteRabbit Timing

OnSubscription Payload

// FIrst of all, make sure that the FESA-device you want to subscribe to is listed in the FESA-DB !

// In the RTAction, add this line to the includes
#include <fesa-core/RealTime/OnSubscriptionRTEventPayload.h>
...
// Use the following code in the execute-method
// This cast will not be the final solution ... however for now it works
const OnSubscriptionRTEventPayload* payload =  dynamic_cast<const OnSubscriptionRTEventPayload*> (pEvt->getPayload().get());
rdaData data = payload->getRDAData();

// now you can perform different operations on the data-container
// E.g. print() will produce a printout of all items inside
// Check the cmw-rda header of Data.h for more options ( Or make use of the auto-completion! )
data.print();
Topic revision: r5 - 08 Jul 2014, AlexanderSchwinn
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback