Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • silecs/opensilecs
  • k.fugiel/opensilecs
  • s.kupiecki/opensilecs
3 results
Show changes
Showing
with 1466 additions and 1805 deletions
#!/bin/sh
set -e
CPU="x86_64"
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT") # path where this script is located in
#SNAP7_PATH=${SCRIPTPATH}/../../../git/snap7/snap7-full/build/bin/${CPU}-linux #local
SNAP7_PATH=${SCRIPTPATH}/../../../snap7/2.0.0/bin/${CPU}-linux
#BINARY="${SCRIPTPATH}/../build/bin/${CPU}/silecs-cli-client" #local
BINARY="${SCRIPTPATH}/../bin/${CPU}/silecs-cli-client"
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SNAP7_PATH
echo "##### LD_LIBRARY_PATH: ###################################################################################"
echo "$LD_LIBRARY_PATH"
echo "##########################################################################################################"
echo ""
PARAM_FILE=/common/home/bel/schwinn/lnx/workspace-silecs-neon/SiemensTestDU/generated/client/tsts7001.silecsparam
REGISTER=DQ_Anlog00
DEVICE=MyDevice1
......
#!/bin/sh
set -e
CPU="x86_64"
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT") # path where this script is located in
#SNAP7_PATH=${SCRIPTPATH}/../../../git/snap7/snap7-full/build/bin/${CPU}-linux #local
SNAP7_PATH=${SCRIPTPATH}/../../../snap7/2.0.0/bin/${CPU}-linux
#BINARY="${SCRIPTPATH}/../build/bin/${CPU}/silecs-cli-client" #local
BINARY="${SCRIPTPATH}/../bin/${CPU}/silecs-cli-client"
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SNAP7_PATH
echo "##### LD_LIBRARY_PATH: ###################################################################################"
echo "$LD_LIBRARY_PATH"
echo "##########################################################################################################"
echo ""
PARAM_FILE=/common/home/bel/schwinn/lnx/workspace-silecs-neon/SiemensTestDU/generated/client/tsts7001.silecsparam
# config for SiemensTestDU
......
#!/bin/sh
set -e
INSTALL_DIR=$1
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT") # path where this script is located in
mkdir -p ${INSTALL_DIR}
cp -r ${SCRIPTPATH}/build/bin ${INSTALL_DIR}
cp -r ${SCRIPTPATH}/examples ${INSTALL_DIR}
\ No newline at end of file
......@@ -24,16 +24,21 @@
#include <silecs-communication/interface/utility/XMLParser.h>
#include <silecs-communication/interface/core/SilecsService.h>
#include <silecs-communication/interface/equipment/SilecsCluster.h>
#include <silecs-communication/interface/equipment/SilecsDevice.h>
#include <silecs-communication/interface/equipment/SilecsRegister.h>
#include <boost/assign/list_of.hpp> // init vector of strings
#include <silecs-communication/interface/equipment/SilecsPLC.h>
const std::string startbold = "\e[1m";
const std::string endbold = "\e[0m";
enum ModeType { UNDEFINED, GET_DEVICE, GET_BLOCK, GET_REGISTER, SET_REGISTER };
enum ModeType
{
UNDEFINED,
GET_DEVICE,
GET_BLOCK,
GET_REGISTER,
SET_REGISTER
};
std::string arg_logTopics; //comma separated list ? space-separated ?
std::string arg_parameterFile = "";
......@@ -47,8 +52,8 @@ bool arg_checkChecksum = true;
ModeType arg_mode = UNDEFINED;
uint32_t periodicInterval = 0;
char* log_arg_base[2] = {(char*)"-plcLog",(char*)"ERROR,COMM"};
char* log_arg_verbose[2] = {(char*)"-plcLog",(char*)"ERROR,DEBUG,SETUP,ALLOC,LOCK,COMM,SEND,RECV,DATA,DIAG"};
char *log_arg_base[2] = {(char*)"-plcLog", (char*)"ERROR"};
char *log_arg_verbose[2] = {(char*)"-plcLog", (char*)"ERROR,DEBUG,SETUP,ALLOC,LOCK,COMM,SEND,RECV,DATA,DIAG"};
void printHelp()
{
......@@ -68,7 +73,7 @@ void printHelp()
std::cout << startbold << "\t-d " << endbold << "silecs-device to request" << std::endl;
std::cout << startbold << "\t-f " << endbold << "path to silecs-parameter-file of the plc" << std::endl;
std::cout << startbold << "\t-h " << endbold << "print this help" << std::endl;
std::cout << startbold << "\t-i " << endbold << "start interactive session" << std::endl; // TODO: Implement
std::cout << startbold << "\t-i " << endbold << "start interactive session" << std::endl; // TODO: Implement
std::cout << startbold << "\t-v " << endbold << "verbose, all LOGTOPICS are enabled" << std::endl; // TODO: Implement
//std::cout << startbold << "\t-m " << endbold << "mode, can be 'GET_DEVICE', 'GET_BLOCK', 'GET_REGISTER' or 'SET_REGISTER'" << std::endl;
std::cout << startbold << "\t-m " << endbold << "mode, can be 'GET_DEVICE', 'GET_BLOCK' or 'GET_REGISTER'" << std::endl;
......@@ -99,518 +104,531 @@ int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
tcgetattr(STDIN_FILENO, &oldattr);
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
newattr.c_lflag &= ~ (ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
return ch;
}
//returns -1 for "return to previous menu" or array-index of list
int querryUserPickFromList(std::vector<std::string> &list)
{
int selection = -1;
std::vector<std::string>::iterator item;
while(selection < 0 || (unsigned int)selection > list.size())
{
int itemIndex = 1;
std::cout << std::endl;
std::cout << "The following options are available:" << std::endl;
std::cout << std::endl;
for( item = list.begin();item!= list.end(); item++)
{
std::cout << std::setw(5) << std::right << itemIndex << ": " << std::setw(30) << std::left << *item << std::endl;
itemIndex++;
}
std::cout << std::endl;
std::cout << std::setw(5) << std::right << "0" << ": " << std::setw(30) << std::left << "return to previous menu" << std::endl;
std::cout << std::endl;
std::cout << "Waiting for your selection ";
int input = getch();
std::cout << std::endl;
selection = input - 48; //ascii magic
if( selection < 0 || (unsigned int)selection > list.size() )
{
std::cout << "Invalid input: '" << input << "'. press any key to take another try!" << std::endl;
getch();
}
}
return selection-1; // -1 = return ... everything else is array-index
int selection = -1;
std::vector<std::string>::iterator item;
while (selection < 0 || (unsigned int)selection > list.size())
{
int itemIndex = 1;
std::cout << std::endl;
std::cout << "The following options are available:" << std::endl;
std::cout << std::endl;
for (item = list.begin(); item != list.end(); item++)
{
std::cout << std::setw(5) << std::right << itemIndex << ": " << std::setw(30) << std::left << *item << std::endl;
itemIndex++;
}
std::cout << std::endl;
std::cout << std::setw(5) << std::right << "0" << ": " << std::setw(30) << std::left << "return to previous menu" << std::endl;
std::cout << std::endl;
std::cout << "Waiting for your selection ";
int input = getch();
std::cout << std::endl;
selection = input - 48; //ascii magic
if (selection < 0 || (unsigned int)selection > list.size())
{
std::cout << "Invalid input: '" << input << "'. press any key to take another try!" << std::endl;
getch();
}
}
return selection - 1; // -1 = return ... everything else is array-index
}
std::string getPLCName(Silecs::XMLParser &paramParser)
{
Silecs::ElementXML mappingNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping");
return mappingNode.getAttribute("plc-name");
Silecs::ElementXML mappingNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping");
return mappingNode.getAttribute("plc-name");
}
Silecs::Cluster* getSilecsClusterbyDevice(std::string deviceName, Silecs::XMLParser &paramParser, Silecs::Service *silecsService)
Silecs::PLC& getSilecsPLC(const std::string& plcName, Silecs::Service *silecsService)
{
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='"+ deviceName + "']");
std::string className = classNode.getAttribute("name");
std::string classVersion = classNode.getAttribute("version");
return silecsService->getCluster(className,classVersion);
return silecsService->getPLCHandler().getPLC(plcName);
}
Silecs::SilecsDesign& getSilecsDesignbyDevice(std::string deviceName, Silecs::XMLParser &paramParser, Silecs::Service *silecsService)
{
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='" + deviceName + "']");
std::string className = classNode.getAttribute("name");
std::string classVersion = classNode.getAttribute("version");
auto& plc = getSilecsPLC(getPLCName(paramParser), silecsService);
return plc.getDeploy().getDesign(className);
}
std::string getSilecsBlockNamebyRegisterName(std::string registerName, Silecs::XMLParser &paramParser)
{
Silecs::ElementXML blockNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class/*[*/@name='"+ registerName + "']");
return blockNode.getAttribute("name");
Silecs::ElementXML blockNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class/*[*/@name='" + registerName + "']");
return blockNode.getAttribute("name");
}
bool isRegisterInBlock(std::string registerName, std::string blockName, Silecs::XMLParser &paramParser)
bool isRegisterInBlock(std::string registerName, std::string blockName, Silecs::XMLParser &paramParser)
{
Silecs::ElementXML blockNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class/*[*/@name='"+ registerName + "']");
if( blockName == blockNode.getAttribute("name"))
return true;
return false;
Silecs::ElementXML blockNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class/*[*/@name='" + registerName + "']");
if (blockName == blockNode.getAttribute("name"))
return true;
return false;
}
std::vector<std::string> getDeviceNames(Silecs::XMLParser &paramParser)
{
std::vector< std::string > deviceNames;
boost::ptr_vector<Silecs::ElementXML> deviceNodes = paramParser.getElementsFromXPath_throwIfEmpty("/SILECS-Param/SILECS-Mapping/SILECS-Class/Instance");
boost::ptr_vector<Silecs::ElementXML>::iterator deviceNode;
for( deviceNode = deviceNodes.begin();deviceNode!= deviceNodes.end(); deviceNode++)
{
deviceNames.push_back(deviceNode->getAttribute("label"));
}
return deviceNames;
std::vector < std::string > deviceNames;
auto deviceNodes = paramParser.getElementsFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class/Instance");
for (auto deviceNode = deviceNodes.begin(); deviceNode != deviceNodes.end(); deviceNode++)
{
deviceNames.push_back(deviceNode->getAttribute("label"));
}
return deviceNames;
}
std::vector<std::string> getBlockNamesFromDeviceName(std::string deviceName, Silecs::XMLParser &paramParser)
std::vector<std::string> getBlockNamesFromDeviceName(std::string deviceName, Silecs::XMLParser &paramParser)
{
std::vector< std::string > blockNames;
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='"+ deviceName + "']");
std::string className = classNode.getAttribute("name");
boost::ptr_vector<Silecs::ElementXML> blocks = paramParser.getElementsFromXPath_throwIfEmpty("/SILECS-Param/SILECS-Mapping/SILECS-Class[@name='"+ className + "']/*[ name()='Acquisition-Block' or name()='Setting-Block' or name()='Command-Block']");
boost::ptr_vector<Silecs::ElementXML>::iterator block;
for( block = blocks.begin();block!= blocks.end(); block++)
{
//std::cout<< block->getAttribute("name") << std::endl;
blockNames.push_back(block->getAttribute("name"));
}
return blockNames;
std::vector < std::string > blockNames;
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='" + deviceName + "']");
std::string className = classNode.getAttribute("name");
auto blocks = paramParser.getElementsFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[@name='" + className + "']/*[ name()='Acquisition-Block' or name()='Setting-Block' or name()='Command-Block']");
for (auto block = blocks.begin(); block != blocks.end(); block++)
{
//std::cout<< block->getAttribute("name") << std::endl;
blockNames.push_back(block->getAttribute("name"));
}
return blockNames;
}
std::vector<std::string> getRegisterNamesFromDeviceBlockName(std::string deviceName, std::string blockName, Silecs::XMLParser &paramParser)
std::vector<std::string> getRegisterNamesFromDeviceBlockName(std::string deviceName, std::string blockName, Silecs::XMLParser &paramParser)
{
std::vector< std::string > registerNames;
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='"+ deviceName + "']");
std::string className = classNode.getAttribute("name");
boost::ptr_vector<Silecs::ElementXML> registerNodes = paramParser.getElementsFromXPath_throwIfEmpty("/SILECS-Param/SILECS-Mapping/SILECS-Class[@name='"+ className + "']/*[@name='"+ blockName + "']/*[ name()='Acquisition-Register' or name()='Setting-Register' or name()='Volatile-Register']");
boost::ptr_vector<Silecs::ElementXML>::iterator registerNode;
for( registerNode = registerNodes.begin();registerNode!= registerNodes.end(); registerNode++)
{
//std::cout<< block->getAttribute("name") << std::endl;
registerNames.push_back(registerNode->getAttribute("name"));
}
return registerNames;
std::vector < std::string > registerNames;
Silecs::ElementXML classNode = paramParser.getFirstElementFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[Instance/@label='" + deviceName + "']");
std::string className = classNode.getAttribute("name");
auto registerNodes = paramParser.getElementsFromXPath("/SILECS-Param/SILECS-Mapping/SILECS-Class[@name='" + className + "']/*[@name='" + blockName + "']/*[ name()='Acquisition-Register' or name()='Setting-Register' or name()='Volatile-Register']");
for (auto registerNode = registerNodes.begin(); registerNode != registerNodes.end(); registerNode++)
{
//std::cout<< block->getAttribute("name") << std::endl;
registerNames.push_back(registerNode->getAttribute("name"));
}
return registerNames;
}
std::string getRegisterValueAsString(Silecs::Register* reg )
std::string getRegisterValueAsString(Silecs::Register *reg)
{
std::ostringstream os;
uint32_t dim1 = reg->getDimension1();
uint32_t dim2 = reg->getDimension2();
for (unsigned int i=0; i<dim1; i++)
for (unsigned int j=0; j<dim2; j++)
os << reg->getInputValAsString(i, j) << " ";
std::ostringstream os;
uint32_t dim1 = reg->getDimension1();
uint32_t dim2 = reg->getDimension2();
for (unsigned int i = 0; i < dim1; i++)
for (unsigned int j = 0; j < dim2; j++)
os << reg->getInputValAsString(i, j) << " ";
return os.str();
}
void printTableHead()
{
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
std::cout << "| "<< std::setw(20) << std::left << "Device" << "| " << std::setw(30) << std::left << "Block" << "| " << std::setw(50) << std::left << "Register" << "| " << std::setw(30) << std::left<< "Value" << "|" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
std::cout << "| " << std::setw(20) << std::left << "Device" << "| " << std::setw(30) << std::left << "Block" << "| " << std::setw(50) << std::left << "Register" << "| " << std::setw(30) << std::left << "Value" << "|" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
}
void printRunState(Silecs::PLC *plc)
void printRunState(Silecs::PLC& plc)
{
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
if( plc->isRunning() )
std::cout << "plc run-state is: RUNNING" << std::endl;
else
std::cout << "plc run-state is: STOPPED" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
if (plc.isRunning())
std::cout << "plc run-state is: RUNNING" << std::endl;
else
std::cout << "plc run-state is: STOPPED" << std::endl;
std::cout << "------------------------------------------------------------------------------------------------------------------------------------------------" << std::endl;
}
void printRegister(Silecs::Device *device, Silecs::Register* reg )
void printRegister(Silecs::Device *device, Silecs::Register *reg)
{
if( arg_silent )
{
std::cout << getRegisterValueAsString(reg) << std::endl;
}
else
{
std::cout << "| " << std::setw(20) << std::left << device->getLabel() << "| " << std::setw(30) << std::left << reg->getBlockName() << "| " << std::setw(50) << std::left << reg->getName() << "| " << std::setw(30) << std::left << getRegisterValueAsString(reg) << "|" << std::endl;
}
if (arg_silent)
{
std::cout << getRegisterValueAsString(reg) << std::endl;
}
else
{
std::cout << "| " << std::setw(20) << std::left << device->getLabel() << "| " << std::setw(30) << std::left << reg->getBlockName() << "| " << std::setw(50) << std::left << reg->getName() << "| " << std::setw(30) << std::left << getRegisterValueAsString(reg) << "|" << std::endl;
}
}
void printBlock(Silecs::Device *device, std::string blockName,Silecs::XMLParser &paramParser)
void printBlock(Silecs::Device *device, std::string blockName, Silecs::XMLParser &paramParser)
{
device->recv(blockName);
std::vector<Silecs::Register*> regCol = device->getRegisterCollection(blockName);
std::vector<Silecs::Register*>::iterator reg;
for (reg = regCol.begin();reg != regCol.end(); reg++ )
{
if(isRegisterInBlock((*reg)->getName(), blockName, paramParser))
{
printRegister(device, *reg);
}
}
device->recv(blockName);
auto& regCol = device->getRegisterCollection(blockName);
for (auto reg = regCol.begin(); reg != regCol.end(); reg++)
{
if (isRegisterInBlock( (*reg)->getName(), blockName, paramParser))
{
printRegister(device, (*reg).get());
}
}
}
void printDevice(Silecs::Device *device, Silecs::XMLParser &paramParser)
{
std::vector<std::string> blockNames = getBlockNamesFromDeviceName(device->getLabel(), paramParser);
std::vector<std::string>::iterator blockName;
for( blockName = blockNames.begin();blockName!= blockNames.end(); blockName++)
{
device->recv(*blockName);
std::vector<Silecs::Register*> regCol = device->getRegisterCollection(*blockName);
std::vector<Silecs::Register*>::iterator reg;
for (reg = regCol.begin();reg != regCol.end(); reg++ )
{
printRegister(device, *reg);
}
}
std::vector < std::string > blockNames = getBlockNamesFromDeviceName(device->getLabel(), paramParser);
std::vector<std::string>::iterator blockName;
for (blockName = blockNames.begin(); blockName != blockNames.end(); blockName++)
{
device->recv(*blockName);
auto& regCol = device->getRegisterCollection(*blockName);
for (auto reg = regCol.begin(); reg != regCol.end(); reg++)
{
printRegister(device, (*reg).get());
}
}
}
void setRegister(Silecs::Register* reg,std::string value)
void setRegister(Silecs::Register *reg, std::string value)
{
std::cout << "Error: Setting values not yet supported."<< std::endl;
exit(EXIT_FAILURE);
std::cout << "Error: Setting values not yet supported." << std::endl;
exit (EXIT_FAILURE);
}
int connectInteractive(Silecs::Service *service, Silecs::XMLParser &paramParser)
{
std::vector<std::string> mainMenu = boost::assign::list_of("connect to plc-device")("select block")("select register")("print whole device")("print block")("print register")("query plc run state")("cold-restart plc");
Silecs::Cluster *silecsCluster = NULL;
Silecs::PLC *plc = NULL;
Silecs::Device *device = NULL;
Silecs::Register* reg = NULL;
while(true)
{
std::cout << std::setw(20) << std::right << "Device:" << std::setw(20) << std::left << startbold << arg_deviceName << endbold <<std::endl;
std::cout << std::setw(20) << std::right << "Block:" << std::setw(20) << std::left << startbold << arg_blockName << endbold <<std::endl;
std::cout << std::setw(20) << std::right << "Register:" << std::setw(20) << std::left << startbold << arg_registerName << endbold <<std::endl;
int item = querryUserPickFromList(mainMenu);
switch(item)
{
case -1:
return EXIT_SUCCESS;
case 0:
{
std::vector<std::string> devices = getDeviceNames(paramParser);
int index = querryUserPickFromList(devices);
if( index == -1 )
break;
arg_deviceName = devices[index];
arg_blockName = "";
arg_registerName = "";
silecsCluster = getSilecsClusterbyDevice(arg_deviceName, paramParser, service);
plc = silecsCluster->getPLC(getPLCName(paramParser),arg_parameterFile);
plc->connect(Silecs::MASTER_SYNCHRO,true,arg_checkChecksum);
device = plc->getDevice(arg_deviceName);
break;
}
case 1:
{
if(arg_deviceName.empty())
{
std::cout << "Please select a device first! - Press any key to continue." << std::endl;
getch();
break;
}
std::vector<std::string> blocks = getBlockNamesFromDeviceName(arg_deviceName,paramParser);
int index = querryUserPickFromList(blocks);
if( index == -1 )
break;
arg_blockName = blocks[index];
arg_registerName = "";
break;
}
case 2:
{
if(arg_deviceName.empty() || arg_blockName.empty() )
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
std::vector<std::string> registers = getRegisterNamesFromDeviceBlockName(arg_deviceName,arg_blockName,paramParser);
int index = querryUserPickFromList(registers);
if( index == -1 )
break;
arg_registerName = registers[index];
reg = device->getRegister(arg_registerName);
break;
}
case 3:
if(arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
printDevice(device, paramParser);
break;
case 4:
if(arg_deviceName.empty() || arg_blockName.empty())
{
std::cout << "Please first connect to a device and select a block! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
printBlock(device, arg_blockName, paramParser);
break;
case 5:
if(arg_deviceName.empty() || arg_blockName.empty() || arg_registerName.empty())
{
std::cout << "Please first connect to device and pick a block and a register! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
printRegister(device,reg );
break;
case 6:
if(arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
printRunState(plc);
break;
case 7:
if(arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
plc->sendColdRestart();
break;
default:
std::cout << "Invalid option:" << item << std::endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
std::vector <std::string> mainMenu = {"connect to plc-device", "select block",
"select register", "print whole device", "print block", "print register",
"query plc run state", "cold-restart plc"};
while (true)
{
std::cout << std::setw(20) << std::right << "Device:" << std::setw(20) << std::left << startbold << arg_deviceName << endbold << std::endl;
std::cout << std::setw(20) << std::right << "Block:" << std::setw(20) << std::left << startbold << arg_blockName << endbold << std::endl;
std::cout << std::setw(20) << std::right << "Register:" << std::setw(20) << std::left << startbold << arg_registerName << endbold << std::endl;
int item = querryUserPickFromList(mainMenu);
switch (item)
{
case -1:
return EXIT_SUCCESS;
case 0:
{
std::vector < std::string > devices = getDeviceNames(paramParser);
int index = querryUserPickFromList(devices);
if (index == -1)
break;
arg_deviceName = devices[index];
arg_blockName = "";
arg_registerName = "";
auto& plc = getSilecsPLC(getPLCName(paramParser), service);
plc.connect(true, arg_checkChecksum);
break;
}
case 1:
{
if (arg_deviceName.empty())
{
std::cout << "Please select a device first! - Press any key to continue." << std::endl;
getch();
break;
}
std::vector < std::string > blocks = getBlockNamesFromDeviceName(arg_deviceName, paramParser);
int index = querryUserPickFromList(blocks);
if (index == -1)
break;
arg_blockName = blocks[index];
arg_registerName = "";
break;
}
case 2:
{
if (arg_deviceName.empty() || arg_blockName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
std::vector < std::string > registers = getRegisterNamesFromDeviceBlockName(arg_deviceName, arg_blockName, paramParser);
int index = querryUserPickFromList(registers);
if (index == -1)
break;
arg_registerName = registers[index];
break;
}
case 3:
{
if (arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
auto& design = getSilecsDesignbyDevice(arg_deviceName, paramParser, service);
auto device = design.getDevice(arg_deviceName);
printDevice(device, paramParser);
break;
}
case 4:
{
if (arg_deviceName.empty() || arg_blockName.empty())
{
std::cout << "Please first connect to a device and select a block! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
auto& design = getSilecsDesignbyDevice(arg_deviceName, paramParser, service);
auto device = design.getDevice(arg_deviceName);
printBlock(device, arg_blockName, paramParser);
break;
}
case 5:
{
if (arg_deviceName.empty() || arg_blockName.empty() || arg_registerName.empty())
{
std::cout << "Please first connect to device and pick a block and a register! - Press any key to continue." << std::endl;
getch();
break;
}
printTableHead();
auto& design = getSilecsDesignbyDevice(arg_deviceName, paramParser, service);
auto device = design.getDevice(arg_deviceName);
auto& reg = device->getRegister(arg_registerName);
printRegister(device, reg.get());
break;
}
case 6:
{
if (arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
auto& plc = getSilecsPLC(getPLCName(paramParser), service);
printRunState(plc);
break;
}
case 7:
{
if (arg_deviceName.empty())
{
std::cout << "Please connect to a device first! - Press any key to continue." << std::endl;
getch();
break;
}
auto& plc = getSilecsPLC(getPLCName(paramParser), service);
plc.sendColdRestart();
break;
}
default:
std::cout << "Invalid option:" << item << std::endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int connectNonInteractive(Silecs::Service *service, Silecs::XMLParser &paramParser, bool periodicOptionSet)
{
Silecs::Cluster *silecsCluster = getSilecsClusterbyDevice(arg_deviceName, paramParser, service);
Silecs::PLC *plc = silecsCluster->getPLC(getPLCName(paramParser),arg_parameterFile);
plc->connect(Silecs::MASTER_SYNCHRO,true,arg_checkChecksum);
if(!plc->isConnected())
{
std::cout << "Error: Failed to connect to PLC."<< std::endl;
return EXIT_FAILURE;
}
if( !arg_silent )
{
printRunState(plc);
}
Silecs::Device *device = plc->getDevice(arg_deviceName);
Silecs::Register* reg = NULL;
if(!arg_registerName.empty())
{
reg = device->getRegister(arg_registerName);
arg_blockName = getSilecsBlockNamebyRegisterName(arg_registerName, paramParser);
}
if( !arg_silent )
{
printTableHead();
}
do
{
switch(arg_mode)
{
case GET_DEVICE:
printDevice(device,paramParser);
break;
case GET_BLOCK:
printBlock(device, arg_blockName, paramParser);
break;
case GET_REGISTER:
device->recv(arg_blockName);
printRegister(device, reg);
break;
case SET_REGISTER:
setRegister(reg,"");
break;
default:
std::cout << "Unknown mode defined by -m" << std::endl;
return EXIT_FAILURE;
}
usleep(periodicInterval);
}while ( periodicOptionSet );
return EXIT_SUCCESS;
auto& plc = getSilecsPLC(getPLCName(paramParser), service);
plc.connect(true, arg_checkChecksum);
if (!plc.isConnected())
{
std::cout << "Error: Failed to connect to PLC." << std::endl;
return EXIT_FAILURE;
}
if (!arg_silent)
{
printRunState(plc);
}
auto& design = getSilecsDesignbyDevice(arg_deviceName, paramParser, service);
auto device = design.getDevice(arg_deviceName);
Silecs::Register *reg = NULL;
if (!arg_registerName.empty())
{
reg = device->getRegister(arg_registerName).get();
arg_blockName = getSilecsBlockNamebyRegisterName(arg_registerName, paramParser);
}
if (!arg_silent)
{
printTableHead();
}
do
{
switch (arg_mode)
{
case GET_DEVICE:
printDevice(device, paramParser);
break;
case GET_BLOCK:
printBlock(device, arg_blockName, paramParser);
break;
case GET_REGISTER:
device->recv(arg_blockName);
printRegister(device, reg);
break;
case SET_REGISTER:
setRegister(reg, "");
break;
default:
std::cout << "Unknown mode defined by -m" << std::endl;
return EXIT_FAILURE;
}
usleep(periodicInterval);
}
while (periodicOptionSet);
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
try
{
int opt;
bool interactiveOptionSet = false;
bool periodicOptionSet = false;
while ((opt = getopt(argc, argv, ":vhcp:r:b:d:f:m:is")) != -1)
{
switch (opt)
{
case 'c':
arg_checkChecksum = false;
break;
case 'h':
printHelp();
return EXIT_SUCCESS;
case 'v':
arg_verbose = true;
break;
case 'p':
{
if(interactiveOptionSet)
{
std::cout << "Error: options '-i' and '-p' are mutually exclusive " << std::endl;
printHelp();
return EXIT_FAILURE;
}
periodicOptionSet = true;
std::istringstream ss(optarg);
ss >> periodicInterval;
break;
}
case 'r':
arg_registerName.assign(optarg);
break;
case 'd':
arg_deviceName.assign(optarg);
break;
case 'f':
arg_parameterFile.assign(optarg);
break;
case 'b':
arg_blockName.assign(optarg);
break;
case 'm':
{
std::string mode;
mode.assign(optarg);
if(mode == "GET_DEVICE")
arg_mode = GET_DEVICE;
else if( mode == "GET_BLOCK")
arg_mode = GET_BLOCK;
else if( mode == "GET_REGISTER")
arg_mode = GET_REGISTER;
else if( mode == "SET_REGISTER")
arg_mode = SET_REGISTER;
else
{
std::cout << "Error: invalid mode passed. Please check the help:" << std::endl;
printHelp();
return EXIT_FAILURE;
}
break;
}
case 'i':
if(interactiveOptionSet)
{
std::cout << "Error: options '-i' and '-p' are mutually exclusive " << std::endl;
printHelp();
return EXIT_FAILURE;
}
interactiveOptionSet = true;
break;
case 's':
arg_silent = true;
break;
case '?':
std::cout << "Unrecognized option: " << optopt << std::endl;
}
}
if( arg_mode == GET_BLOCK && arg_blockName.empty())
{
std::cout << "Error: No block-name specified, cannot execute GET_BLOCK" << std::endl;
printHelp();
return EXIT_FAILURE;
}
if( ( arg_mode == GET_REGISTER || arg_mode == SET_REGISTER ) && arg_registerName.empty())
{
std::cout << "Error: No block-name specified, cannot execute GET_REGISTER or SET_REGISTER" << std::endl;
printHelp();
return EXIT_FAILURE;
}
if( arg_parameterFile.empty() )
{
std::cout << "Error: no parameter-file was passed. You need to at least pass -f [filename]" << std::endl;
printHelp();
return EXIT_FAILURE;
}
Silecs::XMLParser::init();
Silecs::XMLParser paramParser(arg_parameterFile,true);
Silecs::Service *silecsService = NULL;
if(arg_verbose)
silecsService = Silecs::Service::getInstance(2,log_arg_verbose);
else
silecsService = Silecs::Service::getInstance(2,log_arg_base);
if(interactiveOptionSet)
{
return connectInteractive(silecsService, paramParser);
}
else
{
if( arg_deviceName.empty() )
{
std::cout << "Error: no deviceName was passed. You need to pass -d [devicename]" << std::endl;
printHelp();
return EXIT_FAILURE;
}
return connectNonInteractive(silecsService, paramParser, periodicOptionSet );
}
return EXIT_SUCCESS;
}
catch(std::string *str)
{
std::cout << str << std::endl;
}
catch(std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
catch(...)
{
std::cout << "Unexpected error caught in Main. Please notify SILECS support" << std::endl;
}
return -1;
try
{
int opt;
bool interactiveOptionSet = false;
bool periodicOptionSet = false;
while ( (opt = getopt(argc, argv, ":vhcp:r:b:d:f:m:is")) != -1)
{
switch (opt)
{
case 'c':
arg_checkChecksum = false;
break;
case 'h':
printHelp();
return EXIT_SUCCESS;
case 'v':
arg_verbose = true;
break;
case 'p':
{
if (interactiveOptionSet)
{
std::cout << "Error: options '-i' and '-p' are mutually exclusive " << std::endl;
printHelp();
return EXIT_FAILURE;
}
periodicOptionSet = true;
std::istringstream ss(optarg);
ss >> periodicInterval;
break;
}
case 'r':
arg_registerName.assign(optarg);
break;
case 'd':
arg_deviceName.assign(optarg);
break;
case 'f':
arg_parameterFile.assign(optarg);
break;
case 'b':
arg_blockName.assign(optarg);
break;
case 'm':
{
std::string mode;
mode.assign(optarg);
if (mode == "GET_DEVICE")
arg_mode = GET_DEVICE;
else if (mode == "GET_BLOCK")
arg_mode = GET_BLOCK;
else if (mode == "GET_REGISTER")
arg_mode = GET_REGISTER;
else if (mode == "SET_REGISTER")
arg_mode = SET_REGISTER;
else
{
std::cout << "Error: invalid mode passed. Please check the help:" << std::endl;
printHelp();
return EXIT_FAILURE;
}
break;
}
case 'i':
if (interactiveOptionSet)
{
std::cout << "Error: options '-i' and '-p' are mutually exclusive " << std::endl;
printHelp();
return EXIT_FAILURE;
}
interactiveOptionSet = true;
break;
case 's':
arg_silent = true;
break;
case '?':
std::cout << "Unrecognized option: " << optopt << std::endl;
}
}
if (arg_mode == GET_BLOCK && arg_blockName.empty())
{
std::cout << "Error: No block-name specified, cannot execute GET_BLOCK" << std::endl;
printHelp();
return EXIT_FAILURE;
}
if ( (arg_mode == GET_REGISTER || arg_mode == SET_REGISTER) && arg_registerName.empty())
{
std::cout << "Error: No block-name specified, cannot execute GET_REGISTER or SET_REGISTER" << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (arg_parameterFile.empty())
{
std::cout << "Error: no parameter-file was passed. You need to at least pass -f [filename]" << std::endl;
printHelp();
return EXIT_FAILURE;
}
Silecs::XMLParser::init();
Silecs::XMLParser paramParser(arg_parameterFile, true);
Silecs::Service *silecsService = NULL;
if (arg_verbose)
silecsService = Silecs::Service::getInstance(2, log_arg_verbose);
else
silecsService = Silecs::Service::getInstance(2, log_arg_base);
if (interactiveOptionSet)
{
return connectInteractive(silecsService, paramParser);
}
else
{
if (arg_deviceName.empty())
{
std::cout << "Error: no deviceName was passed. You need to pass -d [devicename]" << std::endl;
printHelp();
return EXIT_FAILURE;
}
return connectNonInteractive(silecsService, paramParser, periodicOptionSet);
}
return EXIT_SUCCESS;
}
catch(std::string *str)
{
std::cout << str << std::endl;
}
catch(std::exception &ex)
{
std::cout << ex.what() << std::endl;
}
catch(...)
{
std::cout << "Unexpected error caught in Main. Please notify SILECS support" << std::endl;
}
return -1;
}
**/*.pyc
**/*__pycache__
\ No newline at end of file
cmake_minimum_required(VERSION 3.20.2)
project(silecs-codegen)
find_package(Python COMPONENTS Interpreter)
add_test (NAME codegen-tests
COMMAND ${Python_EXECUTABLE} -m unittest
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/src/xml/
)
install (
DIRECTORY ${PROJECT_SOURCE_DIR}/src/xml
DESTINATION ${CMAKE_PROJECT_VERSION}/${PROJECT_NAME}
FILES_MATCHING PATTERN "*.py*")
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
\ No newline at end of file
# silecs-codegen
This component of the SILECS PLC-framework generates FESA and stand-alone C++ code from an existing silecs-project in order to ease the usage of the package silecs-communication-cpp
This component of the opensilecs PLC-framework generates FESA and stand-alone C++ code from an existing silecs-project in order to ease the usage of the package silecs-communication-cpp
## Getting Started
## Tests
Please check the lab-specific SILECS-Wikis for more information:
In [test](src/xml/test/) directory there are files with {test_name} which contain unit tests written using `unittest` framework. Tests conserning the migration tools are in their own corresponding folders inside [migration](src/xml/migration/).
[CERN SILECS Wiki Page][CERN_Wiki]
[GSI SILECS Wiki Page][GSI_Wiki]
## License
Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See the [LICENSE file][license] for details.
[license]: LICENSE
[CERN_Wiki]: https://wikis.cern.ch/display/SIL/SILECs+Home
[GSI_Wiki]: https://www-acc.gsi.de/wiki/Frontend/SILECS
All tests can be run together using following command from inside [src/xml](src/xml/):
```
python3 -m unittest
```
#!/bin/sh
set -e
INSTALL_DIR=$1
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT") # path where this script is located in
mkdir -p ${INSTALL_DIR}
cp -r ${SCRIPTPATH}/src/xml ${INSTALL_DIR}
\ No newline at end of file
......@@ -9,6 +9,7 @@
# be specialized on call to append the string to be stored in the file.
#
import string
import time
......@@ -54,17 +55,17 @@ def toWordArray(strg):
#=========================================================================
# C Source template (.c file)
#=========================================================================
header = """
header = string.Template("""
/* +-------------------------------------------------------------------
* | Copyright CERN 2015
* | SILECS - BE/CO-SRC
* | April 2015
* +-------------------------------------------------------------------
*
* Release : %s
* Release : ${silecsRelease}
*
* The following code has been automatically generated by SILECS.
* Code regeneration will overwrite it.
*
* N.B: This file relies on the existence of explicit C data type such
* as int8_t, uint8_t, int16_t, etc....
......@@ -73,7 +74,7 @@ header = """
* web page before including this header file.
*/
#define MODBUS_START_ADDRESS %s
#define MODBUS_START_ADDRESS ${baseAddress}
/*---------------------------------------------------------------------
* DT
......@@ -94,7 +95,7 @@ typedef struct
} dt;
#define _frombcd(a) (int)(((a>>4)*10)+(a&0x0F))
#define _tobcd(a) (((unsigned char)((a)/10)<<4)+((a)%%10))
#define _tobcd(a) (((unsigned char)((a)/10)<<4)+((a)%10))
void SILECS_set_dt(int8_t sc_100 ,int8_t sc, int8_t mn,int8_t hh,int8_t dd,int8_t mm,int32_t yy, dt *date)
{
......@@ -105,80 +106,72 @@ void SILECS_set_dt(int8_t sc_100 ,int8_t sc, int8_t mn,int8_t hh,int8_t dd,int8_
date->dd = _tobcd(dd);
date->mm = _tobcd(mm);
date->yy2 = _tobcd((int8_t)(yy/100));
date->yy1 = _tobcd((int8_t)(yy%%100));
date->yy1 = _tobcd((int8_t)(yy%100));
}
"""
""")
#=========================================================================
# DATA TYPE DEFINITION
#=========================================================================
firstBlockUDT = """
firstBlockUDT = string.Template("""
/*---------------------------------------------------------------------
* %s / v%s
* ${className} / v${classVersion}
* BLOCK Type definition
*---------------------------------------------------------------------
*/
"""
""")
blockUDT = """
blockUDT = string.Template("""
typedef struct
{
%s
} _%s_%s;
"""
$regList
} _${className}_${blockName};
""")
regScalar = """ %s %s;
"""
regScalar = string.Template(""" ${regFormat} ${regName};
""")
regArray = """ %s %s[%s];
"""
regArray = string.Template(""" ${regFormat} ${regName}[${strLen}];
""")
regArray2d = """ %s %s[%s][%s];
"""
regArray2d = string.Template(""" ${regFormat} ${regName}[${regDim}][${strLen}];
""")
stringArray = """ %s %s[%s][%s][%s];
"""
stringArray = string.Template(""" ${regFormat} ${regName}[${regDim}][${regDim2}][${strLen}];
""")
#=========================================================================
# INSTANTIATION
#=========================================================================
allocationComment = """
allocationComment = string.Template("""
/*---------------------------------------------------------------------
* MEMORY ALLOCATION
* PROTOCOL: %s
* PROTOCOL: ${plcProtocol}
*---------------------------------------------------------------------
*/
"""
""")
#======= DEVICE MODE =================
deviceModeBlockInstantiation = string.Template(""" _${className}_${blockName} ${blockName};
""")
deviceModeBlockInstantiation = """ _%s_%s %s;
"""
#deviceModeClass_deviceNumber = """
# struct {
# _%s_%s %s;
# } %s_device[%s];
#"""
deviceModeClass_deviceNumber = """
deviceModeClass_deviceNumber = string.Template("""
struct {
%s
} %s_device[NB_%s_DEVICE];
"""
deviceModeClass_deviceList = """
${blockList}
} ${className}_device[NB_${className}_DEVICE];
""")
deviceModeClass_deviceList = string.Template("""
struct {
%s
} %s;
"""
${blockList}
} ${deviceList};
""")
deviceMode_dataInstantiation = """
deviceMode_dataInstantiation = string.Template("""
typedef struct {
%s
${classList}
} _SILECS_DATA_SEGMENT;
#define SILECS_DATA_SEGMENT_MODBUS_SIZE (sizeof(_SILECS_DATA_SEGMENT)/2)
......@@ -188,21 +181,20 @@ union silecsData {
uint16_t array[SILECS_DATA_SEGMENT_MODBUS_SIZE];
} silecsData;
"""
""")
#======= BLOCK MODE =================
blockModeDeviceInstantiation_deviceList = string.Template(""" _${className}_${blockName} ${deviceName};
""")
blockModeDeviceInstantiation_deviceList = """ _%s_%s %s;
"""
blockModeBlockInstantiation = """
blockModeBlockInstantiation = string.Template("""
struct {
%s } %s_%s;
"""
${deviceList} } ${className}_${blockName};
""")
blockMode_dataInstantiation = """
blockMode_dataInstantiation = string.Template("""
typedef struct {
%s
${classList}
} _SILECS_DATA_SEGMENT;
#define SILECS_DATA_SEGMENT_MODBUS_SIZE (sizeof(_SILECS_DATA_SEGMENT)/2)
......@@ -212,7 +204,7 @@ union modbus_data {
uint16_t array[SILECS_DATA_SEGMENT_MODBUS_SIZE];
} silecsData;
"""
""")
#=========================================================================
# init
......@@ -223,44 +215,43 @@ globalAllocation = """
uint16_t modbus_data = & data;
"""
initFunctionDeviceMode = """
initFunctionDeviceMode = string.Template("""
/* Initialization function */
int SILECS_init()
{
/* Silecs version initialization */
strcpy((unsigned char *)silecsData.data.SilecsHeader_device[0].hdrBlk._version, "%s");
strcpy((unsigned char *)silecsData.data.SilecsHeader_device[0].hdrBlk._version, "${version}");
/* Silecs checksum initialization */
silecsData.data.SilecsHeader_device[0].hdrBlk._checksum = %s;
silecsData.data.SilecsHeader_device[0].hdrBlk._checksum = ${checksum};
/* Silecs user initialization */
strcpy((unsigned char *)silecsData.data.SilecsHeader_device[0].hdrBlk._user, "%s");
strcpy((unsigned char *)silecsData.data.SilecsHeader_device[0].hdrBlk._user, "${user}");
/* Silecs date initialization */
SILECS_set_dt(%s,%s,%s,%s,%s,%s,%s,&silecsData.data.SilecsHeader_device[0].hdrBlk._date);
SILECS_set_dt(${dt6},${dt5},${dt4},${dt3},${dt2},${dt1},${dt0},&silecsData.data.SilecsHeader_device[0].hdrBlk._date);
}
"""
""")
#initFunctionBlockMode = """
initFunctionBlockMode = """
initFunctionBlockMode = string.Template("""
/* Initialization function */
int SILECS_init()
{
/* Silecs version initialization */
strcpy((unsigned char *)silecsData.data.SilecsHeader_hdrBlk.device[0]._version, "%s");
strcpy((unsigned char *)silecsData.data.SilecsHeader_hdrBlk.device[0]._version, "${version}");
/* Silecs checksum initialization */
silecsData.data.SilecsHeader_hdrBlk.device[0]._checksum = %s;
silecsData.data.SilecsHeader_hdrBlk.device[0]._checksum = ${checksum};
/* Silecs user initialization */
strcpy((unsigned char *)silecsData.data.SilecsHeader_hdrBlk.device[0]._user, "%s");
strcpy((unsigned char *)silecsData.data.SilecsHeader_hdrBlk.device[0]._user, "${user}");
/* Silecs date initialization */
SILECS_set_dt(%s,%s,%s,%s,%s,%s,%s,&silecsData.data.SilecsHeader_hdrBlk.device[0]._date);
SILECS_set_dt(${dt6},${dt5},${dt4},${dt3},${dt2},${dt1},${dt0},&silecsData.data.SilecsHeader_hdrBlk.device[0]._date);
}
"""
""")
#=========================================================================
# Example generation
......@@ -270,19 +261,19 @@ instantiationExample = """/*
* Automatically generated Addressing example
*"""
deviceModeDeviceListExample = """
* This example shows how to address the register %s of block %s
* of device %s of the class %s
deviceModeDeviceListExample = string.Template("""
* This example shows how to address the register ${registerName} of block ${blockName}
* of device ${deviceLabel} of the class ${className}
*
* silecsData.%s_%s.%s.%s = ....;
*/"""
* silecsData.${className}_${deviceLabel}.${blockName}.${registerName} = ....;
*/""")
blockModeDeviceListExample = """
* This example shows how to address the register %s of block %s
* of device %s of the class %s
blockModeDeviceListExample = string.Template("""
* This example shows how to address the register ${registerName} of block ${blockName}
* of device ${deviceLabel} of the class ${className}
*
* silecsData.%s_%s.%s.%s = ....;
*/"""
* silecsData.${className}_${blockName}.${deviceLabel}.${registerName} = ....;
*/""")
#=========================================================================
# C code generation Sub-function
......@@ -290,33 +281,33 @@ blockModeDeviceListExample = """
# HEADER file ------------------------------------------------------------
def cHeader(silecsRelease, baseAddress):
return header %(silecsRelease, baseAddress)
return header.substitute(silecsRelease=silecsRelease, baseAddress=baseAddress)
# REGISTER definition ----------------------------------------------------
def cRegister(regName, regFormat, regDim, regDim2=1, strLen=1):
if strLen > 1: # if it's a string
if regDim2 > 1: # add another pair of brackets to hold the string length in case second dimension of array is set
return stringArray %(whichDIGIFormat[regFormat], regName, regDim, regDim2, strLen)
return stringArray.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName, regDim=regDim, regDim2=regDim2, strLen=strLen)
elif regDim > 1: # reuse the array2D syntax
return regArray2d %(whichDIGIFormat[regFormat], regName, regDim, strLen)
return regArray2d.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName, regDim=regDim, strLen=strLen)
else: # regular string register
return regArray %(whichDIGIFormat[regFormat], regName, strLen)
return regArray.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName, strLen=strLen)
else:
if regDim == 1 and regDim2 == 1: # scalar
return regScalar %(whichDIGIFormat[regFormat], regName)
return regScalar.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName)
elif regDim > 1 and regDim2 == 1: # array
return regArray %(whichDIGIFormat[regFormat], regName, regDim)
return regArray.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName, strLen=regDim)
else: # dim1>=1 and for whatever dim2, use double array syntax
return regArray2d %(whichDIGIFormat[regFormat], regName, regDim, regDim2)
return regArray2d.substitute(regFormat=whichDIGIFormat[regFormat], regName=regName, regDim=regDim, strLen=regDim2)
def cFirstBlockUDT(className, classVersion):
return firstBlockUDT %(className, classVersion)
return firstBlockUDT.substitute(className=className, classVersion=classVersion)
# BLOCK type definition (UDT) --------------------------------------------
def cBlockUDT(className, blockName, regList):
return blockUDT %(regList, className, blockName)
return blockUDT.substitute(regList=regList, className=className, blockName=blockName)
#============= DEVICE instantiation =============
......@@ -324,46 +315,46 @@ def cBlockUDT(className, blockName, regList):
# GLOBAL instantiation ----------------------------------------------
def cAllocationComment(plcProtocol):
return allocationComment %(plcProtocol)
return allocationComment.substitute(plcProtocol=plcProtocol)
# DEVICE MODE instantiation ----------------------------------------------
def cDeviceModeBlockInstantiation(className, blockName):
return deviceModeBlockInstantiation %(className, blockName, blockName)
return deviceModeBlockInstantiation.substitute(className=className, blockName=blockName)
def cDeviceModeClass_deviceNumber(className, blockList):
return deviceModeClass_deviceNumber %(blockList, className, className)
return deviceModeClass_deviceNumber.substitute(blockList=blockList, className=className)
def cDeviceModeClass_deviceList(blockList, deviceList):
return deviceModeClass_deviceList %(blockList, deviceList)
return deviceModeClass_deviceList.substitute(blockList=blockList, deviceList=deviceList)
def cDeviceModeDataInstantiation(classList):
return deviceMode_dataInstantiation %(classList)
return deviceMode_dataInstantiation.substitute(classList=classList)
# BLOCK MODE instantiation ----------------------------------------------
def cBlockModeDeviceInstantiation_deviceList(className, blockName, deviceName):
return blockModeDeviceInstantiation_deviceList %(className, blockName, deviceName)
return blockModeDeviceInstantiation_deviceList.substitute(className=className, blockName=blockName, deviceName=deviceName)
def cBlockModeBlockInstantiation(deviceList, className, blockName):
return blockModeBlockInstantiation %(deviceList, className, blockName)
return blockModeBlockInstantiation.substitute(deviceList=deviceList, className=className, blockName=blockName)
def cBlockModeDataInstantiation(classList):
return blockMode_dataInstantiation %(classList)
return blockMode_dataInstantiation.substitute(classList=classList)
# Init Function ----------------------------------------------
def cInitDeviceMode(ieVersion,ieChecks,ieUser):
dt = time.localtime(time.time())
return initFunctionDeviceMode %("SILECS_"+ieVersion,ieChecks,ieUser,dt[6],dt[5],dt[4],dt[3],dt[2],dt[1],dt[0])
return initFunctionDeviceMode.substitute(version="SILECS_"+ieVersion, checksum=ieChecks, user=ieUser, dt6=dt[6], dt5=dt[5], dt4=dt[4], dt3=dt[3], dt2=dt[2], dt1=dt[1], dt0=dt[0])
def cInitBlockMode(ieVersion,ieChecks,ieUser):
dt = time.localtime(time.time())
return initFunctionBlockMode %("SILECS_"+ieVersion,ieChecks,ieUser,dt[6],dt[5],dt[4],dt[3],dt[2],dt[1],dt[0])
return initFunctionBlockMode.substitute(version="SILECS_"+ieVersion, checksum=ieChecks, user=ieUser, dt6=dt[6], dt5=dt[5], dt4=dt[4], dt3=dt[3], dt2=dt[2], dt1=dt[1], dt0=dt[0])
# Example function ----------------------------------------------
def cExample(plcProtocol,className, blockName, registerName, deviceLabel =''):
if plcProtocol == 'DEVICE_MODE':
return instantiationExample + deviceModeDeviceListExample %(registerName, blockName, deviceLabel, className, className, deviceLabel, blockName, registerName)
return instantiationExample + deviceModeDeviceListExample.substitute(registerName=registerName, blockName=blockName, deviceLabel=deviceLabel, className=className)
else:
return instantiationExample + blockModeDeviceListExample %(registerName, blockName, deviceLabel, className, className, blockName, deviceLabel, registerName)
return instantiationExample + blockModeDeviceListExample.substitute(registerName=registerName, blockName=blockName, deviceLabel=deviceLabel, className=className)
......@@ -18,77 +18,79 @@
# FESA .cproject file
#=========================================================================
import string
cproject = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cern.fesa.plugin.build.configuration.537108490">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cern.fesa.plugin.build.configuration.537108490" moduleId="org.eclipse.cdt.core.settings" name="FESA Make Build">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration buildProperties="" description="" id="cern.fesa.plugin.build.configuration.537108490" name="FESA Make Build" parent="cern.fesa.plugin.build.configuration">
<folderInfo id="cern.fesa.plugin.build.configuration.537108490." name="/" resourcePath="">
<toolChain id="cern.fesa.plugin.build.toolchain.1156032800" name="FESA Toolchain" superClass="cern.fesa.plugin.build.toolchain">
<targetPlatform id="cern.fesa.plugin.build.targetplatform.67227612" isAbstract="false" superClass="cern.fesa.plugin.build.targetplatform"/>
<builder id="cern.fesa.plugin.build.builder.1302129891" name="Gnu Make Builder.FESA Make Build" superClass="cern.fesa.plugin.build.builder"/>
<tool id="cern.fesa.plugin.build.archiver.1068962328" name="GCC Archiver" superClass="cern.fesa.plugin.build.archiver"/>
<tool id="cern.fesa.plugin.build.compiler.648804671" name="GCC C++ Compiler" superClass="cern.fesa.plugin.build.compiler">
<option id="gnu.cpp.compiler.option.include.paths.12841593" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
</option>
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2129597065" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.662860517" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1388561052" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.365658250" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cern.fesa.plugin.build.linker.884627432" name="GCC C++ Linker" superClass="cern.fesa.plugin.build.linker">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.2024588043" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cern.fesa.plugin.build.assembler.838409637" name="GCC Assembler" superClass="cern.fesa.plugin.build.assembler">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1405521367" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="" name=""/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="all x86_64" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>-j16 CPU=x86_64 </buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
<storageModule moduleId="scannerConfiguration"/>
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cern.fesa.plugin.build.configuration.537108490">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cern.fesa.plugin.build.configuration.537108490" moduleId="org.eclipse.cdt.core.settings" name="FESA Make Build">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration buildProperties="" description="" id="cern.fesa.plugin.build.configuration.537108490" name="FESA Make Build" parent="cern.fesa.plugin.build.configuration">
<folderInfo id="cern.fesa.plugin.build.configuration.537108490." name="/" resourcePath="">
<toolChain id="cern.fesa.plugin.build.toolchain.1156032800" name="FESA Toolchain" superClass="cern.fesa.plugin.build.toolchain">
<targetPlatform id="cern.fesa.plugin.build.targetplatform.67227612" isAbstract="false" superClass="cern.fesa.plugin.build.targetplatform"/>
<builder id="cern.fesa.plugin.build.builder.1302129891" name="Gnu Make Builder.FESA Make Build" superClass="cern.fesa.plugin.build.builder"/>
<tool id="cern.fesa.plugin.build.archiver.1068962328" name="GCC Archiver" superClass="cern.fesa.plugin.build.archiver"/>
<tool id="cern.fesa.plugin.build.compiler.648804671" name="GCC C++ Compiler" superClass="cern.fesa.plugin.build.compiler">
<option id="gnu.cpp.compiler.option.include.paths.12841593" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
</option>
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2129597065" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.662860517" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1388561052" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.365658250" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cern.fesa.plugin.build.linker.884627432" name="GCC C++ Linker" superClass="cern.fesa.plugin.build.linker">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.2024588043" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cern.fesa.plugin.build.assembler.838409637" name="GCC Assembler" superClass="cern.fesa.plugin.build.assembler">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1405521367" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="" name=""/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="all x86_64" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>-j16 CPU=x86_64 </buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
<storageModule moduleId="scannerConfiguration"/>
</cproject>
"""
......@@ -96,24 +98,22 @@ cproject = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
# H Source template (.h file)
#=========================================================================
htop = """/*
htop = string.Template("""/*
* ${className}.h
*
* Generated by SILECS framework tools
* Generated by SILECS framework tools. Will be overwritten on regeneration.
*/
#ifndef ${className}_${className}_H_
#define ${className}_${className}_H_
#include <SilecsService.h>
#include <silecs-communication/interface/core/SilecsService.h>
#include <silecs-communication/interface/equipment/SilecsPLC.h>
#include <fesa-core/Synchronization/MultiplexingContext.h>
#include <${className}/GeneratedCode/ServiceLocator.h>
"""
hTopBlock = """#include <${className}/Server/${blockName}.h>
"""
""")
hTop2 = """
hTop2 = string.Template("""
namespace ${className}
{
......@@ -152,14 +152,14 @@ namespace ${className}
{
public:
static inline Silecs::Service* theService() { return pService_; }
static inline Silecs::Cluster* theCluster() { return pCluster_; }
static inline Silecs::PLCHandler* thePLCHandler() { return pPLCHandler_; }
inline std::string& getBlockName() { return blockName_; }
static void setup(const ServiceLocator* serviceLocator);
static void cleanup();
static bool isInitialized(){ return Abstract${className}::isInitialized_; }
static void setPLCSlaveRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator);
static void getPLCMasterRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator);
static void updatePLCRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator);
static void updateFesaFields(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator);
Abstract${className}(std::string blockName);
virtual ~Abstract${className}();
......@@ -175,9 +175,9 @@ namespace ${className}
virtual void setOneDevice(Device* pDevice, const bool sendNow, MultiplexingContext* pContext);
protected:
static void checkInitialized();
static Silecs::Service* pService_;
static Silecs::Cluster* pCluster_;
static Silecs::PLCHandler* pPLCHandler_;
static bool isInitialized_;
// Name of the silecs-block which is addressed
......@@ -187,45 +187,43 @@ namespace ${className}
Abstract${className}(const Abstract${className}&);
Abstract${className}& operator=(const Abstract${className}&);
};
""")
// -------------------------------------------------------------------------------------------------
#define BLOCK_RO( blockName, propName )\t\\
class blockName##_Type : public Abstract${className}\t\\
{\t\\
public:\t\\
blockName##_Type(std::string name);\t\\
~blockName##_Type();\t\\
void getOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);\t\\
}
#define BLOCK_WO( blockName, propName )\t\\
class blockName##_Type : public Abstract${className}\t\\
{\t\\
public:\t\\
blockName##_Type(std::string name);\t\\
~blockName##_Type();\t\\
void setOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);\t\\
void setOneDevice(Device* pDevice, propName##PropertyData& data, const bool transmitNow, MultiplexingContext* pContext);\t\\
}
hReadBlock= string.Template("""
class ${blockName}_Type : public Abstract${className}
{
public:
${blockName}_Type(std::string name);
~${blockName}_Type();
void getOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);
};
""")
#define BLOCK_RW( blockName, propName )\t\\
class blockName##_Type : public Abstract${className}\t\\
{\t\\
public:\t\\
blockName##_Type(std::string name);\t\\
~blockName##_Type();\t\\
void getOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);\t\\
void setOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);\t\\
void setOneDevice(Device* pDevice, propName##PropertyData& data, const bool transmitNow, MultiplexingContext* pContext);\t\\
}
"""
hWriteBlock= string.Template("""
class ${blockName}_Type : public Abstract${className}
{
public:
${blockName}_Type(std::string name);
~${blockName}_Type();
void setOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);
void setOneDevice(Device* pDevice, const ${propName}PropertyData& data, const bool transmitNow, MultiplexingContext* pContext);
};
""")
hBlock = """BLOCK_${mode}( ${blockName}, ${propName} );
"""
hReadWriteBlock= string.Template("""
class ${blockName}_Type : public Abstract${className}
{
public:
${blockName}_Type(std::string name);
~${blockName}_Type();
void getOneDevice(Device* pDevice, const bool recvNow, MultiplexingContext* pContext);
void getOneDevice(Device* pDevice, ${propName}PropertyData& data, const bool recvNow);
void setOneDevice(Device* pDevice, const bool transmitNow, MultiplexingContext* pContext);
void setOneDevice(Device* pDevice, const ${propName}PropertyData& data, const bool transmitNow, MultiplexingContext* pContext);
};
""")
hBottom = """
hBottom = string.Template("""
/*---------------------------------------------------------------------------------------------------------
* INTERFACE
*---------------------------------------------------------------------------------------------------------
......@@ -235,36 +233,37 @@ hBottom = """
{
public:
static inline Silecs::Service* theService() { return Abstract${className}::theService(); }
static inline Silecs::Cluster* theCluster() { return Abstract${className}::theCluster(); }
static inline Silecs::PLCHandler* thePLCHandler() { return Abstract${className}::thePLCHandler(); }
static void setup(const ServiceLocator* serviceLocator) { Abstract${className}::setup(serviceLocator); }
static void cleanup() { Abstract${className}::cleanup(); }
static bool isInitialized(){ return Abstract${className}::isInitialized(); }
static Silecs::PLC* getPLC(Device* pDevice)
{
return Abstract${className}::theCluster()->getPLC(pDevice->plcHostName.get());
return &Abstract${className}::thePLCHandler()->getPLC(pDevice->plcHostName.get());
}
"""
""")
hDeclBlocks = """
static ${className}_Type ${className};"""
hDeclBlocks = string.Template("""
static ${className}_Type ${className};""")
hClosing = """
hClosing = string.Template("""
};
}
#endif /* ${className}_${className}_H_ */
"""
""")
#=========================================================================
# C++ Source template (.cpp file)
#=========================================================================
cTop = """/*
cTop = string.Template("""/*
* ${className}.cpp
*
* Generated by SILECS framework tools
* Generated by SILECS framework tools. Will be overwritten on regeneration.
*/
#include <${className}/Common/${className}.h>
#include <silecs-communication/interface/utility/SilecsException.h>
#include <fesa-core/Synchronization/NoneContext.h>
#include <fesa-core/Synchronization/MultiplexingContext.h>
......@@ -272,29 +271,28 @@ namespace ${className}
{
//Global objects of the SILECS class
Silecs::Service* Abstract${className}::pService_ = NULL;
Silecs::Cluster* Abstract${className}::pCluster_ = NULL;
Silecs::PLCHandler* Abstract${className}::pPLCHandler_ = NULL;
bool Abstract${className}::isInitialized_ = false;
""")
"""
cGlobal = """${blockName}_Type\t${className}::${blockName}("${blockName}");
"""
cPart1 = """
cGlobal = string.Template("""${blockName}_Type\t${className}::${blockName}("${blockName}");
""")
cPart1 = string.Template("""
//-------------------------------------------------------------------------------------------------------------
// Constructor & Destructor methods
Abstract${className}::Abstract${className}(std::string blockName): blockName_(blockName) {}
Abstract${className}::~Abstract${className}() {}
"""
""")
cBlockConstr = """
cBlockConstr = string.Template("""
${blockName}_Type::${blockName}_Type(std::string name): Abstract${className}(name) {}
${blockName}_Type::~${blockName}_Type() {}
"""
""")
cPart2 = """
cPart2 = string.Template("""
//---------------------------------------------------------------------------------------------------------
// Set-up the SILECS components for the Abstract${className} class (service & cluster)
// Set-up the SILECS components for the Abstract${className} class (service & plchandler)
void Abstract${className}::setup(const ServiceLocator* serviceLocator)
{
......@@ -306,12 +304,11 @@ cPart2 = """
// Enable the SILECS diagnostic with user topics if any
pService_->setArguments(serviceLocator->getUsrCmdArgs());
// Instantiate the SILECS Cluster object for the given Class/Version
GlobalDevice* pGlobalDevice = serviceLocator->getGlobalDevice();
pCluster_ = pService_->getCluster( "${className}", pGlobalDevice->plcClassVersion.get());
pPLCHandler_ = &pService_->getPLCHandler();
isInitialized_ = true;
// Connect each PLC of the Cluster that is referred from the FESA instance
// Connect each PLC of the PLCHandler that is referred from the FESA instance
std::vector<Device*> pDeviceCol = serviceLocator->getDeviceCollection();
for(std::vector<Device*>::iterator pDeviceIter=pDeviceCol.begin(); pDeviceIter!= pDeviceCol.end(); pDeviceIter++)
{
......@@ -319,18 +316,16 @@ cPart2 = """
// Retrieve the PLC related to the current FESA device
// (from 'plcHostName' FESA field defined on that purpose).
Silecs::PLC* pPLC = pCluster_->getPLC(pDevice->plcHostName.get());
Silecs::PLC* pPLC = &pPLCHandler_->getPLC(pDevice->plcHostName.get());
// Update the PLC Slave registers from related FESA fields just before synchronising done at connection time
setPLCSlaveRegisters(pPLC, serviceLocator);
// Update PLC registers from related FESA fields just before synchronising done at connection time
updatePLCRegisters(pPLC, serviceLocator);
// Connect the PLC if not already connected
if (!pPLC->isEnabled())
{ pPLC->connect(/*synchroMode=*/Silecs::FULL_SYNCHRO, /*connectNow=*/true);
{ pPLC->connect(/*connectNow=*/true);
if (pPLC->isConnected())
{ // Update FESA fields from related PLC Master registers just after synchronising done at connection time
getPLCMasterRegisters(pPLC, serviceLocator);
}
updateFesaFields(pPLC, serviceLocator);
}
}
}
......@@ -345,35 +340,40 @@ cPart2 = """
void Abstract${className}::cleanup()
{
// Attention! This method is responsible to stop all the PLC connections
// and to remove all the SILECS resources (Clusters and related components: PLCs, Devices, Registers, ..)
// and to remove all the SILECS resources (PLCs, Devices, Registers, ..)
// Calling method must ensure that no process is currently accessing these resources before cleaning.
//
Silecs::Service::deleteInstance();
}
""")
updatePLCRegisters_start = string.Template("""
//---------------------------------------------------------------------------------------------------------
// Synchronise PLC SLAVE/MASTER registers and related FESA fields (automatically called by the setup method @connection time)
void Abstract${className}::setPLCSlaveRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator)
//automatically called by the setup method at connection time)
void Abstract${className}::updatePLCRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator)
{
fesa::NoneContext noneContext;
"""
cSetPLC = """
${className}::${blockName}.setPLCDevices(pPLC, serviceLocator, false, &noneContext);"""
cPart3 = """
""")
updatePLCRegisters_body = string.Template("""
${className}::${blockName}.setPLCDevices(pPLC, serviceLocator, false, &noneContext);""")
updatePLCRegisters_end = """
}
"""
void Abstract${className}::getPLCMasterRegisters(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator)
updateFesaFields_start = string.Template("""
//---------------------------------------------------------------------------------------------------------
//automatically called by the setup method at connection time)
void Abstract${className}::updateFesaFields(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator)
{
fesa::NoneContext noneContext; //MASTER acquisition fields are not consistent, can be set with none-context
"""
cGetPLC = """
${className}::${blockName}.getPLCDevices(pPLC, serviceLocator, false, &noneContext);"""
cPart4 = """
fesa::NoneContext noneContext;
""")
updateFesaFields_body = string.Template("""
${className}::${blockName}.getPLCDevices(pPLC, serviceLocator, false, &noneContext);""")
updateFesaFields_end = """
}
"""
cPart4 = string.Template("""
//---------------------------------------------------------------------------------------------------------
// General methods to synchronize the FESA fields and related PLC registers of the FESA server
......@@ -385,7 +385,7 @@ cPart4 = """
void Abstract${className}::getAllDevices(const ServiceLocator* serviceLocator, const bool recvNow, MultiplexingContext* pContext)
{
if (recvNow) theCluster()->recv(blockName_);
if (recvNow) thePLCHandler()->recv(blockName_);
std::vector<Device*> deviceCol = serviceLocator->getDeviceCollection();
for(std::vector<Device*>::iterator pDeviceIter=deviceCol.begin(); pDeviceIter!= deviceCol.end(); pDeviceIter++)
......@@ -423,7 +423,7 @@ cPart4 = """
{ setOneDevice(*pDeviceIter, false, pContext);
}
if (sendNow) theCluster()->send(blockName_);
if (sendNow) thePLCHandler()->send(blockName_);
}
void Abstract${className}::setPLCDevices(Silecs::PLC* pPLC, const ServiceLocator* serviceLocator, bool sendNow, MultiplexingContext* pContext)
......@@ -447,241 +447,234 @@ cPart4 = """
void Abstract${className}::setOneDevice(Device* pDevice, const bool sendNow, MultiplexingContext* pContext) {};
void Abstract${className}::checkInitialized()
{
if( !isInitialized_ )
{
throw fesa::FesaException(__FILE__, __LINE__, "SILECS-Service not initialized yet - "
"${className}::setup needs to be called before any plc-interaction can be done");
}
};
//---------------------------------------------------------------------------------------------------------
"""
""")
cCommonGet = """
cCommonGet = string.Template("""
void ${blockName}_Type::getOneDevice(Device* pDevice, const bool recvNow, MultiplexingContext* pContext)
{
if( !isInitialized_ )
{
throw fesa::FesaException(__FILE__, __LINE__, "SILECS-Service not initialized yet - ${className}::setup needs to be called before any plc-interaction can be done");
}
Silecs::PLC* pPLC = pCluster_->getPLC(pDevice->plcHostName.get(),pDevice->parameterFile.get());
Silecs::Device* pPLCDevice = pPLC->getDevice(pDevice->plcDeviceLabel.get());
"""
checkInitialized();
Silecs::PLC* pPLC = &pPLCHandler_->getPLC(pDevice->plcHostName.get());
Silecs::Device* pPLCDevice = pPLC->getDeploy().getDesign("${className}").getDevice(pDevice->plcDeviceLabel.get());
""")
cRecv = """ if (recvNow) pPLCDevice -> recv(blockName_);
cDatatypeGet = string.Template("""
void ${blockName}_Type::getOneDevice(Device* pDevice, ${propName}PropertyData& data, const bool recvNow)
{
checkInitialized();
Silecs::PLC* pPLC = &pPLCHandler_->getPLC(pDevice->plcHostName.get());
Silecs::Device* pPLCDevice = pPLC->getDeploy().getDesign("${className}").getDevice(pDevice->plcDeviceLabel.get());
""")
cRecv = """ if (recvNow) pPLCDevice -> recv(blockName_);
"""
cGetStringReg = """
cGetStringReg = string.Template("""
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
pDevice->${fesaFieldName}.set(pRegister->getValString().c_str(), pContext);
auto& pRegister = pPLCDevice->getRegister("${regName}");
pDevice->${fesaFieldName}.set(pRegister->getVal<std::string>().c_str(), pContext);
}
"""
""")
cGetStringArrayReg = """
cGetStringRegData = string.Template("""
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
const std::string** stdStringArray = pRegister->getRefStringArray(dim1);
for (unsigned int i=0; i<dim1; i++)
{
pDevice->${fesaFieldName}.setString(stdStringArray[i]->c_str(), i, pContext);
}
auto& pRegister = pPLCDevice->getRegister("${regName}");
data.set${fesaFieldName_upper}(pRegister->getVal<std::string>().c_str());
}
"""
cGetScalarReg = """
pDevice->${fesaFieldName}.set( pPLCDevice->getRegister("${regName}")->getVal${regType}(), pContext);"""
""")
cGetArrayReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
pDevice->${fesaFieldName}.set(pRegister->getRef${regType}Array(dim1), dim1, pContext);
}
"""
cGetArray2DReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
uint32_t dim2 = pRegister->getDimension2();
pDevice->${fesaFieldName}.set(pRegister->getRef${regType}Array2D(dim1, dim2), dim1, dim2, pContext);
}
"""
cGetScalarReg = string.Template("""
pDevice->${fesaFieldName}.set( pPLCDevice->getRegister("${regName}")->getVal<${regType}>(), pContext);""")
cGetUnsignedArrayReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
${regType}* ${regName} = (${regType}*)calloc(dim1, sizeof(${regType}));
pRegister->getVal${regType}Array(${regName}, dim1);\t//use automatic conversion for JAVA non-supported type
pDevice->${fesaFieldName}.set(${regName}, dim1, pContext);
free(${regName});
}
"""
cGetScalarRegData = string.Template("""
data.set${fesaFieldName_upper}(pPLCDevice->getRegister("${regName}")->getVal<${regType}>());""")
cGetUnsignedArray2DReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
uint32_t dim2 = pRegister->getDimension2();
${fesaType}* ${regName} = (${fesaType}*)calloc(dim1*dim2, sizeof(${fesaType}));
pRegister->getVal${regType}Array2D(${regName}, dim1, dim2);\t//use automatic conversion for JAVA non-supported type
pDevice->${fesaFieldName}.set(${regName}, dim1, dim2, pContext);
free(${regName});
}
"""
cGetCustomScalarReg = string.Template("""
pDevice->${fesaFieldName}.set(static_cast<${enumName}::${enumName}>(pPLCDevice->getRegister("${regName}")->getVal<${regType}>()), pContext);""")
cCommonSet = """
cGetCustomScalarRegData = string.Template("""
data.set${fesaFieldName_upper}(static_cast<${enumName}::${enumName}>(pPLCDevice->getRegister("${regName}")->getVal<${regType}>()));""")
cCommonSet = string.Template("""
void ${blockName}_Type::setOneDevice(Device* pDevice, const bool sendNow, MultiplexingContext* pContext)
{
if( !isInitialized_ )
{
throw fesa::FesaException(__FILE__, __LINE__, "SILECS-Service not initialized yet - ${className}::setup needs to be called before any plc-interaction can be done");
}
Silecs::PLC* pPLC = pCluster_->getPLC(pDevice->plcHostName.get(),pDevice->parameterFile.get());
Silecs::Device* pPLCDevice = pPLC->getDevice(pDevice->plcDeviceLabel.get());
"""
checkInitialized();
Silecs::PLC* pPLC = &pPLCHandler_->getPLC(pDevice->plcHostName.get());
Silecs::Device* pPLCDevice = pPLC->getDeploy().getDesign("${className}").getDevice(pDevice->plcDeviceLabel.get());
""")
cSend = """
if (sendNow) pPLCDevice->send(blockName_);
"""
cDatatypeSet = """
void ${blockName}_Type::setOneDevice(Device* pDevice, ${propName}PropertyData& data, bool sendNow, MultiplexingContext* pContext)
cDatatypeSet = string.Template("""
void ${blockName}_Type::setOneDevice(Device* pDevice, const ${propName}PropertyData& data, bool sendNow, MultiplexingContext* pContext)
{
if( !isInitialized_ )
{
throw fesa::FesaException(__FILE__, __LINE__, "SILECS-Service not initialized yet - ${className}::setup needs to be called before any plc-interaction can be done");
}
Silecs::PLC* pPLC = pCluster_->getPLC(pDevice->plcHostName.get(),pDevice->parameterFile.get());
Silecs::Device* pPLCDevice = pPLC->getDevice(pDevice->plcDeviceLabel.get());
"""
checkInitialized();
Silecs::PLC* pPLC = &pPLCHandler_->getPLC(pDevice->plcHostName.get());
Silecs::Device* pPLCDevice = pPLC->getDeploy().getDesign("${className}").getDevice(pDevice->plcDeviceLabel.get());
""")
cSetStringReg = """
pPLCDevice->getRegister("${regName}")->setValString(pDevice->${fesaFieldName}.get(pContext));
"""
cSetStringReg = string.Template("""
pPLCDevice->getRegister("${regName}")->setVal<std::string>(pDevice->${fesaFieldName}.get(${context}));
""")
cSetStringArrayReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
std::string stdStringArray[dim1];
uint32_t fesaDim1;
const char** cStringArray = pDevice->${fesaFieldName}.get(fesaDim1, pContext);
for (unsigned int i=0; i<dim1; i++) stdStringArray[i] = (const char*)cStringArray[i];
pRegister->setValStringArray(stdStringArray, dim1);
}
"""
cSetScalarReg = string.Template("""
pPLCDevice->getRegister("${regName}")->setVal<${regType}>( ${cCast}pDevice->${fesaFieldName}.get(${context}));""")
cSetScalarReg = """
pPLCDevice->getRegister("${regName}")->setVal${regType}( pDevice->${fesaFieldName}.get(pContext));"""
cSetScalarUReg = """
pPLCDevice->getRegister("${regName}")->setVal${regType}( (${cType})pDevice->${fesaFieldName}.get(pContext));"""
cSetStringRegData = string.Template("""
(data.is${fesaFieldName_upper}Available()) ? pPLCDevice->getRegister("${regName}")->setVal<std::string>(data.${fesaFieldName}.get()) :
pPLCDevice->getRegister("${regName}")->setVal<std::string>(pDevice->${fesaFieldName}.get(${context}));""")
cSetArrayReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
uint32_t fesaDim1;
pRegister->setVal${regType}Array(pDevice->${fesaFieldName}.get(fesaDim1, pContext), dim1);
}
"""
cSetScalarRegData = string.Template("""
(data.is${fesaFieldName_upper}Available()) ? pPLCDevice->getRegister("${regName}")->setVal<${regType}>( ${cCast}data.${fesaFieldName}.get()) :
pPLCDevice->getRegister("${regName}")->setVal<${regType}>( ${cCast}pDevice->${fesaFieldName}.get(${context}));""")
cSetArray2DReg = """
cGeneral = string.Template("""
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
dim2 = pRegister->getDimension2();
uint32_t fesaDim1,fesaDim2;
pRegister->setVal${regType}Array2D(pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2, pContext), dim1, dim2);
auto& pRegister = pPLCDevice->getRegister("${regName}");
${contents}
}
"""
""")
cSetUnsignedArrayReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
uint32_t fesaDim1;
pRegister->setVal${regType}Array(pDevice->${fesaFieldName}.get(fesaDim1, pContext), dim1);\t//use automatic conversion for JAVA non-supported type
}
"""
cArray = string.Template("""uint32_t dim1 = pRegister->getDimension1();
${contents}""")
cSetUnsignedArray2DReg = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
dim2 = pRegister->getDimension2();
uint32_t fesaDim1,fesaDim2;
pRegister->setVal${regType}Array2D( pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2, pContext), dim1, dim2);\t//use automatic conversion for JAVA non-supported type
}
"""
cArraySetContents = string.Template("""uint32_t fesaDim1;
${contents}""")
cSetStringRegData = """
(data.is${fesaFieldName_upper}Available()) ? pPLCDevice->getRegister("${regName}")->setValString(data.${fesaFieldName}.get()) :
pPLCDevice->getRegister("${regName}")->setValString(pDevice->${fesaFieldName}.get(pContext));"""
cSetStringArrayRegData = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
std::string stdStringArray[dim1];
uint32_t fesaDim1;
const char** cStringArray = (data.is${fesaFieldName_upper}Available() ? data.${fesaFieldName}.get(fesaDim1) : pDevice->${fesaFieldName}.get(fesaDim1, pContext));
cArraySetData = string.Template("""const ${fesaType}* ${regName};
(data.is${fesaFieldName_upper}Available()) ? ${regName} = data.${fesaFieldName}.get(fesaDim1) :
${regName} = pDevice->${fesaFieldName}.get(fesaDim1${context});
std::vector<${regType}> data(${regName}, ${regName} + dim1);
pRegister->setValArray<${regType}>(data.data(), dim1);""")
cArraySetDataSigned = string.Template("""(data.is${fesaFieldName_upper}Available()) ? pRegister->setValArray<${regType}>( data.${fesaFieldName}.get(fesaDim1), dim1) :
pRegister->setValArray<${regType}>( pDevice->${fesaFieldName}.get(fesaDim1${context}), dim1);""")
cArraySetSigned = string.Template("""pRegister->setValArray<${regType}>(pDevice->${fesaFieldName}.get(fesaDim1${context}), dim1);""")
cArraySet = string.Template("""const ${fesaType}* ${regName} = pDevice->${fesaFieldName}.get(fesaDim1${context});
std::vector<${regType}> data(${regName}, ${regName} + dim1);
pRegister->setValArray<${regType}>(data.data(), dim1);""")
cArraySetString = string.Template("""std::string stdStringArray[dim1];
const char* const* cStringArray = pDevice->${fesaFieldName}.get(fesaDim1${context});
for (unsigned int i=0; i<dim1; i++) stdStringArray[i] = (const char*)cStringArray[i];
pRegister->setValStringArray(stdStringArray, dim1);
}
"""
pRegister->setValArray<std::string>(stdStringArray, dim1);""")
cSetScalarRegData = """
(data.is${fesaFieldName_upper}Available()) ? pPLCDevice->getRegister("${regName}")->setVal${regType}( data.${fesaFieldName}.get()) :
pPLCDevice->getRegister("${regName}")->setVal${regType}( pDevice->${fesaFieldName}.get(pContext));"""
cArraySetDataString = string.Template("""std::string stdStringArray[dim1];
const char* const* cStringArray = (data.is${fesaFieldName_upper}Available() ? data.${fesaFieldName}.get(fesaDim1) : pDevice->${fesaFieldName}.get(fesaDim1${context}));
for (unsigned int i=0; i<dim1; i++) stdStringArray[i] = (const char*)cStringArray[i];
pRegister->setValArray<std::string>(stdStringArray, dim1);""")
cSetScalarURegData = """
(data.is${fesaFieldName_upper}Available()) ? pPLCDevice->getRegister("${regName}")->setVal${regType}( (${cType})data.${fesaFieldName}.get()) :
pPLCDevice->getRegister("${regName}")->setVal${regType}( (${cType})pDevice->${fesaFieldName}.get(pContext));"""
cSetArrayRegData = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
uint32_t fesaDim1;
(data.is${fesaFieldName_upper}Available()) ? pRegister->setVal${regType}Array( data.${fesaFieldName}.get(fesaDim1), dim1) :
pRegister->setVal${regType}Array( pDevice->${fesaFieldName}.get(fesaDim1, pContext), dim1);
}
"""
cSetArray2DRegData = """
{
Silecs::Register* pRegister = pPLCDevice->getRegister("${regName}");
uint32_t dim1 = pRegister->getDimension1();
cArrayGetSigned = string.Template("""pDevice->${fesaFieldName}.set(pRegister->getRefArray<${regType}>(dim1), dim1, pContext);""")
cArrayGet = string.Template("""data.set${fesaFieldName_upper}(pRegister->getRefArray<${regType}>(dim1), dim1);""")
cArrayGetCustom = string.Template("""${regType}* arrData = pRegister->getRefArray<${regType}>(dim1);
std::vector<${enumName}::${enumName}> ${regName};
for(uint32_t i = 0; i < dim1; ++i)
{
${regName}.push_back(static_cast<${enumName}::${enumName}>(*(arrData + i)));
}
${contents}""")
cArrayGetUnsigned = string.Template("""${regType}* arrData = pRegister->getRefArray<${regType}>(dim1);
std::vector<${fesaType}> ${regName}(arrData, arrData + dim1);
${contents}""")
cArrayGetReg = string.Template("""pDevice->${fesaFieldName}.set(${regName}.data(), dim1, pContext);""")
cArrayGetData = string.Template("""data.set${fesaFieldName_upper}(${regName}.data(), dim1);""")
cArrayGetStringReg = string.Template("""const std::string** stdStringArray = pRegister->getRefArray<const std::string*>(dim1);
for (unsigned int i=0; i<dim1; i++)
{
pDevice->${fesaFieldName}.setString(stdStringArray[i]->c_str(), i, pContext);
}""")
cArrayGetStringData = string.Template("""const std::string** stdStringArray = pRegister->getRefArray<const std::string*>(dim1);
std::vector<std::string> strings;
for (unsigned int i=0; i<dim1; i++)
{
strings.push_back(stdStringArray[i]->c_str());
}
data.set${fesaFieldName_upper}(strings);""")
cArray2D = string.Template("""uint32_t dim1 = pRegister->getDimension1();
uint32_t dim2 = pRegister->getDimension2();
uint32_t fesaDim1,fesaDim2;
(data.is${fesaFieldName_upper}Available()) ? pRegister->setVal${regType}Array2D(data.${fesaFieldName}.get(fesaDim1, fesaDim2), dim1, dim2) :
pRegister->setVal${regType}Array2D(pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2, pContext), dim1, dim2);
}
"""
${contents}""")
cArray2DSetContents = string.Template("""uint32_t fesaDim1,fesaDim2;
${contents}""")
cArray2DSetData = string.Template("""const ${fesaType}* ${regName};
(data.is${fesaFieldName_upper}Available()) ? ${regName} = data.${fesaFieldName}.get(fesaDim1, fesaDim2) :
${regName} = pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2${context});
std::vector<${regType}> data(${regName}, ${regName} + dim1 * dim2);
pRegister->setValArray2D<${regType}>(data.data(), dim1, dim2);""")
cArray2DSetDataSigned = string.Template("""(data.is${fesaFieldName_upper}Available()) ? pRegister->setValArray2D<${regType}>(data.${fesaFieldName}.get(fesaDim1, fesaDim2), dim1, dim2) :
pRegister->setValArray2D<${regType}>(pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2${context}), dim1, dim2);""")
cArray2DSetSigned = string.Template("""pRegister->setValArray2D<${regType}>(pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2${context}), dim1, dim2);""")
cArray2DSet = string.Template("""const ${fesaType}* ${regName} = pDevice->${fesaFieldName}.get(fesaDim1, fesaDim2${context});
std::vector<${regType}> data(${regName}, ${regName} + dim1 * dim2);
pRegister->setValArray2D<${regType}>(data.data(), dim1, dim2);""")
cArray2DGetSigned = string.Template("""pDevice->${fesaFieldName}.set(pRegister->getRefArray2D<${regType}>(dim1, dim2), dim1, dim2, pContext);""")
cArray2DGet = string.Template("""data.set${fesaFieldName_upper}(pRegister->getRefArray2D<${regType}>(dim1, dim2), dim1, dim2);""")
cArray2DGetCustom = string.Template("""${regType}* arrData = pRegister->getRefArray2D<${regType}>(dim1, dim2);
std::vector<${enumName}::${enumName}> ${regName};
for(uint32_t i = 0; i < dim1 * dim2; ++i)
{
${regName}.push_back(static_cast<${enumName}::${enumName}>(*(arrData + i)));
}
${contents}""")
cArray2DGetUnsigned = string.Template("""${regType}* arrData = pRegister->getRefArray2D<${regType}>(dim1, dim2);
std::vector<${fesaType}> ${regName}(arrData, arrData + dim1 * dim2);
${contents}""")
makeDesign = """# Include SILECS library path
SILECS_PATH ?= ${centralMakefilePath}
cArray2DGetReg = string.Template("""pDevice->${fesaFieldName}.set(${regName}.data(), dim1, dim2, pContext);""")
cArray2DGetData = string.Template("""data.set${fesaFieldName_upper}(${regName}.data(), dim1, dim2);""")
makeDesign = """# Include SILECS makefile
include Makefile.silecs
# Additional compiler warning flags
override WARNFLAGS +=
# Additional compiler flags
COMPILER_FLAGS += -I$(SILECS_PATH)/include -I$(SILECS_PATH)/include/silecs-communication/interface/core
COMPILER_FLAGS +=
LINKER_FLAGS +=
# Additional headers (Custom.h Specific.h ...) which need to be installed
EXTRA_HEADERS +=
"""
makeDeploy = """# Include SILECS library path
SILECS_PATH ?= ${silecsBasePath}
SNAP7_BASE = ${snap7BasePath}
makeDeploy = """# Include SILECS makefile
include Makefile.silecs
# Additional compiler warning flags
override WARNFLAGS +=
# Additional libs and flags which are common to the Realtime and Server part
COMPILER_FLAGS +=
LINKER_FLAGS += -L$(SILECS_PATH)/lib/$(CPU) -lsilecs-comm
LINKER_FLAGS += -L$(SNAP7_BASE)/bin/$(CPU)-linux -lsnap7
#add default search path for dynamic snap7 library
LINKER_FLAGS += -Wl,-rpath,$(SNAP7_BASE)/bin/$(CPU)-linux,-rpath,/usr/lib
LINKER_FLAGS +=
# Additional libs and flags which are specific to the Realtime part
......@@ -695,7 +688,7 @@ LINKER_SERVER_FLAGS +=
# Additional headers (Custom.h Specific.h ...) which need to be released
EXTRA_HEADERS +=
"""
#=========================================================================
# FESA .cproject file
#=========================================================================
......@@ -705,134 +698,253 @@ def genCProject():
#=========================================================================
# Header file (.h) code generation sub-functions
#================ =========================================================
#================ =========================================================
def genHTop(className):
return htop.replace('${className}', className )
def genHTopBlock(className, blockName):
return hTopBlock.replace('${className}', className).replace('${blockName}', blockName)
def genHTop(className):
return htop.substitute(className=className)
def genHTop2(className):
return hTop2.replace('${className}', className)
return hTop2.substitute(className=className)
def genHBlock(mode, blockName, propName):
return hBlock.replace('${mode}', mode).replace('${blockName}', blockName).replace('${propName}', propName)
def genHReadBlock(classname, blockName):
return hReadBlock.substitute(className=classname, blockName=blockName)
def genHWriteBlock(classname, blockName, propName):
return hWriteBlock.substitute(className=classname, blockName=blockName, propName=propName)
def genHReadWriteBlock(classname, blockName, propName):
return hReadWriteBlock.substitute(className=classname, blockName=blockName, propName=propName)
def genHBottom(className):
return hBottom.replace('${className}', className)
return hBottom.substitute(className=className)
def genHDeclBlocks(className):
return hDeclBlocks.replace('${className}', className)
return hDeclBlocks.substitute(className=className)
def genHClosing(className):
return hClosing.replace('${className}', className)
return hClosing.substitute(className=className)
#=========================================================================
# C++ file (.cpp) code generation sub-functions
#=========================================================================
def genCTop(className):
return cTop.replace('${className}', className)
return cTop.substitute(className=className)
def genCGlobal(className, blockName):
return cGlobal.replace('${className}', className).replace('${blockName}', blockName)
return cGlobal.substitute(className=className,blockName=blockName)
def genCPart1(className):
return cPart1.replace('${className}', className)
return cPart1.substitute(className=className)
def genCBlockConstr(blockName, className):
return cBlockConstr.replace('${className}', className).replace('${blockName}', blockName)
return cBlockConstr.substitute(className=className, blockName=blockName)
def genCPart2(className):
return cPart2.replace('${className}', className)
def genCSetPLC(className, blockName):
return cSetPLC.replace('${className}', className).replace('${blockName}', blockName)
def genCCommonGet(blockName,className):
return cCommonGet.replace('${className}', className).replace('${blockName}', blockName)
def genCPart3(className):
return cPart3.replace('${className}', className)
def genCGetPLC(className, blockName):
return cGetPLC.replace('${className}', className).replace('${blockName}', blockName)
return cPart2.substitute(className=className)
def genCCommonGet(blockName, className):
return cCommonGet.substitute(blockName=blockName, className=className)
def genCDatatypeGet(blockName, propName, className):
return cDatatypeGet.substitute(blockName=blockName, propName=propName, className=className)
def updatePLCRegisters(className, blockList):
code = updatePLCRegisters_start.substitute(className=className)
for block in blockList:
if block.isConfiguration(): # only config Blocks are updated on PLC during startup !
code += updatePLCRegisters_body.substitute(className=className, blockName=block.name)
code += updatePLCRegisters_end
return code
def updateFesaFields(className, blockList):
code = updateFesaFields_start.substitute(className=className)
for block in blockList:
if block.isReadable() and not block.isConfiguration():
code += updateFesaFields_body.substitute(className=className, blockName=block.name)
code += updateFesaFields_end
return code
def genCPart4(className):
return cPart4.replace('${className}', className)
return cPart4.substitute(className=className)
def genCGetStringReg(register):
return cGetStringReg.replace('${regName}', register.name).replace('${fesaFieldName}', register.getFesaFieldName())
return cGetStringReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName())
def genCGetStringRegData(register):
return cGetStringRegData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized())
def genCGetStringArrayReg(register):
return cGetStringArrayReg.replace('${regName}', register.name).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetStringReg.substitute(fesaFieldName=register.getFesaFieldName())))
def genCGetStringArrayRegData(register):
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetStringData.substitute(fesaFieldName_upper=register.getFesaFieldNameCapitalized())))
def genCGetScalarReg(register):
return cGetScalarReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGetScalarReg.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName())
def genCGetScalarRegData(register):
return cGetScalarRegData.substitute(regName=register.name, regType=register.getCType(), fesaFieldName_upper=register.getFesaFieldNameCapitalized())
def genCGetCustomScalarReg(register):
return cGetCustomScalarReg.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), enumName=register.custom_type_name)
def genCGetCustomScalarRegData(register):
return cGetCustomScalarRegData.substitute(regName=register.name, regType=register.getCType(), fesaFieldName_upper=register.getFesaFieldNameCapitalized(), enumName=register.custom_type_name)
def genCGetCustomArrayReg(register):
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetCustom.substitute(regName=register.name, regType=register.getCType(), enumName=register.custom_type_name, contents=cArrayGetReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName()))))
def genCGetCustomArrayRegData(register):
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetCustom.substitute(regName=register.name, regType=register.getCType(), enumName=register.custom_type_name, contents=cArrayGetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized()))))
def genCGetCustomArray2DReg(register):
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGetCustom.substitute(regName=register.name, regType=register.getCType(), enumName=register.custom_type_name, contents=cArray2DGetReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName()))))
def genCGetCustomArray2DRegData(register):
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGetCustom.substitute(regName=register.name, regType=register.getCType(), enumName=register.custom_type_name, contents=cArray2DGetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized()))))
def genCGetArrayReg(register):
if register.isUnsigned():
return cGetUnsignedArrayReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName()).replace('${fesaType}', register.getFesaType())
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetUnsigned.substitute(regName=register.name, regType=register.getCType(), fesaType=register.getFesaType(), contents=cArrayGetReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName()))))
else:
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetSigned.substitute(regType=register.getCType(), fesaFieldName=register.getFesaFieldName())))
def genCGetArrayRegData(register):
if register.isUnsigned():
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGetUnsigned.substitute(regName=register.name, regType=register.getCType(), fesaType=register.getFesaType(), contents=cArrayGetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized()))))
else:
return cGetArrayReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArrayGet.substitute(regType=register.getCType(), fesaFieldName_upper=register.getFesaFieldNameCapitalized())))
def genCGetArray2DReg(register):
if register.isUnsigned():
return cGetUnsignedArray2DReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaType}', register.getFesaType()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGetUnsigned.substitute(regName=register.name, regType=register.getCType(), fesaType=register.getFesaType(), contents=cArray2DGetReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName()))))
else:
return cGetArray2DReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGetSigned.substitute(regType=register.getCType(), fesaFieldName=register.getFesaFieldName())))
def genCCommonSet(blockName,className):
return cCommonSet.replace('${className}', className).replace('${blockName}', blockName)
def genCGetArray2DRegData(register):
if register.isUnsigned():
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGetUnsigned.substitute(regName=register.name, regType=register.getCType(), fesaType=register.getFesaType(), contents=cArray2DGetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized()))))
else:
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DGet.substitute(regType=register.getCType(), fesaFieldName_upper=register.getFesaFieldNameCapitalized())))
def genCCommonSet(blockName, className):
return cCommonSet.substitute(blockName=blockName, className=className)
def genCDatatypeSet(blockName,propName,className):
return cDatatypeSet.replace('${className}', className).replace('${blockName}', blockName).replace('${propName}', propName)
def genCDatatypeSet(blockName,propName, className):
return cDatatypeSet.substitute(blockName=blockName, propName=propName, className=className)
def genCSetStringReg(register):
return cSetStringReg.replace('${regName}', register.name).replace('${fesaFieldName}', register.getFesaFieldName())
context = "pContext"
if register.isConfiguration():
context = ""
return cSetStringReg.substitute(regName=register.name, fesaFieldName=register.getFesaFieldName(), context=context)
def genCSetStringArrayReg(register):
return cSetStringArrayReg.replace('${regName}', register.name).replace('${fesaFieldName}', register.getFesaFieldName())
context = ", pContext"
if register.isConfiguration():
context = ""
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetString.substitute(fesaFieldName=register.getFesaFieldName(), context=context))))
def genCSetScalarReg(register):
cCast = ""
context = "pContext"
if register.isUnsigned():
return cSetScalarUReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${cType}', register.getCType()).replace('${fesaFieldName}', register.getFesaFieldName())
else:
return cSetScalarReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
cCast = "(" + register.getCType() + ")"
if register.isConfiguration():
context = ""
return cSetScalarReg.substitute(regName=register.name, regType=register.getCType(), cCast=cCast, fesaFieldName=register.getFesaFieldName(), context=context)
def genCSetArrayReg(register):
context = ", pContext"
if register.isConfiguration():
context = ""
if register.isUnsigned():
return cSetUnsignedArrayReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySet.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=register.getFesaType()))))
else:
return cSetArrayReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetSigned.substitute(regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context))))
def genCSetArray2DReg(register):
context = ", pContext"
if register.isConfiguration():
context = ""
if register.isUnsigned():
return cSetUnsignedArray2DReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
setContent = cArray2DSet.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=register.getFesaType())
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DSetContents.substitute(contents=setContent)))
else:
return cSetArray2DReg.replace('${regName}', register.name).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
setContent = cArray2DSetSigned.substitute(regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context)
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DSetContents.substitute(contents=setContent)))
def genCSetCustomArrayReg(register):
context = ", pContext"
if register.isConfiguration():
context = ""
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySet.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=f"{register.custom_type_name}::{register.custom_type_name}"))))
def genCSetCustomArray2DReg(register):
context = ", pContext"
if register.isConfiguration():
context = ""
setContent = cArray2DSet.substitute(regName=register.name, regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=f"{register.custom_type_name}::{register.custom_type_name}")
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DSetContents.substitute(contents=setContent)))
def genCSetStringRegData(register):
return cSetStringRegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
context = "pContext"
if register.isConfiguration():
context = ""
return cSetStringRegData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), fesaFieldName=register.getFesaFieldName(), context=context)
def genCSetStringArrayRegData(register):
return cSetStringArrayRegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
context = ", pContext"
if register.isConfiguration():
context = ""
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetDataString.substitute(fesaFieldName_upper=register.getFesaFieldNameCapitalized(), fesaFieldName=register.getFesaFieldName(), context=context))))
def genCSetScalarRegData(register):
cCast = ""
context = "pContext"
if register.isUnsigned():
return cSetScalarURegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName()).replace('${cType}', register.getCType())
else:
return cSetScalarRegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
cCast = "(" + register.getCType() + ")"
if register.isConfiguration():
context = ""
return cSetScalarRegData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), cCast=cCast, context=context)
def genCSetArrayRegData(register):
return cSetArrayRegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
context = ", pContext"
if register.isConfiguration():
context = ""
if register.isUnsigned():
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaType=register.getFesaType(), fesaFieldName=register.getFesaFieldName(), context=context))))
else:
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetDataSigned.substitute(fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context))))
def genCSetCustomArrayRegData(register):
context = ", pContext"
if register.isConfiguration():
context = ""
return cGeneral.substitute(regName=register.name, contents=cArray.substitute(contents=cArraySetContents.substitute(contents=cArraySetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaType=f"{register.custom_type_name}::{register.custom_type_name}", fesaFieldName=register.getFesaFieldName(), context=context))))
def genCSetArray2DRegData(register):
return cSetArray2DRegData.replace('${regName}', register.name).replace('${fesaFieldName_upper}', register.getFesaFieldNameCapitalized()).replace('${regType}', register.getSilecsTypeCapitalized()).replace('${fesaFieldName}', register.getFesaFieldName())
context = ", pContext"
if register.isConfiguration():
context = ""
if register.isUnsigned():
setDataContent = cArray2DSetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=register.getFesaType())
else:
setDataContent = cArray2DSetDataSigned.substitute(fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context)
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DSetContents.substitute(contents=setDataContent)))
def genCSetCustomArray2DRegData(register):
context = ", pContext"
if register.isConfiguration():
context = ""
setDataContent = cArray2DSetData.substitute(regName=register.name, fesaFieldName_upper=register.getFesaFieldNameCapitalized(), regType=register.getCType(), fesaFieldName=register.getFesaFieldName(), context=context, fesaType=f"{register.custom_type_name}::{register.custom_type_name}")
return cGeneral.substitute(regName=register.name, contents=cArray2D.substitute(contents=cArray2DSetContents.substitute(contents=setDataContent)))
def genMakeDesign(centralMakefilePath):
return makeDesign.replace('${centralMakefilePath}', centralMakefilePath)
def genMakeDesign():
return makeDesign
def genMakeDeploy(silecsBasePath,snap7BasePath):
return makeDeploy.replace('${silecsBasePath}', silecsBasePath).replace('${snap7BasePath}', snap7BasePath)
def genMakeDeploy():
return makeDeploy
......@@ -33,9 +33,9 @@ from iecommon import *
# Generates two Makefile.specific, one for the class design
# and another for the deploy unit
#-------------------------------------------------------------------------
def genMakefileClass(projectPath, centralMakefilePath, logTopics={'errorlog': True} ):
def genMakefileClass(projectPath, logTopics={'errorlog': True} ):
# Generate makefile for class design
source = fesaTemplates.genMakeDesign(centralMakefilePath)
source = fesaTemplates.genMakeDesign()
makefile = projectPath + "/" + "Makefile.specific"
if os.path.isfile(makefile): #dont overwrite
return
......@@ -44,9 +44,9 @@ def genMakefileClass(projectPath, centralMakefilePath, logTopics={'errorlog': Tr
fdesc.write(source)
fdesc.close()
def genMakefileDU(projectPath, silecsBasePath, snap7BasePath, logTopics={'errorlog': True}):
def genMakefileDU(projectPath, logTopics={'errorlog': True}):
# Generate makefile for class design
source = fesaTemplates.genMakeDeploy(silecsBasePath,snap7BasePath)
source = fesaTemplates.genMakeDeploy()
# Write file and save
makefile = projectPath + "/" + "Makefile.specific"
if os.path.isfile(makefile): #dont overwrite
......
......@@ -26,7 +26,7 @@ import datetime
import socket
import iecommon
import fesaTemplates
import fesa.fesa_3_0_0.fesaTemplates
import iefiles
from iecommon import *
......@@ -87,8 +87,29 @@ class FESADesignGenerator3_0_0(object):
fillAttributes(scalarNode, {'type': register.getFesaType()})
return scalarNode
def getOrCreateType(self,fieldNode,register):
if register.valueType == "scalar":
def getOrCreateCustomScalarType(self, fieldNode, register):
scalarNode = getOrCreateChildElement(fieldNode,'custom-type-scalar')
fillAttributes(scalarNode, {'data-type-name-ref': register.custom_type_name})
return scalarNode
def getOrCreateCustomArrayType(self,fieldNode,register):
arrayNode = getOrCreateChildElement(fieldNode,'custom-type-array')
fillAttributes(arrayNode, {'data-type-name-ref': register.custom_type_name})
dimNode = getOrCreateChildElement(arrayNode,'dim')
dimNode.setContent(str(register.dim1))
return arrayNode
def getOrCreateCustom2DArrayType(self,fieldNode,register):
array2DNode = getOrCreateChildElement(fieldNode,'custom-type-array2D')
fillAttributes(array2DNode, {'data-type-name-ref': register.custom_type_name})
dim1Node = getOrCreateChildElement(array2DNode,'dim1')
dim2Node = getOrCreateChildElement(array2DNode,'dim2')
dim1Node.setContent(str(register.dim1))
dim2Node.setContent(str(register.dim2))
return array2DNode
def getOrCreateType(self,fieldNode, register):
if register.valueType == "scalar":
return self.getOrCreateScalarType(fieldNode,register)
elif register.valueType == "array":
return self.getOrCreateArrayType(fieldNode,register)
......@@ -100,6 +121,12 @@ class FESADesignGenerator3_0_0(object):
return self.getOrCreateStringArrayType(fieldNode,register)
elif register.valueType == "stringArray2D":
iecommon.logError('ERROR: In register '+register.name+' - 2D array of strings not supported in FESA.', True, {'errorlog': True})
elif register.valueType == "custom-type-scalar":
return self.getOrCreateCustomScalarType(fieldNode, register)
elif register.valueType == "custom-type-array":
return self.getOrCreateCustomArrayType(fieldNode, register)
elif register.valueType == "custom-type-array2D":
return self.getOrCreateCustom2DArrayType(fieldNode, register)
else:
iecommon.logError('ERROR: Unknown data-type:' + register.valueType, True, {'errorlog': True})
return None
......@@ -197,6 +224,10 @@ class FESADesignGenerator3_0_0(object):
else:
return getOrCreateNamedChildElement(parent,'field',register.getFesaFieldName())
def addDefaultNode(self, fieldNode, defaultValue):
defaultNode = getOrCreateChildElement(fieldNode,'default')
defaultNode.setContent(defaultValue)
def getOrCreatePLCHostNameField(self,configurationNode):
fieldNode = getOrCreateNamedFirstChild(configurationNode,'field','plcHostName')
descriptionNode = getOrCreateChildElement(fieldNode,'description')
......@@ -224,15 +255,14 @@ class FESADesignGenerator3_0_0(object):
array = getOrCreateChildElement(fieldNode,'array')
fillAttributes(array, {'type': 'char'})
dim = getOrCreateChildElement(array,'dim')
defaultNode = getOrCreateChildElement(fieldNode,'default')
defaultNode.setContent(plcClassVersion)
dim.setContent(str(len(defaultNode.getContent())))
self.addDefaultNode(fieldNode, plcClassVersion)
dim.setContent(str(len(plcClassVersion)))
return fieldNode
def getOrCreateRegisterValueItems(self,prop,block,isSetting):
def getOrCreateRegisterValueItems(self,prop,block,direction):
for register in block.getDesignRegisters():
if register.generateFesaValueItem:
self.getOrCreateValueItem(prop,register,isSetting)
self.getOrCreateValueItem(prop,register,direction)
def getOrCreateSettingProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating SettingProperty for Block: ' + block.name, {'debuglog': True})
......@@ -242,12 +272,23 @@ class FESADesignGenerator3_0_0(object):
else:
prop = getOrCreateNamedChildElement(parent,'setting-property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'multiplexed': 'false'})
self.getOrCreateRegisterValueItems(prop,block,True)
self.getOrCreateRegisterValueItems(prop,block,"INOUT")
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
self.getOrCreateAction(prop,block.fesaSetServerActionName,'set',actionsNode,'custom')
self.getOrCreateAction(prop,block.fesaGetServerActionName,'get',actionsNode,'custom')
return prop
def getOrCreateCommandProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating CommandProperty for Block: ' + block.name, {'debuglog': True})
if( hasChildren(parent)):
prop = getOrCreateNamedPreviousSiblingElement(parent,getFirstChild(parent), 'command-property',block.getFesaName())
else:
prop = getOrCreateNamedChildElement(parent,'command-property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'multiplexed': 'false'})
self.getOrCreateRegisterValueItems(prop,block,"IN")
self.getOrCreateAction(prop,block.fesaSetServerActionName,'set',actionsNode,'custom')
return prop
def getOrCreateAcquisitionProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating AcquisitionProperty for Block: ' + block.name, {'debuglog': True})
......@@ -257,7 +298,7 @@ class FESADesignGenerator3_0_0(object):
else:
prop = getOrCreateNamedChildElement(parent,'acquisition-property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'subscribable': 'true', 'multiplexed': 'false', 'on-change': 'true'})
self.getOrCreateRegisterValueItems(prop,block,False)
self.getOrCreateRegisterValueItems(prop,block,"OUT")
self.getOrCreateAcqStampItem(prop)
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
......@@ -265,13 +306,15 @@ class FESADesignGenerator3_0_0(object):
self.getOrCreateAction(prop,block.fesaGetServerActionName,'get',actionsNode,'custom')
return prop
def getOrCreateGSISettingProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating GSISettingProperty for Block: ' + block.name, {'debuglog': True})
powerProp = parent.xpathEval('GSI-Power-Property')[0] # template is used --> there has to be a power prop
powerProps = parent.xpathEval('GSI-Power-Property')
if len(powerProps) == 0:
raise Exception("Error: A GSI-Power-Property needs to be available to generate a GSISettingProperty")
powerProp = powerProps[0] # template is used --> there has to be a power prop
prop = getOrCreateNamedPreviousSiblingElement(parent,powerProp, 'GSI-Setting-Property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'multiplexed': 'false'})
self.getOrCreateRegisterValueItems(prop,block,True)
self.getOrCreateRegisterValueItems(prop,block,"INOUT")
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
self.getOrCreateAction(prop,block.fesaSetServerActionName,'set',actionsNode,'custom')
......@@ -280,10 +323,12 @@ class FESADesignGenerator3_0_0(object):
def getOrCreateGSIAcquisitionProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating GSIAcquisitionProperty for Block: ' + block.name, {'debuglog': True})
versionProp = parent.xpathEval('GSI-Version-Property')[0] # template is used --> there has to be a version prop
prop = getOrCreateNamedPreviousSiblingElement(parent,versionProp, 'GSI-Acquisition-Property',block.getFesaName())
versionProps = parent.xpathEval('GSI-Version-Property')
if len(versionProps) == 0:
raise Exception("Error: A GSI-Version-Property needs to be available to generate a GSIAcquisitionProperty")
prop = getOrCreateNamedPreviousSiblingElement(parent,versionProps[0], 'GSI-Acquisition-Property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'subscribable': 'true', 'multiplexed': 'false', 'on-change': 'true'})
self.getOrCreateRegisterValueItems(prop,block,False)
self.getOrCreateRegisterValueItems(prop,block,"OUT")
self.getOrCreateAcqStampItem(prop)
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
......@@ -295,17 +340,44 @@ class FESADesignGenerator3_0_0(object):
# propertyType only used during creation ! If named property already exists, it is just returned, no matter which type
def getOrCreateFESAProperty(self,parent,actionsNode,block):
if self.isGSITemplate(parent):
if parent.get_name() == 'setting':
return self.getOrCreateGSISettingProperty(parent,actionsNode,block)
if block.isSetting():
if block.getFesaName() == 'Power':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-Power-Property and connect silecs-fields manually")
else:
return self.getOrCreateGSISettingProperty(parent,actionsNode,block)
elif block.isCommand():
if block.getFesaName() == 'Init':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-Init-Property and connect silecs-fields manually")
elif block.getFesaName() == 'Reset':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-Reset-Property and connect silecs-fields manually")
else:
return self.getOrCreateCommandProperty(parent,actionsNode,block)
elif block.isAcquisition():
if block.getFesaName() == 'Status':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-Status-Property and connect silecs-fields manually")
elif block.getFesaName() == 'ModuleStatus':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-ModuleStatus-Property and connect silecs-fields manually")
elif block.getFesaName() == 'Version':
raise Exception("Error: Please use '@generateFesaProperty=false' for the GSI-Version-Property and connect silecs-fields manually")
else:
return self.getOrCreateGSIAcquisitionProperty(parent,actionsNode,block)
elif block.isConfiguration():
return self.getOrCreateGSIAcquisitionProperty(parent,actionsNode,block);
else:
return self.getOrCreateGSIAcquisitionProperty(parent,actionsNode,block)
raise Exception( "Cannot identify FESA GSI Property-type to use for block:" + block.name )
else:
if parent.get_name() == 'setting':
if block.isSetting():
return self.getOrCreateSettingProperty(parent,actionsNode,block)
else:
elif block.isCommand():
return self.getOrCreateCommandProperty(parent,actionsNode,block)
elif block.isAcquisition():
return self.getOrCreateAcquisitionProperty(parent,actionsNode,block)
elif block.isConfiguration():
return self.getOrCreateAcquisitionProperty(parent,actionsNode,block);
else:
raise Exception( "Cannot identify FESA Property-type to use for block:" + block.name )
def getOrCreateValueItem(self,propertyNode,register,isSetting):
def getOrCreateValueItem(self,propertyNode,register,direction):
iecommon.logDebug('Generating ValueItem for Register: ' + register.name, {'debuglog': True})
result = propertyNode.xpathEval("value-item[@name='" + register.getFesaFieldName() + "']")
if len(result):
......@@ -315,10 +387,7 @@ class FESADesignGenerator3_0_0(object):
valueItemNode = getOrCreateNamedPreviousSiblingElement(propertyNode,result[0],'value-item',register.getFesaFieldName())
else:
valueItemNode = getOrCreateNamedChildElement(propertyNode,'value-item',register.getFesaFieldName())
if isSetting:
fillAttributes(valueItemNode, {'direction': 'INOUT'})
else:
fillAttributes(valueItemNode, {'direction': 'OUT'})
fillAttributes(valueItemNode, {'direction': direction})
self.getOrCreateType(valueItemNode,register)
self.getOrCreateFieldRef(valueItemNode,register.getFesaFieldName())
......@@ -346,9 +415,10 @@ class FESADesignGenerator3_0_0(object):
elif reg.isAcquisition():
fieldNode = self.getOrCreateFieldNode(acquisitionNode,reg)
fillAttributes(fieldNode, {'multiplexed': 'false', 'persistent': 'false'})
else: #volatile#
fieldNode = self.getOrCreateFieldNode(settingNode,reg)
fillAttributes(fieldNode, {'multiplexed': 'false', 'persistent': 'false'})
elif reg.isConfiguration():
fieldNode = self.getOrCreateFieldNode(configurationNode,reg)
else:
raise Exception( "Cannot identify register-type to use for register:" + reg.name )
self.getOrCreateType(fieldNode,reg)
globalDataNode = getOrCreateChildElement(dataNode,'global-data')
......@@ -377,32 +447,11 @@ class FESADesignGenerator3_0_0(object):
for block in designClass.getDesignBlocks():
if not block.generateFesaProperty:
continue #skip this block
if block.isWritable():
if block.isSetting() or block.isCommand():
propertyNode = self.getOrCreateFESAProperty(settingNode, actionsNode, block)
else:
propertyNode = self.getOrCreateFESAProperty(acquisitionNode,actionsNode,block)
#-------------------------------------------------------------------------
# Generates the scheduling-units node of the FESA design
# document parsing the SILECS class document
#-------------------------------------------------------------------------
def addDesignFileId(self,fesaDesignFile,logTopics):
nodeRequiringId = ['setting-property','acquisition-property','diagnostic-property',
'value-item','update-flag-item','cycle-name-item', 'acq-stamp-item',
'cycle-stamp-item','mode-item','host-item','port-item','config-item',
'state-item','fwk-topic-item','custom-topic-item','device-trace-item',
'bypass-action-item','diag-custom-topic','field','timing-event-source',
'timer-event-source','logical-event']
counter = 0
now = datetime.datetime.today()
id = '_' + now.strftime('%y%m%d%H%M%S') + '_%s'
for nodeName in nodeRequiringId:
for node in fesaDesignFile.xpathEval("//" + nodeName):
if node.hasProp("id"):
node.setProp("id", id%counter)
counter = counter +1
def fillXML(self,fesaVersion, className, fesaRoot, silecsRoot,logTopics={'errorlog': True}):
......@@ -428,7 +477,6 @@ class FESADesignGenerator3_0_0(object):
# Generate properties, Actions, Events, Scheduling Units
self.genDeviceInterface(designClass, fesaRoot,logTopics)
self.addDesignFileId(fesaRoot,logTopics)
return fesaRoot
#-------------------------------------------------------------------------
......
......@@ -24,7 +24,7 @@ import datetime
import socket
import iecommon
import fesaTemplates
import fesa.fesa_3_0_0.fesaTemplates as fesaTemplates
import iefiles
from iecommon import *
......@@ -47,25 +47,19 @@ def findBlockServerSetActionName(fesaRoot, propName):
def genHSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
designClass = DesignClass.getDesignClassFromRootNode(silecsRoot)
source = fesaTemplates.genHTop(className)
for block in designClass.getDesignBlocks():
if block.isWritable():
serverActionName = findBlockServerSetActionName(fesaRoot,block.getFesaName())
source += fesaTemplates.genHTopBlock(className, serverActionName)
source += fesaTemplates.genHTop2(className)
for block in designClass.getDesignBlocks():
for block in designClass.getDesignFesaBlocks():
if block.isAcquisition():
source += fesaTemplates.genHBlock('RO', block.name,block.getFesaName() )
elif block.isCommand():
source += fesaTemplates.genHBlock('WO', block.name,block.getFesaName())
source += fesaTemplates.genHReadBlock(className, block.name)
elif block.isCommand() or block.isConfiguration():
source += fesaTemplates.genHWriteBlock(className, block.name, block.getFesaName())
else: # Setting
source += fesaTemplates.genHBlock('RW', block.name,block.getFesaName())
source += fesaTemplates.genHReadWriteBlock(className, block.name, block.getFesaName())
source += fesaTemplates.genHBottom(className)
for block in designClass.getDesignBlocks():
for block in designClass.getDesignFesaBlocks():
source += fesaTemplates.genHDeclBlocks(block.name)
source += fesaTemplates.genHClosing(className)
......@@ -93,7 +87,8 @@ def genHSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
designClass = DesignClass.getDesignClassFromRootNode(silecsRoot)
finalSource = fesaTemplates.genCTop(className)
blockList = designClass.getDesignBlocks()
blockList = designClass.getDesignFesaBlocks()
for block in blockList:
finalSource += fesaTemplates.genCGlobal(className, block.name)
......@@ -103,24 +98,15 @@ def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
finalSource += fesaTemplates.genCBlockConstr(block.name, className)
finalSource += fesaTemplates.genCPart2(className)
for block in blockList:
if (block.isWritable()):
# WARNING: In order to have multiplexed FESA fields, the corresponding SILECS registers' synchro mode must be 'NONE'
finalSource += fesaTemplates.genCSetPLC(className, block.name)
finalSource += fesaTemplates.genCPart3(className)
for block in blockList:
if (block.isReadable()):
# WARNING: In order to have multiplexed FESA fields, the corresponding SILECS registers' synchro mode must be 'NONE'
finalSource += fesaTemplates.genCGetPLC(className, block.name)
finalSource += fesaTemplates.updatePLCRegisters(className, blockList)
finalSource += fesaTemplates.updateFesaFields(className, blockList)
finalSource += fesaTemplates.genCPart4(className)
for block in blockList:
if block.isReadable():
finalSource += fesaTemplates.genCCommonGet(block.name,className)
if block.isSetting() or block.isAcquisition(): #configuration-fields in fesa are not writable, so no setter to generate for them !
finalSource += fesaTemplates.genCCommonGet(block.name, className)
finalSource += '\n'
finalSource += fesaTemplates.cRecv
for register in block.getDesignRegisters():
......@@ -136,10 +122,43 @@ def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
finalSource += fesaTemplates.genCGetArrayReg(register)
elif register.valueType == 'array2D':
finalSource += fesaTemplates.genCGetArray2DReg(register)
elif register.valueType == 'custom-type-scalar':
finalSource += fesaTemplates.genCGetCustomScalarReg(register)
elif register.valueType == 'custom-type-array':
finalSource += fesaTemplates.genCGetCustomArrayReg(register)
elif register.valueType == 'custom-type-array2D':
finalSource += fesaTemplates.genCGetCustomArray2DReg(register)
finalSource += '\n }\n'
if block.isSetting():
finalSource += fesaTemplates.genCDatatypeGet(block.name, block.getFesaName(), className)
finalSource += '\n'
finalSource += fesaTemplates.cRecv
for register in block.getDesignRegisters():
if register.valueType == 'string':
finalSource += fesaTemplates.genCGetStringRegData(register)
elif register.valueType == 'stringArray':
finalSource += fesaTemplates.genCGetStringArrayRegData(register)
elif register.valueType == 'stringArray2D':
iecommon.logError('ERROR: In register '+register.name+' - 2D array of strings not supported in FESA.', True, {'errorlog': True})
elif register.valueType == 'scalar':
finalSource += fesaTemplates.genCGetScalarRegData(register)
elif register.valueType == 'array':
finalSource += fesaTemplates.genCGetArrayRegData(register)
elif register.valueType == 'array2D':
finalSource += fesaTemplates.genCGetArray2DRegData(register)
elif register.valueType == 'custom-type-scalar':
finalSource += fesaTemplates.genCGetCustomScalarRegData(register)
elif register.valueType == 'custom-type-array':
finalSource += fesaTemplates.genCGetCustomArrayRegData(register)
elif register.valueType == 'custom-type-array2D':
finalSource += fesaTemplates.genCGetCustomArray2DRegData(register)
finalSource += '\n }\n'
if block.isWritable():
finalSource += fesaTemplates.genCCommonSet(block.name,className)
finalSource += fesaTemplates.genCCommonSet(block.name, className)
for register in block.getDesignRegisters():
if register.valueType == 'string':
finalSource += fesaTemplates.genCSetStringReg(register)
......@@ -153,6 +172,12 @@ def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
finalSource += fesaTemplates.genCSetArrayReg(register)
elif register.valueType == 'array2D':
finalSource += fesaTemplates.genCSetArray2DReg(register)
elif register.valueType == 'custom-type-scalar':
finalSource += fesaTemplates.genCSetScalarReg(register)
elif register.valueType == 'custom-type-array':
finalSource += fesaTemplates.genCSetCustomArrayReg(register)
elif register.valueType == 'custom-type-array2D':
finalSource += fesaTemplates.genCSetCustomArray2DReg(register)
finalSource += fesaTemplates.cSend
finalSource += ' }\n'
finalSource += fesaTemplates.genCDatatypeSet(block.name,block.getFesaName(), className)
......@@ -170,6 +195,12 @@ def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
finalSource += fesaTemplates.genCSetArrayRegData(register)
elif register.valueType == 'scalar':
finalSource += fesaTemplates.genCSetScalarRegData(register)
elif register.valueType == 'custom-type-scalar':
finalSource += fesaTemplates.genCSetScalarRegData(register)
elif register.valueType == 'custom-type-array':
finalSource += fesaTemplates.genCSetCustomArrayRegData(register)
elif register.valueType == 'custom-type-array2D':
finalSource += fesaTemplates.genCSetCustomArray2DRegData(register)
finalSource += fesaTemplates.cSend
finalSource += '\n }\n' # closing bracket for block
......
......@@ -16,11 +16,11 @@
import fesa.fesa_3_0_0.generateBuildEnvironment
def genMakefileClass(projectPath, centralMakefilePath, logTopics={'errorlog': True} ):
return fesa.fesa_3_0_0.generateBuildEnvironment.genMakefileClass(projectPath, centralMakefilePath, logTopics )
def genMakefileClass(projectPath, logTopics={'errorlog': True} ):
return fesa.fesa_3_0_0.generateBuildEnvironment.genMakefileClass(projectPath, logTopics )
def genMakefileDU(projectPath, silecsBasePath, snap7BasePath, logTopics={'errorlog': True}):
return fesa.fesa_3_0_0.generateBuildEnvironment.genMakefileDU(projectPath, silecsBasePath, snap7BasePath, logTopics )
def genMakefileDU(projectPath, logTopics={'errorlog': True}):
return fesa.fesa_3_0_0.generateBuildEnvironment.genMakefileDU(projectPath, logTopics )
def genCProjectFile(projectPath, logTopics={'errorlog': True}):
return fesa.fesa_3_0_0.generateBuildEnvironment.genCProjectFile(projectPath, logTopics )
#!/usr/bin/python
# Copyright 2016 CERN and GSI
#
# This program is free software: you can redistribute it and/or modify
......@@ -13,19 +14,10 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
PROJECT = silecs
PRODUCT = cli-client
VERSION = 0.0.0
import fesa.fillFesaDeployUnitBase
import fesa.fesa_3_0_0.fillFESADeployUnit
SKIP_MANIFEST = TRUE
#local
#COMMON_MAKE_PATH ?= /common/home/bel/schwinn/lnx/workspace-silecs-neon/generic-makefiles
#global
COMMON_MAKE_PATH ?= /opt/cern/buildsystem/generic/2.9.0
def fillDeployUnit(fesaVersion, className, workspacePath,fesaDesignXSDPath,logTopics={'errorlog': True}):
generator = fesa.fesa_3_0_0.fillFESADeployUnit.FESADeployUnitGenerator3_0_0() # identical with FESA 3.0.0
fesa.fillFesaDeployUnitBase.fillFesaDeployUnitBase(generator,fesaVersion, className, workspacePath,fesaDesignXSDPath,logTopics)
# product configuration
BIN_NAME = $(PROJECT)-$(PRODUCT)
DBG = false
# Include the generic make file
include $(COMMON_MAKE_PATH)/Make.generic
\ No newline at end of file
#!/usr/bin/python
# Copyright 2016 CERN and GSI
#
# This program is free software: you can redistribute it and/or modify
......@@ -13,28 +14,13 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
PROJECT = silecs
PRODUCT = communication
VERSION = 0.0.0
import fesa.fesa_3_1_0.generateBuildEnvironment
SKIP_MANIFEST = TRUE
#local
#COMMON_MAKE_PATH ?= /common/home/bel/schwinn/lnx/workspace-silecs-neon/generic-makefiles
#global
COMMON_MAKE_PATH ?= /opt/cern/buildsystem/generic/2.9.0
def genMakefileClass(projectPath, logTopics={'errorlog': True} ):
return fesa.fesa_3_1_0.generateBuildEnvironment.genMakefileClass(projectPath, logTopics )
# product configuration
LIB_NAME = comm
DBG = true
def genMakefileDU(projectPath, logTopics={'errorlog': True}):
return fesa.fesa_3_1_0.generateBuildEnvironment.genMakefileDU(projectPath, logTopics )
#COMPILER_FLAGS = -Os -fno-strict-aliasing -fexceptions -DLINUX -DARM_FIX -DDAVE_LITTLE_ENDIAN -D_GNU_SOURCE -DMAJOR=$(MAJOR) -DMINOR=$(MINOR) -DPATCH=$(PATCH)
COMPILER_FLAGS = -DMAJOR=$(MAJOR) -DMINOR=$(MINOR) -DPATCH=$(PATCH)
# Comment IN/Out to enable NI-Support
#COMPILER_FLAGS += -DNI_SUPPORT_ENABLED=TRUE
# Comment IN/Out to enable Modbus-Support
#COMPILER_FLAGS += -DMODBUS_SUPPORT_ENABLED=TRUE
# Include the generic make file
include $(COMMON_MAKE_PATH)/Make.generic
\ No newline at end of file
def genCProjectFile(projectPath, logTopics={'errorlog': True}):
return fesa.fesa_3_1_0.generateBuildEnvironment.genCProjectFile(projectPath, logTopics )
#!/usr/bin/python
# Copyright 2016 CERN and GSI
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import fesa.fillFesaDesignBase
import fesa.fesa_3_1_0.generateFesaDesign
from iecommon import *
def fillDesignFile(fesaVersion, className, workspacePath,fesaDesignXSDPath,logTopics={'errorlog': True}):
generator = FESADesignGenerator7_3_0()
fesa.fillFesaDesignBase.fillDesignFileBase(generator,fesaVersion, className, workspacePath,fesaDesignXSDPath,logTopics)
class FESADesignGenerator7_3_0(fesa.fesa_3_1_0.generateFesaDesign.FESADesignGenerator3_1_0):
#overwrite 3_0_0 version (multiplexed --> cycle-bound)
def getOrCreateAcquisitionProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating AcquisitionProperty for Block: ' + block.name, {'debuglog': True})
prop = ""
if( hasChildren(parent)):
prop = getOrCreateNamedPreviousSiblingElement(parent,getFirstChild(parent), 'acquisition-property',block.getFesaName())
else:
prop = getOrCreateNamedChildElement(parent,'acquisition-property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'subscribable': 'true', 'cycle-bound': 'false', 'on-change': 'true'})
self.getOrCreateRegisterValueItems(prop,block,"OUT")
self.getOrCreateAcqStampItem(prop)
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
self.getOrCreateCyleStampItem(prop)
self.getOrCreateAction(prop,block.fesaGetServerActionName,'get',actionsNode,'custom')
return prop
#overwrite 3_0_0 version (multiplexed --> cycle-bound)
def getOrCreateGSIAcquisitionProperty(self,parent,actionsNode,block):
iecommon.logDebug('Generating GSIAcquisitionProperty for Block: ' + block.name, {'debuglog': True})
versionProps = parent.xpathEval('GSI-Version-Property')
if len(versionProps) == 0:
raise Exception("Error: A GSI-Version-Property needs to be available to generate a GSIAcquisitionProperty")
prop = getOrCreateNamedPreviousSiblingElement(parent,versionProps[0], 'GSI-Acquisition-Property',block.getFesaName())
fillAttributes(prop, {'visibility': 'development', 'subscribable': 'true', 'cycle-bound': 'false', 'on-change': 'true'})
self.getOrCreateRegisterValueItems(prop,block,"OUT")
self.getOrCreateAcqStampItem(prop)
self.getOrCreateUpdateFlagItem(prop)
self.getOrCreateCyleNameItem(prop)
self.getOrCreateCyleStampItem(prop)
self.getOrCreateAction(prop,block.fesaGetServerActionName,'get',actionsNode,'custom')
self.getOrCreateAcquisitionContextItem(prop)
return prop
#overwrite 3_0_0 version (multiplexed --> cycle-bound for acquisition fileds)
def genData(self,designClass, doc,logTopics):
iecommon.logDebug("Creating data fields", logTopics)
dataNode = doc.xpathEval('/equipment-model/data')[0]
iecommon.logError("len(dataNode)" + dataNode.get_name(), logTopics)
deviceDataNode = getOrCreateChildElement(dataNode,'device-data')
configurationNode = getOrCreateChildElement(deviceDataNode,'configuration')
settingNode = getOrCreateChildElement(deviceDataNode,'setting')
acquisitionNode = getOrCreateChildElement(deviceDataNode,'acquisition')
self.getOrCreatePLCHostNameField(configurationNode)
self.getOrCreatePLCDeviceLabelField(configurationNode)
for block in designClass.getDesignBlocks():
for reg in block.getDesignRegisters():
if reg.isSetting():
fieldNode = self.getOrCreateFieldNode(settingNode,reg)
fillAttributes(fieldNode, {'multiplexed': 'false', 'persistent': 'true'})
elif reg.isAcquisition():
fieldNode = self.getOrCreateFieldNode(acquisitionNode,reg)
fillAttributes(fieldNode, {'cycle-bound': 'false', 'persistent': 'false'})
elif reg.isConfiguration():
fieldNode = self.getOrCreateFieldNode(configurationNode,reg)
else:
raise Exception( "Cannot identify register-type to use for register:" + reg.name )
self.getOrCreateType(fieldNode,reg)
globalDataNode = getOrCreateChildElement(dataNode,'global-data')
globalConfigurationNode = ""
if len(globalDataNode.xpathEval("configuration")) == 0:
if len( globalDataNode.xpathEval("*")) == 0:
globalConfigurationNode = getOrCreateChildElement(globalDataNode,'configuration')
else:
globalConfigurationNode = getOrCreatePreviousSiblingElement(getFirstChild(globalDataNode),'configuration')
else:
globalConfigurationNode = globalDataNode.xpathEval("configuration")[0]
self.getOrCreatePLCClassVersionField(globalConfigurationNode,designClass.version)
# Fill custom-types with enums.
enums = designClass.getEnums()
customTypesNode = doc.xpathEval('/equipment-model/custom-types')[0]
for enum in enums:
enumElement = getOrCreateNamedChildElement(customTypesNode, "enum", enum.name)
existing_items = enumElement.xpathEval("item")
to_add = []
to_edit = []
# Loop through all new enums and check which should be added and which edited.
for item in enum.items:
if item.symbol in [item.prop("symbol") for item in existing_items]:
to_edit.append(item)
else:
to_add.append(item)
# Loop though all existing enums and remove any which are not in new enums.
to_add_edit = to_add + to_edit
for existing in existing_items:
if existing.prop("symbol") not in [item.symbol for item in to_add_edit]:
existing.unlinkNode()
existing.freeNode()
# Edit existing items.
for item in to_edit:
for existing in existing_items:
if existing.prop("symbol") != item.symbol:
continue
existing.setProp("access", item.access)
existing.setProp("value", item.value)
# Add missing items.
for item in to_add:
itemElement = libxml2.newNode("item")
enumElement.addChild(itemElement)
itemElement.setProp("access", item.access)
itemElement.setProp("value", item.value)
itemElement.setProp("symbol", item.symbol)
......@@ -14,37 +14,13 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import fesa.fesa_3_0_0.generateSourceCode
from test.testBase import *
def genHSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
return fesa.fesa_3_0_0.generateSourceCode.genHSource(className, silecsRoot, fesaRoot, sourcePath,logTopics)
import test.fesa.fillFESADeployUnitTest
import test.fesa.generateFesaDesignTest
import test.fesa.generateSourceCodeTest
import migration.runTests
def genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics):
return fesa.fesa_3_0_0.generateSourceCode.genCppSource(className, silecsRoot, fesaRoot, sourcePath,logTopics)
import test.general.iecommonTest
import test.general.genplcsrcTest
import test.general.genParamTest
import test.general.genDuWrapperTest
def runTests():
migration.runTests.runAllTests()
test.fesa.fillFESADeployUnitTest.runTests()
test.fesa.generateFesaDesignTest.runTests()
test.fesa.generateSourceCodeTest.runTests()
test.general.iecommonTest.runTests()
test.general.genParamTest.runTests()
test.general.genplcsrcTest.runTests()
test.general.genDuWrapperTest.runTests()
print "################################################"
print "# Test suite finished - no failures detected ! #"
print "################################################"
sys.exit(0)
# ********************** module stand alone code **********************
if __name__ == "__main__":
runTests()
def genCppFiles(className, workspacePath, silecsDesignFilePath,logTopics={'errorlog': True}):
return fesa.fesa_3_0_0.generateSourceCode.genCppFiles(className, workspacePath, silecsDesignFilePath,logTopics)