FESA3 C++ Code Snippets

- Working with devices -

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
this->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*> devCol =  this->MyClassServiceLocator_->getDeviceCollection();
std::vector<Device*>::iterator device;
for(device=devCol.begin();device!=devCol.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
this->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>

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

// Like in the RT-Action in the method "specificInit" of the RT/Server-DeviceClass the service-locator can be used to access the different devices
std::vector<Device*> devCol =  this->MyClassServiceLocator_->getDeviceCollection();
std::vector<Device*>::iterator device;
for(device=devCol.begin();device!=devCol.end();++device)
{
    // perform some action with the device
    std::cout << "DeviceName: " << (*device)->getName() << std::endl;
    (*device)->myField.set(someValue,&context);
}

// Accordingly the global-device can be accessed
this->MyClassServiceLocator_->getGlobalDevice()->myField.set(someValue,pEvt->getMultiplexingContext());

- Working with fields -

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;
uint32_t dim2;

// Get the dimensions
(*device)->myField.getSize(dim1, dim2, pEvt->getMultiplexingContext());

// 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());

// Get a column
uint32_t tempArraySize = dim2;
double* column = new double[tempArraySize];
(*device)->myField.getColumn(index2, dim2, column, tempArraySize, 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 ( use the correct type as template argument )
fesa::ImmutableArray2D<double> data = (*device)->myField.get(pEvt->getMultiplexingContext());
std::cout << " data[2][2]: "<< data[2][2] << std::endl;

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());

Working with hw-address fields

// The concrete values of a hw-address can be set in the instantiation-file for each device

 // for  a "logical-address"
int32_t logicalUnitNumber = (*device)->myLogicalHardwareAddress.get()->logicalUnitNumber;
int32_t channel = (*device)->myLogicalHardwareAddress.get()->channel;
const char* moduleType = (*device)->myLogicalHardwareAddress.get()->moduleType;

// for a "host"
int32_t port = (*device)->myRemoteHost.get()->port;
const char* host = (*device)->myRemoteHost.get()->hostName;

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 must be given in Nanoseconds - UTC !
// E.g. if your hardware provides a precise stamp, you can make use of it here.
// You can as well make use of the system-stamp. The following fesa-method already returns the right format:
#include <fesa-core/Synchronization/Timing.h>
....
int64_t stamp = fesa::getSystemTime(); 
(*device)->acquisitionContext.insert( pEvt->getMultiplexingContext(), stamp );

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 !

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();

- Misc -

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.getMyValueItemName();
bool myData = filter.getMyFilterItemName();
 
// 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.setMyValueItemName(myData );

// For 2D arrays you can make use of the FESA Container-class "ImmutableArray2D":
fesa::ImmutableArray2D<double> myData = data.getMyDoubleArray2D();
std::cout << "myData[2][2]: " << myData[2][2] << std::endl;

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()); // In FESA-classes you should use the diagnostic-logging instead
// LOG_DEBUG_IF(logger, message.str());  // In FESA-classes you should use the diagnostic-logging instead
// LOG_INFO_IF(logger, message.str());  // In FESA-classes you should use the diagnostic-logging instead
// LOG_WARNING_IF(logger, message.str());
// LOG_ERROR_IF(logger, message.str());


// Diagnostic-Information can be logged like this 
// You can define specific log-traces to only enable/disable your own log
// Use the global "diagnostic-property" in order to enable/disable specific traces during runtime
// 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
  • As well check doxygen documentation of the complete logger API.

How to trigger an on-demand-event manually

// In the class-design you have to choose "@automatic = false" on your action/triggered-event-source.
// In the custom-server-/rt- action you can now do the following:
triggerOnDemandEventSource(MyOnDemandEventSourceName,pEvt->getMultiplexingContext());

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","")

Working with Event-Payload

OnDemand Payload

// If you choose "triggered-event-source/@automatic = false" for the action,
// you can add your own payload to the event. The data-format is a char-array
std::string payload = "myPayload";
triggerOnDemandEventSource(MyODEventSourceName,pEvt->getMultiplexingContext(),payload.c_str(),payload.size() + 1);

// Please note that for "triggered-event-source/@automatic = true" in server-actions,
// the device-name for which the server-action was triggered is automatically added as payload !

// In the RT-Action you can read-out the defined payload like that:
#include <fesa-core/RealTime/RTEventPayload.h>
....
const char* payload = pEvt->getPayload()->getValue<char>();
// or, if you prefer using a std::string:
std::string payload(pEvt->getPayload()->getValue<char>());

Timing Payload White Rabbit

// Include this header in the RT-Action
#include <fesa-core-gsi/Synchronization/TimingContextWR.h>
...
// Cast the MultiplexingContext to the right type
const fesaGSI::TimingContextWR* contextWR =  dynamic_cast<const fesaGSI::TimingContextWR*>(pEvt->getMultiplexingContext());

// Sorry about the const_cast ... in the next FESA-Version the cast will not be needed any more
std::cout << "FormatID: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getFormatID() << std::endl;
std::cout << "GroupID: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getGroupID() << std::endl;
std::cout << "EventNumber: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getEventNumber() << std::endl;
std::cout << "SequenceID: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getSequenceID() << std::endl;
std::cout << "BeamProcessID: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getBeamProcessID() << std::endl;
std::cout << "SequenceCounter: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getSequenceCounter() << std::endl;
std::cout << "ActionTimeStamp: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getActionTimeStamp() << std::endl;
std::cout << "EventParameter: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getEventParameter() << std::endl;
std::cout << "BeamProductionChainID: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getBeamProductionChainID() << std::endl;
std::cout << "BeamProductionChainTimestamp: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getBeamProductionChainTimestamp() << std::endl;
std::cout << "SequenceTimeStamp: " <<  const_cast<fesaGSI::TimingContextWR*>(contextWR)->getSequenceTimeStamp() << std::endl;

//You as well can get the whole payload at once:
fesaGSI::TimingContextWRPayload payload = const_cast<fesaGSI::TimingContextWR*>(contextWR)->getPayload();

More information about White-Rabbit tIming can be found here.

OnSubscription Payload

The code, needed to extract the data is so bulky, that it got a own wiki page.

Perform a client-"Get" from one FESA-class to another

// Lets assume you write code for class "ClassA". And you want to do a "Get" of the property "PropB " of the device "DevB" of class "ClassB"
// PropB has the value items "ItemB1" and "ItemB2"
// First you need to include the following fesa-core header
#include <fesa-core/Proxy/ProxyInterface.h>
// Second you need to include PropertyData.h of ClassB
#include <ClassB/GeneratedCode/PropertyData.h>
...
// If you need to do the "Get" more than once, it may make sense to store this object as class-member
fesa::ProxyInterface rda;

std::string deviceName = "DevB";
std::string cycleSelector = ""; // For multiplexed devices you have to enter the concrete cycle-selector here
std::auto_ptr<const ClassB::PropBPropertyData> ;

// Probably you want to wrap a try / catch around this block later and catch for std::exception
  propData = rda.getProperty<const ClassB::PropBPropertyData>(deviceName,cycleSelector);
std::cout << "ItemB1: " << propData->getItemB1() << std::endl;
std::cout << "ItemB2: " << propData->getItemB2() << std::endl;

Perform a client-"Set" from one FESA-class to another

// Lets assume you write code for class "ClassA". And you want to do a "Set" of the property "PropB " of the device "DevB" of class "ClassB"
// PropB has the value items "ItemB1" and "ItemB2"
// First you need to include the following fesa-core header
#include <fesa-core/Proxy/ProxyInterface.h>
// Second you need to include PropertyData.h of ClassB
#include <ClassB/GeneratedCode/PropertyData.h>
...
// If you need to do the "Get" more than once, it may make sense to store this object as class-member
fesa::ProxyInterface rda;

std::string deviceName = "DevB";
std::string cycleSelector = ""; // For multiplexed devices you have to enter the concrete cycle-selector here
ClassB::PropBPropertyData propData;
double myValue = 42;
propData.setItemB1(myValue);
propData.setItemB2(myValue);

// Probably you want to wrap a try / catch around this block later and catch for std::exception
rda.setProperty<const ClassB::PropBPropertyData>(deviceName,cycleSelector,propData);

Read instance file information

// E.g. the TimingDomain defined in the instance-file can be accessed like that:
// ( How to obtain a device-pointer is explained on top )
std::string timingDomain = (*device)->getInstantiationData()->getTimingDomain();
The complete API of the class 'DeviceInstantiationData' can be found here
Topic revision: r21 - 25 Mar 2015, 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