Commit f48f2b58 authored by Pavel Vainerman's avatar Pavel Vainerman

Перевёл глобальный UniSetTypes::conf на использование shared_ptr + singleton

(заодно привёл форматирование к общему виду "пробелы вместо tab").
parent dab976bb
...@@ -56,13 +56,13 @@ string conffile("configure.xml"); ...@@ -56,13 +56,13 @@ string conffile("configure.xml");
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static bool commandToAll( const string& section, ObjectRepository *rep, Command cmd ); static bool commandToAll( const string& section, ObjectRepository *rep, Command cmd );
static void createSections( UniSetTypes::Configuration* c ); static void createSections( const std::shared_ptr<UniSetTypes::Configuration> c );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int omap(); int omap();
int configure( const string& args, UInterface &ui ); int configure( const string& args, UInterface &ui );
int logRotate( const string& args, UInterface &ui ); int logRotate( const string& args, UInterface &ui );
int setValue( const string& args, UInterface &ui, Configuration* conf = UniSetTypes::conf ); int setValue( const string& args, UInterface &ui );
int getValue( const string& args, UInterface &ui, Configuration* conf = UniSetTypes::conf ); int getValue( const string& args, UInterface &ui );
int getRawValue( const string& args, UInterface &ui ); int getRawValue( const string& args, UInterface &ui );
int getState( const string& args, UInterface &ui ); int getState( const string& args, UInterface &ui );
int getCalibrate( const string& args, UInterface &ui ); int getCalibrate( const string& args, UInterface &ui );
...@@ -153,14 +153,14 @@ int main(int argc, char** argv) ...@@ -153,14 +153,14 @@ int main(int argc, char** argv)
case 'b': //--create case 'b': //--create
{ {
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
createSections(conf); createSections(conf);
} }
return 0; return 0;
case 'x': //--setValue case 'x': //--setValue
{ {
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return setValue(optarg,ui); return setValue(optarg,ui);
} }
...@@ -169,7 +169,7 @@ int main(int argc, char** argv) ...@@ -169,7 +169,7 @@ int main(int argc, char** argv)
case 'g': //--getValue case 'g': //--getValue
{ {
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl; // cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return getValue(optarg,ui); return getValue(optarg,ui);
} }
...@@ -178,7 +178,7 @@ int main(int argc, char** argv) ...@@ -178,7 +178,7 @@ int main(int argc, char** argv)
case 'w': //--getRawValue case 'w': //--getRawValue
{ {
// cout<<"(main):received option --getRawValue='"<<optarg<<"'"<<endl; // cout<<"(main):received option --getRawValue='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return getRawValue(optarg,ui); return getRawValue(optarg,ui);
} }
...@@ -187,7 +187,7 @@ int main(int argc, char** argv) ...@@ -187,7 +187,7 @@ int main(int argc, char** argv)
case 'p': //--oinfo case 'p': //--oinfo
{ {
// cout<<"(main):received option --oinfo='"<<optarg<<"'"<<endl; // cout<<"(main):received option --oinfo='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return oinfo(optarg,ui); return oinfo(optarg,ui);
} }
...@@ -196,10 +196,10 @@ int main(int argc, char** argv) ...@@ -196,10 +196,10 @@ int main(int argc, char** argv)
case 'e': //--exist case 'e': //--exist
{ {
// cout<<"(main):received option --exist"<<endl; // cout<<"(main):received option --exist"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
verb = true; verb = true;
Command cmd=Exist; Command cmd=Exist;
ObjectRepository* rep = new ObjectRepository(conf); ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)cmd); commandToAll(conf->getServicesSection(), rep, (Command)cmd);
...@@ -213,7 +213,7 @@ int main(int argc, char** argv) ...@@ -213,7 +213,7 @@ int main(int argc, char** argv)
case 's': //--start case 's': //--start
{ {
// cout<<"(main):received option --start"<<endl; // cout<<"(main):received option --start"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
Command cmd=StartUp; Command cmd=StartUp;
...@@ -227,7 +227,7 @@ int main(int argc, char** argv) ...@@ -227,7 +227,7 @@ int main(int argc, char** argv)
case 'r': //--configure case 'r': //--configure
{ {
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return configure(optarg,ui); return configure(optarg,ui);
} }
...@@ -236,7 +236,7 @@ int main(int argc, char** argv) ...@@ -236,7 +236,7 @@ int main(int argc, char** argv)
case 'f': //--finish case 'f': //--finish
{ {
// cout<<"(main):received option --finish"<<endl; // cout<<"(main):received option --finish"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
Command cmd=Finish; Command cmd=Finish;
...@@ -252,7 +252,7 @@ int main(int argc, char** argv) ...@@ -252,7 +252,7 @@ int main(int argc, char** argv)
case 'l': //--logrotate case 'l': //--logrotate
{ {
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return logRotate(optarg, ui); return logRotate(optarg, ui);
} }
...@@ -261,7 +261,7 @@ int main(int argc, char** argv) ...@@ -261,7 +261,7 @@ int main(int argc, char** argv)
case 'y': //--getCalibrate case 'y': //--getCalibrate
{ {
// cout<<"(main):received option --getCalibrate='"<<optarg<<"'"<<endl; // cout<<"(main):received option --getCalibrate='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
return getCalibrate(optarg, ui); return getCalibrate(optarg, ui);
} }
...@@ -270,7 +270,7 @@ int main(int argc, char** argv) ...@@ -270,7 +270,7 @@ int main(int argc, char** argv)
case 'u': //--foldUp case 'u': //--foldUp
{ {
// cout<<"(main):received option --foldUp"<<endl; // cout<<"(main):received option --foldUp"<<endl;
uniset_init(argc,argv,conffile); auto conf = uniset_init(argc,argv,conffile);
UInterface ui(conf); UInterface ui(conf);
Command cmd=FoldUp; Command cmd=FoldUp;
...@@ -449,7 +449,7 @@ static bool commandToAll(const string& section, ObjectRepository *rep, Command c ...@@ -449,7 +449,7 @@ static bool commandToAll(const string& section, ObjectRepository *rep, Command c
} }
// ============================================================================================== // ==============================================================================================
static void createSections( UniSetTypes::Configuration* rconf ) static void createSections( const std::shared_ptr<UniSetTypes::Configuration> rconf )
{ {
ObjectRepositoryFactory repf(rconf); ObjectRepositoryFactory repf(rconf);
...@@ -469,7 +469,7 @@ int omap() ...@@ -469,7 +469,7 @@ int omap()
{ {
cout.setf(ios::left, ios::adjustfield); cout.setf(ios::left, ios::adjustfield);
cout << "========================== ObjectsMap =================================\n"; cout << "========================== ObjectsMap =================================\n";
conf->oind->printMap(cout); uniset_conf()->oind->printMap(cout);
cout << "==========================================================================\n"; cout << "==========================================================================\n";
} }
catch( Exception& ex ) catch( Exception& ex )
...@@ -482,9 +482,10 @@ int omap() ...@@ -482,9 +482,10 @@ int omap()
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
int setValue( const string& args, UInterface &ui, Configuration* conf ) int setValue( const string& args, UInterface &ui )
{ {
int err = 0; int err = 0;
auto conf = ui.getConf();
typedef std::list<UniSetTypes::ParamSInfo> SList; typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList(args, conf); SList sl = UniSetTypes::getSInfoList(args, conf);
...@@ -536,12 +537,13 @@ int setValue( const string& args, UInterface &ui, Configuration* conf ) ...@@ -536,12 +537,13 @@ int setValue( const string& args, UInterface &ui, Configuration* conf )
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
int getValue( const string& args, UInterface &ui, Configuration* conf ) int getValue( const string& args, UInterface &ui )
{ {
int err = 0; int err = 0;
auto conf = ui.getConf();
typedef std::list<UniSetTypes::ParamSInfo> SList; typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf ); SList sl = UniSetTypes::getSInfoList( args, conf );
if( verb ) if( verb )
cout << "====== getValue ======" << endl; cout << "====== getValue ======" << endl;
...@@ -594,8 +596,9 @@ int getValue( const string& args, UInterface &ui, Configuration* conf ) ...@@ -594,8 +596,9 @@ int getValue( const string& args, UInterface &ui, Configuration* conf )
int getCalibrate( const std::string& args, UInterface &ui ) int getCalibrate( const std::string& args, UInterface &ui )
{ {
int err = 0; int err = 0;
auto conf = ui.getConf();
typedef std::list<UniSetTypes::ParamSInfo> SList; typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf ); SList sl = UniSetTypes::getSInfoList( args, conf );
if( verb ) if( verb )
cout << "====== getCalibrate ======" << endl; cout << "====== getCalibrate ======" << endl;
...@@ -635,8 +638,9 @@ int getCalibrate( const std::string& args, UInterface &ui ) ...@@ -635,8 +638,9 @@ int getCalibrate( const std::string& args, UInterface &ui )
int getRawValue( const std::string& args, UInterface &ui ) int getRawValue( const std::string& args, UInterface &ui )
{ {
int err = 0; int err = 0;
auto conf = ui.getConf();
typedef std::list<UniSetTypes::ParamSInfo> SList; typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf ); SList sl = UniSetTypes::getSInfoList( args, conf );
if( verb ) if( verb )
cout << "====== getRawValue ======" << endl; cout << "====== getRawValue ======" << endl;
for( SList::iterator it=sl.begin(); it!=sl.end(); ++it ) for( SList::iterator it=sl.begin(); it!=sl.end(); ++it )
...@@ -668,6 +672,7 @@ int getRawValue( const std::string& args, UInterface &ui ) ...@@ -668,6 +672,7 @@ int getRawValue( const std::string& args, UInterface &ui )
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
int logRotate( const string& arg, UInterface &ui ) int logRotate( const string& arg, UInterface &ui )
{ {
auto conf = ui.getConf();
// посылка всем // посылка всем
if( arg.empty() || (arg.c_str())[0]!='-' ) if( arg.empty() || (arg.c_str())[0]!='-' )
{ {
...@@ -699,6 +704,7 @@ int logRotate( const string& arg, UInterface &ui ) ...@@ -699,6 +704,7 @@ int logRotate( const string& arg, UInterface &ui )
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
int configure( const string& arg, UInterface &ui ) int configure( const string& arg, UInterface &ui )
{ {
auto conf = ui.getConf();
// посылка всем // посылка всем
if( arg.empty() || (arg.c_str())[0]!='-' ) if( arg.empty() || (arg.c_str())[0]!='-' )
{ {
...@@ -732,7 +738,7 @@ int oinfo( const string& arg, UInterface &ui ) ...@@ -732,7 +738,7 @@ int oinfo( const string& arg, UInterface &ui )
UniSetTypes::ObjectId oid(uni_atoi(arg)); UniSetTypes::ObjectId oid(uni_atoi(arg));
if( oid==0 ) if( oid==0 )
{ {
if( verb ) if( verb )
cout << "(oinfo): Не задан OID!"<< endl; cout << "(oinfo): Не задан OID!"<< endl;
return 1; return 1;
} }
......
...@@ -36,7 +36,7 @@ int main(int argc, char** argv) ...@@ -36,7 +36,7 @@ int main(int argc, char** argv)
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc,argv,"configure.xml");
// определяем ID объекта // определяем ID объекта
......
...@@ -36,8 +36,8 @@ int main( int argc, char **argv ) ...@@ -36,8 +36,8 @@ int main( int argc, char **argv )
} }
// ------------------------------------- // -------------------------------------
uniset_init(argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv, "configure.xml" );
UInterface ui; UInterface ui(conf);
string sid(conf->getArgParam("--sid")); string sid(conf->getArgParam("--sid"));
if( sid.empty() ) if( sid.empty() )
...@@ -46,7 +46,7 @@ int main( int argc, char **argv ) ...@@ -46,7 +46,7 @@ int main( int argc, char **argv )
return 1; return 1;
} }
std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid,UniSetTypes::conf); std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid,conf);
if( lst.empty() ) if( lst.empty() )
{ {
......
...@@ -19,7 +19,7 @@ int main( int argc, const char **argv ) ...@@ -19,7 +19,7 @@ int main( int argc, const char **argv )
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc"); string name = conf->getArgParam("--name", "TestProc");
......
...@@ -21,7 +21,7 @@ int main(int argc, const char **argv) ...@@ -21,7 +21,7 @@ int main(int argc, const char **argv)
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc,argv,"configure.xml");
bool fullname = false; bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 ) if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
......
...@@ -50,10 +50,10 @@ ...@@ -50,10 +50,10 @@
<xsl:if test="normalize-space(@vartype)!='io'"> <xsl:if test="normalize-space(@vartype)!='io'">
<xsl:value-of select="../../@name"/>(<xsl:value-of select="../../@id"/>), <xsl:value-of select="../../@name"/>(<xsl:value-of select="../../@id"/>),
<xsl:if test="not(normalize-space(../../@node)='')"> <xsl:if test="not(normalize-space(../../@node)='')">
node_<xsl:value-of select="../../@name"/>(conf->getNodeID("<xsl:value-of select="../../@node"/>")), node_<xsl:value-of select="../../@name"/>(uniset_conf()->getNodeID("<xsl:value-of select="../../@node"/>")),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(../../@node)=''"> <xsl:if test="normalize-space(../../@node)=''">
node_<xsl:value-of select="../../@name"/>(UniSetTypes::conf->getLocalNode()), node_<xsl:value-of select="../../@name"/>(UniSetTypes::uniset_conf()->getLocalNode()),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(../../@default)=''"> <xsl:if test="normalize-space(../../@default)=''">
<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>(0), <xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>(0),
...@@ -159,7 +159,7 @@ ...@@ -159,7 +159,7 @@
bool alarm( UniSetTypes::ObjectId sid, bool state ); bool alarm( UniSetTypes::ObjectId sid, bool state );
long getValue( UniSetTypes::ObjectId sid ); long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value ); void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
void updateValues(); void updateValues();
void setMsg( UniSetTypes::ObjectId code, bool state ); void setMsg( UniSetTypes::ObjectId code, bool state );
...@@ -229,9 +229,9 @@ ...@@ -229,9 +229,9 @@
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string&amp; name) { return UniSetTypes::conf->getIntProp(confnode, name); } int getIntProp(const std::string&amp; name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string&amp; name) { return UniSetTypes::conf->getProp(confnode, name); } inline const std::string getProp(const std::string&amp; name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
int smReadyTimeout; /*!&lt; время ожидания готовности SM */ int smReadyTimeout; /*!&lt; время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
...@@ -418,7 +418,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -418,7 +418,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
</xsl:template> </xsl:template>
<xsl:template name="COMMON-ID-LIST"> <xsl:template name="COMMON-ID-LIST">
if( UniSetTypes::findArgParam("--print-id-list",conf->getArgc(),conf->getArgv()) != -1 ) if( UniSetTypes::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
{ {
<xsl:for-each select="//smap/item"> <xsl:for-each select="//smap/item">
if( <xsl:value-of select="normalize-space(@name)"/> != UniSetTypes::DefaultObjectId ) if( <xsl:value-of select="normalize-space(@name)"/> != UniSetTypes::DefaultObjectId )
...@@ -444,22 +444,22 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -444,22 +444,22 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
</xsl:template> </xsl:template>
<xsl:template name="init-variables"> <xsl:template name="init-variables">
<xsl:if test="normalize-space(@type)='int'"> <xsl:if test="normalize-space(@type)='int'">
<xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))), <xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@type)='long'"> <xsl:if test="normalize-space(@type)='long'">
<xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))), <xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@type)='float'"> <xsl:if test="normalize-space(@type)='float'">
<xsl:value-of select="normalize-space(@name)"/>(atof( init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>").c_str())), <xsl:value-of select="normalize-space(@name)"/>(atof( init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>").c_str())),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@type)='double'"> <xsl:if test="normalize-space(@type)='double'">
<xsl:value-of select="normalize-space(@name)"/>(atof( init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>").c_str())), <xsl:value-of select="normalize-space(@name)"/>(atof( init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>").c_str())),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@type)='bool'"> <xsl:if test="normalize-space(@type)='bool'">
<xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))), <xsl:value-of select="normalize-space(@name)"/>(uni_atoi( init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>"))),
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@type)='str'"> <xsl:if test="normalize-space(@type)='str'">
<xsl:value-of select="normalize-space(@name)"/>(init3_str(conf->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),conf->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>")), <xsl:value-of select="normalize-space(@name)"/>(init3_str(uniset_conf()->getArgParam("--" + argprefix + "<xsl:value-of select="@name"/>"),uniset_conf()->getProp(cnode,"<xsl:value-of select="@name"/>"),"<xsl:value-of select="normalize-space(@default)"/>")),
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
...@@ -552,13 +552,13 @@ static const std::string init3_str( const std::string&amp; s1, const std::string ...@@ -552,13 +552,13 @@ static const std::string init3_str( const std::string&amp; s1, const std::string
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
<xsl:for-each select="//smap/item"> <xsl:for-each select="//smap/item">
<xsl:if test="normalize-space(@vartype)!='io'"> <xsl:if test="normalize-space(@vartype)!='io'">
<xsl:value-of select="normalize-space(@name)"/>(conf->getSensorID(conf->getProp(cnode,"<xsl:value-of select="normalize-space(@name)"/>"))), <xsl:value-of select="normalize-space(@name)"/>(uniset_conf()->getSensorID(uniset_conf()->getProp(cnode,"<xsl:value-of select="normalize-space(@name)"/>"))),
node_<xsl:value-of select="normalize-space(@name)"/>( conf->getNodeID(conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>")) ), node_<xsl:value-of select="normalize-space(@name)"/>( uniset_conf()->getNodeID(uniset_conf()->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>")) ),
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
<xsl:for-each select="//msgmap/item"><xsl:value-of select="normalize-space(@name)"/>(conf->getSensorID(conf->getProp(cnode,"<xsl:value-of select="normalize-space(@name)"/>"))), <xsl:for-each select="//msgmap/item"><xsl:value-of select="normalize-space(@name)"/>(uniset_conf()->getSensorID(uniset_conf()->getProp(cnode,"<xsl:value-of select="normalize-space(@name)"/>"))),
node_<xsl:value-of select="normalize-space(@name)"/>(conf->getNodeID( conf->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>"))), node_<xsl:value-of select="normalize-space(@name)"/>(uniset_conf()->getNodeID( uniset_conf()->getProp(cnode,"node_<xsl:value-of select="normalize-space(@name)"/>"))),
m_<xsl:value-of select="normalize-space(@name)"/>(false), m_<xsl:value-of select="normalize-space(@name)"/>(false),
prev_m_<xsl:value-of select="normalize-space(@name)"/>(false), prev_m_<xsl:value-of select="normalize-space(@name)"/>(false),
</xsl:for-each> </xsl:for-each>
...@@ -577,8 +577,8 @@ sleep_msec(<xsl:call-template name="settings"><xsl:with-param name="varname" sel ...@@ -577,8 +577,8 @@ sleep_msec(<xsl:call-template name="settings"><xsl:with-param name="varname" sel
active(true), active(true),
<xsl:if test="normalize-space($TESTMODE)!=''"> <xsl:if test="normalize-space($TESTMODE)!=''">
isTestMode(false), isTestMode(false),
idTestMode_S(conf->getSensorID("TestMode_S")), idTestMode_S(uniset_conf()->getSensorID("TestMode_S")),
idLocalTestMode_S(conf->getSensorID(conf->getProp(cnode,"LocalTestMode_S"))), idLocalTestMode_S(uniset_conf()->getSensorID(uniset_conf()->getProp(cnode,"LocalTestMode_S"))),
in_TestMode_S(false), in_TestMode_S(false),
in_LocalTestMode_S(false), in_LocalTestMode_S(false),
</xsl:if> </xsl:if>
...@@ -587,7 +587,7 @@ maxHeartBeat(10), ...@@ -587,7 +587,7 @@ maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(conf->getPIntProp(cnode,"askPause",2000)), askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
<xsl:for-each select="//variables/item"> <xsl:for-each select="//variables/item">
<xsl:if test="normalize-space(@private)!=''"> <xsl:if test="normalize-space(@private)!=''">
<xsl:call-template name="init-variables"/> <xsl:call-template name="init-variables"/>
...@@ -595,6 +595,8 @@ askPause(conf->getPIntProp(cnode,"askPause",2000)), ...@@ -595,6 +595,8 @@ askPause(conf->getPIntProp(cnode,"askPause",2000)),
</xsl:for-each> </xsl:for-each>
end_private(false) end_private(false)
{ {
auto conf = uniset_conf();
<xsl:call-template name="COMMON-ID-LIST"/> <xsl:call-template name="COMMON-ID-LIST"/>
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
...@@ -898,8 +900,8 @@ sleep_msec(<xsl:call-template name="settings-alone"><xsl:with-param name="varnam ...@@ -898,8 +900,8 @@ sleep_msec(<xsl:call-template name="settings-alone"><xsl:with-param name="varnam
active(true), active(true),
<xsl:if test="normalize-space($TESTMODE)!=''"> <xsl:if test="normalize-space($TESTMODE)!=''">
isTestMode(false), isTestMode(false),
idTestMode_S(conf->getSensorID("TestMode_S")), idTestMode_S(uniset_conf()->getSensorID("TestMode_S")),
idLocalTestMode_S(conf->getSensorID(conf->getProp(cnode,"LocalTestMode_S"))), idLocalTestMode_S(uniset_conf()->getSensorID(uniset_conf()->getProp(cnode,"LocalTestMode_S"))),
in_TestMode_S(false), in_TestMode_S(false),
in_LocalTestMode_S(false), in_LocalTestMode_S(false),
</xsl:if> </xsl:if>
...@@ -907,8 +909,10 @@ idHeartBeat(DefaultObjectId), ...@@ -907,8 +909,10 @@ idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
activated(false), activated(false),
askPause(conf->getPIntProp(cnode,"askPause",2000)) askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000))
{ {
auto conf = uniset_conf();
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
......
...@@ -51,10 +51,10 @@ class <xsl:value-of select="$CLASSNAME"/>_SK: ...@@ -51,10 +51,10 @@ class <xsl:value-of select="$CLASSNAME"/>_SK:
{ {
public: public:
<xsl:if test="not(normalize-space($OID))=''"> <xsl:if test="not(normalize-space($OID))=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = UniSetTypes::conf->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($OID)"/>"), const string&amp; argprefix="" ); <xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = UniSetTypes::uniset_conf()->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::uniset_conf()->getNode("<xsl:value-of select="normalize-space($OID)"/>"), const string&amp; argprefix="" );
</xsl:if> </xsl:if>
<xsl:if test="normalize-space($OID)=''"> <xsl:if test="normalize-space($OID)=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($OID)"/>") ); <xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("<xsl:value-of select="normalize-space($OID)"/>") );
</xsl:if> </xsl:if>
<xsl:value-of select="$CLASSNAME"/>_SK(); <xsl:value-of select="$CLASSNAME"/>_SK();
......
...@@ -52,10 +52,10 @@ class <xsl:value-of select="$CLASSNAME"/>_SK: ...@@ -52,10 +52,10 @@ class <xsl:value-of select="$CLASSNAME"/>_SK:
{ {
public: public:
<xsl:if test="not(normalize-space($OID))=''"> <xsl:if test="not(normalize-space($OID))=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = conf->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($CNAME)"/>"), const std::string&amp; argprefix="<xsl:value-of select="normalize-space($ARGPREFIX)"/>" ); <xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id = UniSetTypes::uniset_conf()->getObjectID("<xsl:value-of select="$OID"/>"), xmlNode* node=UniSetTypes::uniset_conf()->getNode("<xsl:value-of select="normalize-space($CNAME)"/>"), const std::string&amp; argprefix="<xsl:value-of select="normalize-space($ARGPREFIX)"/>" );
</xsl:if> </xsl:if>
<xsl:if test="normalize-space($OID)=''"> <xsl:if test="normalize-space($OID)=''">
<xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::conf->getNode("<xsl:value-of select="normalize-space($CNAME)"/>"), const std::string&amp; argprefix="<xsl:value-of select="normalize-space($ARGPREFIX)"/>" ); <xsl:value-of select="$CLASSNAME"/>_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("<xsl:value-of select="normalize-space($CNAME)"/>"), const std::string&amp; argprefix="<xsl:value-of select="normalize-space($ARGPREFIX)"/>" );
</xsl:if> </xsl:if>
<xsl:value-of select="$CLASSNAME"/>_SK(); <xsl:value-of select="$CLASSNAME"/>_SK();
virtual ~<xsl:value-of select="$CLASSNAME"/>_SK(); virtual ~<xsl:value-of select="$CLASSNAME"/>_SK();
......
...@@ -50,9 +50,7 @@ int main( int argc,char* argv[] ) ...@@ -50,9 +50,7 @@ int main( int argc,char* argv[] )
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv,confile);
// определяем ID объекта // определяем ID объекта
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
...@@ -74,7 +72,7 @@ int main( int argc,char* argv[] ) ...@@ -74,7 +72,7 @@ int main( int argc,char* argv[] )
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
obj.mylog.logFile( logname.c_str() ); obj.mylog.logFile( logname.c_str() );
UniSetActivator* act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act-&gt;addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj)); act-&gt;addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
......
...@@ -52,9 +52,7 @@ int main( int argc, const char** argv ) ...@@ -52,9 +52,7 @@ int main( int argc, const char** argv )
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv, confile);
<xsl:if test="not(normalize-space(//@OID))=''"> <xsl:if test="not(normalize-space(//@OID))=''">
<xsl:value-of select="$CLASSNAME"/> obj; <xsl:value-of select="$CLASSNAME"/> obj;
...@@ -82,7 +80,7 @@ int main( int argc, const char** argv ) ...@@ -82,7 +80,7 @@ int main( int argc, const char** argv )
</xsl:if> </xsl:if>
UniSetActivator* act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act-&gt;addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj)); act-&gt;addObject(static_cast&lt;class UniSetObject*&gt;(&amp;obj));
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
......
...@@ -9,7 +9,7 @@ int main( int argc, const char **argv ) ...@@ -9,7 +9,7 @@ int main( int argc, const char **argv )
{ {
try try
{ {
uniset_init(argc, argv); auto conf = uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log"); string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
...@@ -17,7 +17,7 @@ int main( int argc, const char **argv ) ...@@ -17,7 +17,7 @@ int main( int argc, const char **argv )
ulog.logFile( logname.c_str() ); ulog.logFile( logname.c_str() );
// conf->initDebug(dlog,"dlog"); // conf->initDebug(dlog,"dlog");
UniSetActivator act; auto act = UniSetActivator::Instance();
xmlNode* cnode = conf->getNode("Skel"); xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL ) if( cnode == NULL )
{ {
...@@ -35,7 +35,7 @@ int main( int argc, const char **argv ) ...@@ -35,7 +35,7 @@ int main( int argc, const char **argv )
ulog << "(Skel::main): -------------- Skel START -------------------------\n\n"; ulog << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlog << "\n\n\n"; dlog << "\n\n\n";
dlog << "(Skel::main): -------------- Skel START -------------------------\n\n"; dlog << "(Skel::main): -------------- Skel START -------------------------\n\n";
act.run(false); act->run(false);
} }
catch(SystemError& err) catch(SystemError& err)
{ {
......
...@@ -8,7 +8,7 @@ class Skel: ...@@ -8,7 +8,7 @@ class Skel:
public Skel_SK public Skel_SK
{ {
public: public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("Skel") ); Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("Skel") );
virtual ~Skel(); virtual ~Skel();
protected: protected:
......
...@@ -8,7 +8,7 @@ class TestGen: ...@@ -8,7 +8,7 @@ class TestGen:
public TestGen_SK public TestGen_SK
{ {
public: public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGen") ); TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGen") );
virtual ~TestGen(); virtual ~TestGen();
......
...@@ -8,7 +8,7 @@ class TestGenAlone: ...@@ -8,7 +8,7 @@ class TestGenAlone:
public TestGenAlone_SK public TestGenAlone_SK
{ {
public: public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::conf->getNode("TestGenAlone") ); TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGenAlone") );
virtual ~TestGenAlone(); virtual ~TestGenAlone();
......
...@@ -59,7 +59,7 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id): ...@@ -59,7 +59,7 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id):
} }
DBServer_MySQL::DBServer_MySQL(): DBServer_MySQL::DBServer_MySQL():
DBServer(conf->getDBServer()), DBServer(uniset_conf()->getDBServer()),
db(new MySQLInterface()), db(new MySQLInterface()),
PingTime(300000), PingTime(300000),
ReconnectTime(180000), ReconnectTime(180000),
...@@ -261,11 +261,13 @@ void DBServer_MySQL::init_dbserver() ...@@ -261,11 +261,13 @@ void DBServer_MySQL::init_dbserver()
if( connect_ok ) if( connect_ok )
{ {
initDBTableMap(tblMap); initDBTableMap(tblMap);
initDB(db); initDB(db);
return; return;
} }
auto conf = uniset_conf();
if( conf->getDBServer() == UniSetTypes::DefaultObjectId ) if( conf->getDBServer() == UniSetTypes::DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -335,6 +337,8 @@ void DBServer_MySQL::init_dbserver() ...@@ -335,6 +337,8 @@ void DBServer_MySQL::init_dbserver()
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::createTables( MySQLInterface *db ) void DBServer_MySQL::createTables( MySQLInterface *db )
{ {
auto conf = uniset_conf();
UniXML::iterator it( conf->getNode("Tables") ); UniXML::iterator it( conf->getNode("Tables") );
if(!it) if(!it)
{ {
......
...@@ -106,8 +106,8 @@ bool MySQLInterface::query_ok( const string& q ) ...@@ -106,8 +106,8 @@ bool MySQLInterface::query_ok( const string& q )
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( !res || mysql_num_rows(res)==0 ) if( !res || mysql_num_rows(res)==0 )
{ {
if( res ) if( res )
mysql_free_result(res); mysql_free_result(res);
return false; return false;
} }
......
...@@ -21,7 +21,7 @@ int main(int argc, char** argv) ...@@ -21,7 +21,7 @@ int main(int argc, char** argv)
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
......
...@@ -8,9 +8,9 @@ using namespace std; ...@@ -8,9 +8,9 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
std::string dbname("test-db"); std::string dbname("test-db");
if( argc > 1 ) if( argc > 1 )
dbname = string(argv[1]); dbname = string(argv[1]);
try try
{ {
......
...@@ -57,7 +57,7 @@ DBServer_SQLite::DBServer_SQLite( ObjectId id ): ...@@ -57,7 +57,7 @@ DBServer_SQLite::DBServer_SQLite( ObjectId id ):
} }
DBServer_SQLite::DBServer_SQLite(): DBServer_SQLite::DBServer_SQLite():
DBServer(conf->getDBServer()), DBServer(uniset_conf()->getDBServer()),
db(new SQLiteInterface()), db(new SQLiteInterface()),
PingTime(300000), PingTime(300000),
ReconnectTime(180000), ReconnectTime(180000),
...@@ -251,6 +251,8 @@ void DBServer_SQLite::init_dbserver() ...@@ -251,6 +251,8 @@ void DBServer_SQLite::init_dbserver()
return; return;
} }
auto conf = uniset_conf();
if( conf->getDBServer() == UniSetTypes::DefaultObjectId ) if( conf->getDBServer() == UniSetTypes::DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -313,6 +315,7 @@ void DBServer_SQLite::init_dbserver() ...@@ -313,6 +315,7 @@ void DBServer_SQLite::init_dbserver()
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::createTables( SQLiteInterface *db ) void DBServer_SQLite::createTables( SQLiteInterface *db )
{ {
auto conf = uniset_conf();
UniXML::iterator it( conf->getNode("Tables") ); UniXML::iterator it( conf->getNode("Tables") );
if(!it) if(!it)
{ {
......
...@@ -254,11 +254,11 @@ SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize ) ...@@ -254,11 +254,11 @@ SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
int n = sqlite3_data_count(s); int n = sqlite3_data_count(s);
if( n<=0 ) if( n<=0 )
{ {
if( finalize ) if( finalize )
sqlite3_finalize(s); sqlite3_finalize(s);
return; return;
} }
COL c; COL c;
for( unsigned int i=0; i<n; i++ ) for( unsigned int i=0; i<n; i++ )
......
...@@ -21,7 +21,7 @@ int main(int argc, char** argv) ...@@ -21,7 +21,7 @@ int main(int argc, char** argv)
return 0; return 0;
} }
uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc,argv,"configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
......
...@@ -10,7 +10,7 @@ using namespace UniSetExtensions; ...@@ -10,7 +10,7 @@ using namespace UniSetExtensions;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, IOControl::IOInfo& inf ) std::ostream& operator<<( std::ostream& os, IOControl::IOInfo& inf )
{ {
os << "(" << inf.si.id << ")" << conf->oind->getMapName(inf.si.id) os << "(" << inf.si.id << ")" << uniset_conf()->oind->getMapName(inf.si.id)
<< " card=" << inf.ncard << " channel=" << inf.channel << " subdev=" << inf.subdev << " card=" << inf.ncard << " channel=" << inf.channel << " subdev=" << inf.subdev
<< " aref=" << inf.aref << " range=" << inf.range << " aref=" << inf.aref << " range=" << inf.range
<< " default=" << inf.defval << " safety=" << inf.safety; << " default=" << inf.defval << " safety=" << inf.safety;
...@@ -50,6 +50,8 @@ IOControl::IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, ...@@ -50,6 +50,8 @@ IOControl::IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID,
testmode(tmNone), testmode(tmNone),
prev_testmode(tmNone) prev_testmode(tmNone)
{ {
auto conf = uniset_conf();
string cname = conf->getArgParam("--"+prefix+"-confnode",myname); string cname = conf->getArgParam("--"+prefix+"-confnode",myname);
cnode = conf->getNode(cname); cnode = conf->getNode(cname);
if( cnode == NULL ) if( cnode == NULL )
...@@ -288,7 +290,7 @@ void IOControl::execute() ...@@ -288,7 +290,7 @@ void IOControl::execute()
// чтение параметров по входам-выходам // чтение параметров по входам-выходам
initIOCard(); initIOCard();
bool skip_iout = conf->getArgInt("--"+prefix+"-skip-init-output"); bool skip_iout = uniset_conf()->getArgInt("--"+prefix+"-skip-init-output");
if( !skip_iout ) if( !skip_iout )
initOutputs(); initOutputs();
...@@ -646,7 +648,7 @@ void IOControl::readConfiguration() ...@@ -646,7 +648,7 @@ void IOControl::readConfiguration()
{ {
readconf_ok = false; readconf_ok = false;
xmlNode* root = conf->getXMLSensorsSection(); xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root) if(!root)
{ {
ostringstream err; ostringstream err;
...@@ -716,39 +718,39 @@ bool IOControl::initIOItem( UniXML::iterator& it ) ...@@ -716,39 +718,39 @@ bool IOControl::initIOItem( UniXML::iterator& it )
else else
inf.subdev = DefaultSubdev; inf.subdev = DefaultSubdev;
} }
std::string prop_prefix( prefix+"_" ); std::string prop_prefix( prefix+"_" );
if( !IOBase::initItem(&inf,it,shm,prop_prefix,false,&dlog,myname,filtersize,filterT) ) if( !IOBase::initItem(&inf,it,shm,prop_prefix,false,&dlog,myname,filtersize,filterT) )
return false; return false;
// если вектор уже заполнен // если вектор уже заполнен
// то увеличиваем его на 30 элементов (с запасом) // то увеличиваем его на 30 элементов (с запасом)
// после инициализации делается resize // после инициализации делается resize
// под реальное количество // под реальное количество
if( maxItem >= iomap.size() ) if( maxItem >= iomap.size() )
iomap.resize(maxItem+30); iomap.resize(maxItem+30);
int prior = IOBase::initIntProp(it,"iopriority",prop_prefix,false); int prior = IOBase::initIntProp(it,"iopriority",prop_prefix,false);
if( prior > 0 ) if( prior > 0 )
{ {
IOPriority p(prior,maxItem); IOPriority p(prior,maxItem);
pmap.push_back(p); pmap.push_back(p);
if( dlog.debugging(Debug::LEVEL3) ) if( dlog.debugging(Debug::LEVEL3) )
dlog[Debug::LEVEL3] << myname << "(readItem): add to priority list: " << dlog[Debug::LEVEL3] << myname << "(readItem): add to priority list: " <<
it.getProp("name") it.getProp("name")
<< " priority=" << prior << endl; << " priority=" << prior << endl;
} }
// значит это пороговый датчик.. // значит это пороговый датчик..
if( inf.t_ai != DefaultObjectId ) if( inf.t_ai != DefaultObjectId )
{ {
iomap[maxItem++] = std::move(inf); iomap[maxItem++] = std::move(inf);
if( dlog.debugging(Debug::LEVEL3) ) if( dlog.debugging(Debug::LEVEL3) )
dlog[Debug::LEVEL3] << myname << "(readItem): add threshold '" << it.getProp("name") dlog[Debug::LEVEL3] << myname << "(readItem): add threshold '" << it.getProp("name")
<< " for '" << conf->oind->getNameById(inf.t_ai) << endl; << " for '" << uniset_conf()->oind->getNameById(inf.t_ai) << endl;
return true; return true;
} }
inf.channel = IOBase::initIntProp(it,"channel",prop_prefix,false); inf.channel = IOBase::initIntProp(it,"channel",prop_prefix,false);
if( inf.channel < 0 || inf.channel > 32 ) if( inf.channel < 0 || inf.channel > 32 )
{ {
...@@ -1105,7 +1107,7 @@ void IOControl::check_testlamp() ...@@ -1105,7 +1107,7 @@ void IOControl::check_testlamp()
} }
catch(...) catch(...)
{ {
dcrit << myname << "(check_testlamp): catch ..." << endl; dcrit << myname << "(check_testlamp): catch ..." << endl;
} }
} }
...@@ -1114,6 +1116,7 @@ IOControl* IOControl::init_iocontrol( int argc, const char* const* argv, ...@@ -1114,6 +1116,7 @@ IOControl* IOControl::init_iocontrol( int argc, const char* const* argv,
UniSetTypes::ObjectId icID, SharedMemory* ic, UniSetTypes::ObjectId icID, SharedMemory* ic,
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--"+prefix+"-name","IOControl1"); string name = conf->getArgParam("--"+prefix+"-name","IOControl1");
if( name.empty() ) if( name.empty() )
{ {
...@@ -1474,6 +1477,8 @@ void IOControl::waitSM() ...@@ -1474,6 +1477,8 @@ void IOControl::waitSM()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IOControl::buildCardsList() void IOControl::buildCardsList()
{ {
auto conf = uniset_conf();
xmlNode* nnode = conf->getXMLNodesSection(); xmlNode* nnode = conf->getXMLNodesSection();
if( !nnode ) if( !nnode )
{ {
...@@ -1481,7 +1486,7 @@ void IOControl::buildCardsList() ...@@ -1481,7 +1486,7 @@ void IOControl::buildCardsList()
return; return;
} }
const std::shared_ptr<UniXML> xml = conf->getConfXML(); auto xml = conf->getConfXML();
if( !xml ) if( !xml )
{ {
dwarn << myname << "(buildCardsList): xml=NULL?!" << endl; dwarn << myname << "(buildCardsList): xml=NULL?!" << endl;
......
...@@ -21,8 +21,7 @@ int main(int argc, const char **argv) ...@@ -21,8 +21,7 @@ int main(int argc, const char **argv)
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log"); string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
......
...@@ -11,6 +11,7 @@ using namespace UniSetExtensions; ...@@ -11,6 +11,7 @@ using namespace UniSetExtensions;
LProcessor::LProcessor( const std::string& name ): LProcessor::LProcessor( const std::string& name ):
logname(name) logname(name)
{ {
auto conf = uniset_conf();
sleepTime = conf->getArgPInt("--sleepTime", 200); sleepTime = conf->getArgPInt("--sleepTime", 200);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout",""); smReadyTimeout = conf->getArgInt("--sm-ready-timeout","");
if( smReadyTimeout == 0 ) if( smReadyTimeout == 0 )
...@@ -58,6 +59,8 @@ void LProcessor::step() ...@@ -58,6 +59,8 @@ void LProcessor::step()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::build( const string& lfile ) void LProcessor::build( const string& lfile )
{ {
auto conf = uniset_conf();
sch.read(lfile); sch.read(lfile);
// составляем карту внешних входов // составляем карту внешних входов
......
...@@ -11,6 +11,8 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o ...@@ -11,6 +11,8 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o
UniSetObject_LT(objId), UniSetObject_LT(objId),
shm(0) shm(0)
{ {
auto conf = uniset_conf();
logname = myname; logname = myname;
shm = new SMInterface(shmID,&(UniSetObject_LT::ui),objId,ic); shm = new SMInterface(shmID,&(UniSetObject_LT::ui),objId,ic);
build(lfile); build(lfile);
...@@ -28,7 +30,7 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o ...@@ -28,7 +30,7 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o
throw SystemError(err.str()); throw SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",conf->getHeartBeatTime());
if( heartbeatTime ) if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
......
...@@ -11,15 +11,14 @@ int main(int argc, const char **argv) ...@@ -11,15 +11,14 @@ int main(int argc, const char **argv)
{ {
try try
{ {
string confile=UniSetTypes::getArgParam("--confile",argc,argv,"configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--logicproc-logfile")); string logfilename(conf->getArgParam("--logicproc-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
logfilename = "logicproc.log"; logfilename = "logicproc.log";
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
std::ostringstream logname; std::ostringstream logname;
string dir(conf->getLogDir()); string dir(conf->getLogDir());
logname << dir << logfilename; logname << dir << logfilename;
......
...@@ -13,8 +13,7 @@ int main(int argc, const char **argv) ...@@ -13,8 +13,7 @@ int main(int argc, const char **argv)
{ {
try try
{ {
string confile=UniSetTypes::getArgParam("--confile",argc,argv,"configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--logicproc-logfile")); string logfilename(conf->getArgParam("--logicproc-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -11,92 +11,92 @@ using namespace UniSetTypes; ...@@ -11,92 +11,92 @@ using namespace UniSetTypes;
TEST_CASE("Logic processor","[LogicProcessor]") TEST_CASE("Logic processor","[LogicProcessor]")
{ {
#if 0 #if 0
SECTION( "ShemaXML" ) SECTION( "ShemaXML" )
{ {
SchemaXML sch; SchemaXML sch;
sch.read("schema.xml"); sch.read("schema.xml");
CHECK( !sch.empty() ); CHECK( !sch.empty() );
} }
#endif #endif
SECTION( "TOR" ) SECTION( "TOR" )
{ {
TOR e("1",2); // элемент на два входа.. TOR e("1",2); // элемент на два входа..
REQUIRE( e.getOut() == 0 ); REQUIRE( e.getOut() == 0 );
e.setIn(1,true); e.setIn(1,true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(2,true); e.setIn(2,true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(1,false); e.setIn(1,false);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(2,false); e.setIn(2,false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(3,true); // несуществующий вход.. e.setIn(3,true); // несуществующий вход..
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
} }
SECTION( "TAND" ) SECTION( "TAND" )
{ {
TAND e("1",2); // элемент на два входа.. TAND e("1",2); // элемент на два входа..
REQUIRE( e.getOut() == 0 ); REQUIRE( e.getOut() == 0 );
e.setIn(1,true); e.setIn(1,true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(2,true); e.setIn(2,true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(1,false); e.setIn(1,false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(2,false); e.setIn(2,false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(3,true); // несуществующий вход.. e.setIn(3,true); // несуществующий вход..
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
} }
SECTION( "TNOT" ) SECTION( "TNOT" )
{ {
TNOT e("1",false); TNOT e("1",false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(1,true); e.setIn(1,true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(1,false); e.setIn(1,false);
CHECK( e.getOut() ); CHECK( e.getOut() );
// other constructor // other constructor
TNOT e1("1",true); TNOT e1("1",true);
CHECK( e1.getOut() ); CHECK( e1.getOut() );
e1.setIn(1,true); e1.setIn(1,true);
CHECK_FALSE( e1.getOut() ); CHECK_FALSE( e1.getOut() );
e1.setIn(1,false); e1.setIn(1,false);
CHECK( e1.getOut() ); CHECK( e1.getOut() );
} }
SECTION( "TDelay" ) SECTION( "TDelay" )
{ {
TDelay e("1",50,1); TDelay e("1",50,1);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
// ON DELAY // ON DELAY
e.setIn(1,true); e.setIn(1,true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
msleep(60); msleep(60);
e.tick(); e.tick();
CHECK( e.getOut() ); CHECK( e.getOut() );
msleep(60); msleep(60);
e.tick(); e.tick();
CHECK( e.getOut() ); CHECK( e.getOut() );
// OFF DELAY // OFF DELAY
e.setIn(1,false); e.setIn(1,false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
// delay 0 msek.. // delay 0 msek..
e.setDelay(0); e.setDelay(0);
e.setIn(1,true); e.setIn(1,true);
CHECK( e.getOut() ); CHECK( e.getOut() );
// delay < 0 === 0 // delay < 0 === 0
e.setIn(1,false); e.setIn(1,false);
e.setDelay(-10); e.setDelay(-10);
e.setIn(1,true); e.setIn(1,true);
CHECK( e.getOut() ); CHECK( e.getOut() );
} }
} }
...@@ -34,6 +34,7 @@ pollActivated(false) ...@@ -34,6 +34,7 @@ pollActivated(false)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBExchange): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBExchange): objId=-1?!! Use --" + prefix + "-name" );
auto conf = uniset_conf();
mutex_start.setName(myname + "_mutex_start"); mutex_start.setName(myname + "_mutex_start");
string conf_name(conf->getArgParam("--" + prefix + "-confnode",myname)); string conf_name(conf->getArgParam("--" + prefix + "-confnode",myname));
...@@ -188,7 +189,7 @@ MBExchange::~MBExchange() ...@@ -188,7 +189,7 @@ MBExchange::~MBExchange()
void MBExchange::waitSMReady() void MBExchange::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int ready_timeout = conf->getArgInt("--" + prefix +"-sm-ready-timeout","15000"); int ready_timeout = uniset_conf()->getArgInt("--" + prefix +"-sm-ready-timeout","15000");
if( ready_timeout == 0 ) if( ready_timeout == 0 )
ready_timeout = 15000; ready_timeout = 15000;
else if( ready_timeout < 0 ) else if( ready_timeout < 0 )
...@@ -254,7 +255,7 @@ void MBExchange::sigterm( int signo ) ...@@ -254,7 +255,7 @@ void MBExchange::sigterm( int signo )
void MBExchange::readConfiguration() void MBExchange::readConfiguration()
{ {
// readconf_ok = false; // readconf_ok = false;
xmlNode* root = conf->getXMLSensorsSection(); xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root) if(!root)
{ {
ostringstream err; ostringstream err;
...@@ -527,6 +528,8 @@ void MBExchange::rtuQueryOptimization( RTUDeviceMap& m ) ...@@ -527,6 +528,8 @@ void MBExchange::rtuQueryOptimization( RTUDeviceMap& m )
//std::ostream& operator<<( std::ostream& os, MBExchange::PList& lst ) //std::ostream& operator<<( std::ostream& os, MBExchange::PList& lst )
std::ostream& MBExchange::print_plist( std::ostream& os, const MBExchange::PList& lst ) std::ostream& MBExchange::print_plist( std::ostream& os, const MBExchange::PList& lst )
{ {
auto conf = uniset_conf();
os << "[ "; os << "[ ";
for( auto it=lst.begin(); it!=lst.end(); ++it ) for( auto it=lst.begin(); it!=lst.end(); ++it )
os << "(" << it->si.id << ")" << conf->oind->getBaseName(conf->oind->getMapName(it->si.id)) << " "; os << "(" << it->si.id << ")" << conf->oind->getBaseName(conf->oind->getMapName(it->si.id)) << " ";
...@@ -1979,7 +1982,7 @@ bool MBExchange::initRegInfo( RegInfo* r, UniXML::iterator& it, MBExchange::RTU ...@@ -1979,7 +1982,7 @@ bool MBExchange::initRegInfo( RegInfo* r, UniXML::iterator& it, MBExchange::RTU
if( mbregFromID ) if( mbregFromID )
{ {
if( it.getProp("id").empty() ) if( it.getProp("id").empty() )
r->mbreg = conf->getSensorID(it.getProp("name")); r->mbreg = uniset_conf()->getSensorID(it.getProp("name"));
else else
r->mbreg = it.getIntProp("id"); r->mbreg = it.getIntProp("id");
} }
...@@ -2012,7 +2015,7 @@ bool MBExchange::initRegInfo( RegInfo* r, UniXML::iterator& it, MBExchange::RTU ...@@ -2012,7 +2015,7 @@ bool MBExchange::initRegInfo( RegInfo* r, UniXML::iterator& it, MBExchange::RTU
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool MBExchange::initRTUDevice( RTUDevice* d, UniXML::iterator& it ) bool MBExchange::initRTUDevice( RTUDevice* d, UniXML::iterator& it )
{ {
string mbtype(IOBase::initProp(it,"mbtype",prefix,false)); string mbtype(IOBase::initProp(it,"mbtype",prefix,false));
d->dtype = getDeviceType(mbtype); d->dtype = getDeviceType(mbtype);
if( d->dtype == dtUnknown ) if( d->dtype == dtUnknown )
...@@ -2370,6 +2373,7 @@ std::ostream& operator<<( std::ostream& os, const MBExchange::RSProperty& p ) ...@@ -2370,6 +2373,7 @@ std::ostream& operator<<( std::ostream& os, const MBExchange::RSProperty& p )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::initDeviceList() void MBExchange::initDeviceList()
{ {
auto conf = uniset_conf();
xmlNode* respNode = 0; xmlNode* respNode = 0;
const std::shared_ptr<UniXML> xml = conf->getConfXML(); const std::shared_ptr<UniXML> xml = conf->getConfXML();
if( xml ) if( xml )
...@@ -2410,7 +2414,7 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM ...@@ -2410,7 +2414,7 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM
string s(it.getProp("respondSensor")); string s(it.getProp("respondSensor"));
if( !s.empty() ) if( !s.empty() )
{ {
d->second->resp_id = conf->getSensorID(s); d->second->resp_id = uniset_conf()->getSensorID(s);
if( d->second->resp_id == DefaultObjectId ) if( d->second->resp_id == DefaultObjectId )
{ {
dinfo << myname << "(initDeviceInfo): not found ID for respondSensor=" << s << endl; dinfo << myname << "(initDeviceInfo): not found ID for respondSensor=" << s << endl;
...@@ -2418,6 +2422,8 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM ...@@ -2418,6 +2422,8 @@ bool MBExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXM
} }
} }
auto conf = uniset_conf();
string mod(it.getProp("modeSensor")); string mod(it.getProp("modeSensor"));
if( !mod.empty() ) if( !mod.empty() )
{ {
......
...@@ -20,6 +20,8 @@ pollThread(0) ...@@ -20,6 +20,8 @@ pollThread(0)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBTCPMaster): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBTCPMaster): objId=-1?!! Use --" + prefix + "-name" );
auto conf = uniset_conf();
// префикс для "свойств" - по умолчанию // префикс для "свойств" - по умолчанию
prop_prefix = "tcp_"; prop_prefix = "tcp_";
// если задано поле для "фильтрации" // если задано поле для "фильтрации"
...@@ -219,6 +221,7 @@ MBTCPMaster* MBTCPMaster::init_mbmaster( int argc, const char* const* argv, ...@@ -219,6 +221,7 @@ MBTCPMaster* MBTCPMaster::init_mbmaster( int argc, const char* const* argv,
UniSetTypes::ObjectId icID, SharedMemory* ic, UniSetTypes::ObjectId icID, SharedMemory* ic,
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","MBTCPMaster1"); string name = conf->getArgParam("--" + prefix + "-name","MBTCPMaster1");
if( name.empty() ) if( name.empty() )
{ {
......
...@@ -22,6 +22,8 @@ checkThread(0) ...@@ -22,6 +22,8 @@ checkThread(0)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBTCPMultiMaster): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBTCPMultiMaster): objId=-1?!! Use --" + prefix + "-name" );
auto conf = uniset_conf();
// префикс для "свойств" - по умолчанию // префикс для "свойств" - по умолчанию
prop_prefix = "tcp_"; prop_prefix = "tcp_";
// если задано поле для "фильтрации" // если задано поле для "фильтрации"
...@@ -365,6 +367,8 @@ MBTCPMultiMaster* MBTCPMultiMaster::init_mbmaster( int argc, const char* const* ...@@ -365,6 +367,8 @@ MBTCPMultiMaster* MBTCPMultiMaster::init_mbmaster( int argc, const char* const*
UniSetTypes::ObjectId icID, SharedMemory* ic, UniSetTypes::ObjectId icID, SharedMemory* ic,
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","MBTCPMultiMaster1"); string name = conf->getArgParam("--" + prefix + "-name","MBTCPMultiMaster1");
if( name.empty() ) if( name.empty() )
{ {
......
...@@ -20,6 +20,8 @@ rs_pre_clean(false) ...@@ -20,6 +20,8 @@ rs_pre_clean(false)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(RTUExchange): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(RTUExchange): objId=-1?!! Use --" + prefix + "-name" );
auto conf = uniset_conf();
// префикс для "свойств" - по умолчанию // префикс для "свойств" - по умолчанию
prop_prefix = ""; prop_prefix = "";
// если задано поле для "фильтрации" // если задано поле для "фильтрации"
...@@ -317,6 +319,8 @@ void RTUExchange::poll() ...@@ -317,6 +319,8 @@ void RTUExchange::poll()
RTUExchange* RTUExchange::init_rtuexchange( int argc, const char* const* argv, UniSetTypes::ObjectId icID, RTUExchange* RTUExchange::init_rtuexchange( int argc, const char* const* argv, UniSetTypes::ObjectId icID,
SharedMemory* ic, const std::string& prefix ) SharedMemory* ic, const std::string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","RTUExchange1"); string name = conf->getArgParam("--" + prefix + "-name","RTUExchange1");
if( name.empty() ) if( name.empty() )
{ {
......
...@@ -23,8 +23,7 @@ int main( int argc, const char** argv ) ...@@ -23,8 +23,7 @@ int main( int argc, const char** argv )
try try
{ {
string confile=UniSetTypes::getArgParam("--confile",argc, argv, "configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--mbtcp-logfile")); string logfilename(conf->getArgParam("--mbtcp-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -23,8 +23,7 @@ int main( int argc, const char** argv ) ...@@ -23,8 +23,7 @@ int main( int argc, const char** argv )
try try
{ {
string confile=UniSetTypes::getArgParam("--confile",argc, argv, "configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--mbtcp-logfile")); string logfilename(conf->getArgParam("--mbtcp-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -21,8 +21,7 @@ int main( int argc, char** argv ) ...@@ -21,8 +21,7 @@ int main( int argc, char** argv )
return 0; return 0;
} }
string confile=UniSetTypes::getArgParam("--confile", argc, argv, "configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--rs-logfile")); string logfilename(conf->getArgParam("--rs-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -32,6 +32,7 @@ prefix(prefix) ...@@ -32,6 +32,7 @@ prefix(prefix)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBSlave): objId=-1?!! Use --mbs-name" ); throw UniSetTypes::SystemError("(MBSlave): objId=-1?!! Use --mbs-name" );
auto conf = uniset_conf();
mutex_start.setName(myname + "_mutex_start"); mutex_start.setName(myname + "_mutex_start");
// xmlNode* cnode = conf->getNode(myname); // xmlNode* cnode = conf->getNode(myname);
...@@ -377,7 +378,7 @@ MBSlave::~MBSlave() ...@@ -377,7 +378,7 @@ MBSlave::~MBSlave()
void MBSlave::waitSMReady() void MBSlave::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int ready_timeout = conf->getArgInt("--" + prefix + "-sm-ready-timeout","15000"); int ready_timeout = uniset_conf()->getArgInt("--" + prefix + "-sm-ready-timeout","15000");
if( ready_timeout == 0 ) if( ready_timeout == 0 )
ready_timeout = 15000; ready_timeout = 15000;
else if( ready_timeout < 0 ) else if( ready_timeout < 0 )
...@@ -553,9 +554,9 @@ void MBSlave::execute_tcp() ...@@ -553,9 +554,9 @@ void MBSlave::execute_tcp()
IOBase::processingThreshold(&it.second,shm,force); IOBase::processingThreshold(&it.second,shm,force);
} }
catch( std::exception& ex) catch( std::exception& ex)
{ {
dcrit << myname << "(execute_tcp): " << ex.what() << endl; dcrit << myname << "(execute_tcp): " << ex.what() << endl;
} }
} }
dinfo << myname << "(execute_tcp): thread stopped.." << endl; dinfo << myname << "(execute_tcp): thread stopped.." << endl;
...@@ -774,7 +775,7 @@ void MBSlave::sigterm( int signo ) ...@@ -774,7 +775,7 @@ void MBSlave::sigterm( int signo )
void MBSlave::readConfiguration() void MBSlave::readConfiguration()
{ {
// readconf_ok = false; // readconf_ok = false;
xmlNode* root = conf->getXMLSensorsSection(); xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root) if(!root)
{ {
ostringstream err; ostringstream err;
...@@ -809,8 +810,8 @@ bool MBSlave::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it ...@@ -809,8 +810,8 @@ bool MBSlave::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it
bool MBSlave::initItem( UniXML::iterator& it ) bool MBSlave::initItem( UniXML::iterator& it )
{ {
IOProperty p; IOProperty p;
string prop_prefix(prefix+"_"); string prop_prefix(prefix+"_");
if( !IOBase::initItem( static_cast<IOBase*>(&p),it,shm,prop_prefix,false,&dlog,myname) ) if( !IOBase::initItem( static_cast<IOBase*>(&p),it,shm,prop_prefix,false,&dlog,myname) )
return false; return false;
...@@ -860,20 +861,20 @@ bool MBSlave::initItem( UniXML::iterator& it ) ...@@ -860,20 +861,20 @@ bool MBSlave::initItem( UniXML::iterator& it )
p.nbyte = IOBase::initIntProp(it,"nbyte",prop_prefix,false); p.nbyte = IOBase::initIntProp(it,"nbyte",prop_prefix,false);
if( p.nbyte <=0 ) if( p.nbyte <=0 )
{ {
dcrit << myname << "(initItem): Unknown nbyte='' for " dcrit << myname << "(initItem): Unknown nbyte='' for "
<< it.getProp("name") << it.getProp("name")
<< endl; << endl;
return false; return false;
}
else if( p.nbyte > 2 )
{
dcrit << myname << "(initItem): BAD nbyte='" << p.nbyte << "' for "
<< it.getProp("name")
<< ". Must be [1,2]."
<< endl;
return false;
} }
else if( p.nbyte > 2 ) }
{
dcrit << myname << "(initItem): BAD nbyte='" << p.nbyte << "' for "
<< it.getProp("name")
<< ". Must be [1,2]."
<< endl;
return false;
}
}
p.vtype = v; p.vtype = v;
p.wnum = 0; p.wnum = 0;
...@@ -936,6 +937,7 @@ void MBSlave::help_print( int argc, const char* const* argv ) ...@@ -936,6 +937,7 @@ void MBSlave::help_print( int argc, const char* const* argv )
MBSlave* MBSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID, SharedMemory* ic, MBSlave* MBSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID, SharedMemory* ic,
const string& prefix ) const string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","MBSlave1"); string name = conf->getArgParam("--" + prefix + "-name","MBSlave1");
if( name.empty() ) if( name.empty() )
{ {
...@@ -1029,7 +1031,7 @@ ModbusRTU::mbErrCode MBSlave::writeOutputSingleRegister( ModbusRTU::WriteSingleO ...@@ -1029,7 +1031,7 @@ ModbusRTU::mbErrCode MBSlave::writeOutputSingleRegister( ModbusRTU::WriteSingleO
ModbusRTU::mbErrCode MBSlave::much_real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat, ModbusRTU::mbErrCode MBSlave::much_real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat,
int count ) int count )
{ {
dinfo << myname << "(much_real_write): read mbID=" dinfo << myname << "(much_real_write): read mbID="
<< ModbusRTU::dat2str(reg) << " count=" << count << endl; << ModbusRTU::dat2str(reg) << " count=" << count << endl;
...@@ -1063,14 +1065,14 @@ ModbusRTU::mbErrCode MBSlave::much_real_write( ModbusRTU::ModbusData reg, Modbus ...@@ -1063,14 +1065,14 @@ ModbusRTU::mbErrCode MBSlave::much_real_write( ModbusRTU::ModbusData reg, Modbus
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData val ) ModbusRTU::mbErrCode MBSlave::real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData val )
{ {
ModbusRTU::ModbusData dat[1] = {val}; ModbusRTU::ModbusData dat[1] = {val};
int i=0; int i=0;
return real_write(reg,dat,i,1); return real_write(reg,dat,i,1);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat, int &i, int count ) ModbusRTU::mbErrCode MBSlave::real_write( ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat, int &i, int count )
{ {
ModbusRTU::ModbusData mbval = dat[i]; ModbusRTU::ModbusData mbval = dat[i];
dinfo << myname << "(write): save mbID=" dinfo << myname << "(write): save mbID="
<< ModbusRTU::dat2str(reg) << ModbusRTU::dat2str(reg)
...@@ -1086,7 +1088,7 @@ ModbusRTU::mbErrCode MBSlave::real_write_it( IOMap::iterator& it, ModbusRTU::Mod ...@@ -1086,7 +1088,7 @@ ModbusRTU::mbErrCode MBSlave::real_write_it( IOMap::iterator& it, ModbusRTU::Mod
if( it == iomap.end() ) if( it == iomap.end() )
return ModbusRTU::erBadDataAddress; return ModbusRTU::erBadDataAddress;
ModbusRTU::ModbusData mbval = dat[i++]; ModbusRTU::ModbusData mbval = dat[i++];
try try
{ {
IOProperty* p(&it->second); IOProperty* p(&it->second);
...@@ -1120,116 +1122,116 @@ ModbusRTU::mbErrCode MBSlave::real_write_it( IOMap::iterator& it, ModbusRTU::Mod ...@@ -1120,116 +1122,116 @@ ModbusRTU::mbErrCode MBSlave::real_write_it( IOMap::iterator& it, ModbusRTU::Mod
} }
else if( p->vtype == VTypes::vtI2 ) else if( p->vtype == VTypes::vtI2 )
{ {
if( (i + VTypes::I2::wsize() - 1) > count ) if( (i + VTypes::I2::wsize() - 1) > count )
{ {
i += VTypes::I2::wsize(); i += VTypes::I2::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::I2::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::I2::wsize()];
for( int k=0; k<VTypes::I2::wsize(); k++, i++ ) for( int k=0; k<VTypes::I2::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::I2 i2(d,VTypes::I2::wsize()); VTypes::I2 i2(d,VTypes::I2::wsize());
delete[] d; delete[] d;
IOBase::processingAsAI( p, (long)i2, shm, force ); IOBase::processingAsAI( p, (long)i2, shm, force );
} }
else if( p->vtype == VTypes::vtI2r ) else if( p->vtype == VTypes::vtI2r )
{ {
if( (i + VTypes::I2r::wsize() - 1) > count ) if( (i + VTypes::I2r::wsize() - 1) > count )
{ {
i += VTypes::I2r::wsize(); i += VTypes::I2r::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::I2r::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::I2r::wsize()];
for( int k=0; k<VTypes::I2r::wsize(); k++, i++ ) for( int k=0; k<VTypes::I2r::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::I2r i2r(d,VTypes::I2r::wsize()); VTypes::I2r i2r(d,VTypes::I2r::wsize());
delete[] d; delete[] d;
IOBase::processingAsAI( p, (long)i2r, shm, force ); IOBase::processingAsAI( p, (long)i2r, shm, force );
} }
else if( p->vtype == VTypes::vtU2 ) else if( p->vtype == VTypes::vtU2 )
{ {
if( (i + VTypes::U2::wsize() - 1) > count ) if( (i + VTypes::U2::wsize() - 1) > count )
{ {
i += VTypes::U2::wsize(); i += VTypes::U2::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::U2::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::U2::wsize()];
for( int k=0; k<VTypes::U2::wsize(); k++, i++ ) for( int k=0; k<VTypes::U2::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::U2 u2(d,VTypes::U2::wsize()); VTypes::U2 u2(d,VTypes::U2::wsize());
delete[] d; delete[] d;
IOBase::processingAsAI( p, (unsigned long)u2, shm, force ); IOBase::processingAsAI( p, (unsigned long)u2, shm, force );
} }
else if( p->vtype == VTypes::vtU2r ) else if( p->vtype == VTypes::vtU2r )
{ {
if( (i + VTypes::U2r::wsize() - 1) > count ) if( (i + VTypes::U2r::wsize() - 1) > count )
{ {
i += VTypes::U2r::wsize(); i += VTypes::U2r::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::U2r::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::U2r::wsize()];
for( int k=0; k<VTypes::U2r::wsize(); k++, i++ ) for( int k=0; k<VTypes::U2r::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::U2r u2r(d,VTypes::U2r::wsize()); VTypes::U2r u2r(d,VTypes::U2r::wsize());
delete[] d; delete[] d;
IOBase::processingAsAI( p, (unsigned long)u2r, shm, force ); IOBase::processingAsAI( p, (unsigned long)u2r, shm, force );
} }
else if( p->vtype == VTypes::vtF2 ) else if( p->vtype == VTypes::vtF2 )
{ {
if( (i + VTypes::F2::wsize() - 1) > count ) if( (i + VTypes::F2::wsize() - 1) > count )
{ {
i += VTypes::F2::wsize(); i += VTypes::F2::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F2::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F2::wsize()];
for( int k=0; k<VTypes::F2::wsize(); k++, i++ ) for( int k=0; k<VTypes::F2::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::F2 f2(d,VTypes::F2::wsize()); VTypes::F2 f2(d,VTypes::F2::wsize());
delete[] d; delete[] d;
IOBase::processingFasAI( p, (float)f2, shm, force ); IOBase::processingFasAI( p, (float)f2, shm, force );
} }
else if( p->vtype == VTypes::vtF2r ) else if( p->vtype == VTypes::vtF2r )
{ {
if( (i + VTypes::F2r::wsize() - 1) > count ) if( (i + VTypes::F2r::wsize() - 1) > count )
{ {
i += VTypes::F2r::wsize(); i += VTypes::F2r::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F2r::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F2r::wsize()];
for( int k=0; k<VTypes::F2r::wsize(); k++, i++ ) for( int k=0; k<VTypes::F2r::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::F2r f2r(d,VTypes::F2r::wsize()); VTypes::F2r f2r(d,VTypes::F2r::wsize());
delete[] d; delete[] d;
IOBase::processingFasAI( p, (float)f2r, shm, force ); IOBase::processingFasAI( p, (float)f2r, shm, force );
} }
else if( p->vtype == VTypes::vtF4 ) else if( p->vtype == VTypes::vtF4 )
{ {
if( (i + VTypes::F4::wsize() - 1) > count ) if( (i + VTypes::F4::wsize() - 1) > count )
{ {
i += VTypes::F4::wsize(); i += VTypes::F4::wsize();
return ModbusRTU::erInvalidFormat; return ModbusRTU::erInvalidFormat;
} }
ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F4::wsize()]; ModbusRTU::ModbusData* d = new ModbusRTU::ModbusData[VTypes::F4::wsize()];
for( int k=0; k<VTypes::F4::wsize(); k++, i++ ) for( int k=0; k<VTypes::F4::wsize(); k++, i++ )
d[k] = dat[i-1]; d[k] = dat[i-1];
VTypes::F4 f4(d,VTypes::F4::wsize()); VTypes::F4 f4(d,VTypes::F4::wsize());
delete[] d; delete[] d;
IOBase::processingFasAI( p, (float)f4, shm, force ); IOBase::processingFasAI( p, (float)f4, shm, force );
} }
else if( p->vtype == VTypes::vtByte ) else if( p->vtype == VTypes::vtByte )
{ {
VTypes::Byte b(mbval); VTypes::Byte b(mbval);
......
...@@ -24,20 +24,20 @@ ...@@ -24,20 +24,20 @@
- \ref sec_MBSlave_Comm - \ref sec_MBSlave_Comm
- \ref sec_MBSlave_Conf - \ref sec_MBSlave_Conf
- \ref sec_MBSlave_ConfList - \ref sec_MBSlave_ConfList
- \ref sec_MBSlave_FileTransfer - \ref sec_MBSlave_FileTransfer
- \ref sec_MBSlave_MEIRDI - \ref sec_MBSlave_MEIRDI
- \ref sec_MBSlave_DIAG - \ref sec_MBSlave_DIAG
\section sec_MBSlave_Comm Общее описание Modbus slave \section sec_MBSlave_Comm Общее описание Modbus slave
Класс реализует базовые функции для протокола Modbus в slave режиме. Реализацию Modbus RTU - см. RTUExchange. Класс реализует базовые функции для протокола Modbus в slave режиме. Реализацию Modbus RTU - см. RTUExchange.
Реализацию Modbus slave (TCP) - см. MBSlave. Список регистров с которыми работает процесс задаётся в конфигурационном файле Реализацию Modbus slave (TCP) - см. MBSlave. Список регистров с которыми работает процесс задаётся в конфигурационном файле
в секции \b <sensors>. см. \ref sec_MBSlave_Conf в секции \b <sensors>. см. \ref sec_MBSlave_Conf
В данной версии поддерживаются следующие функции: В данной версии поддерживаются следующие функции:
- 0x02 - read input status - 0x02 - read input status
- 0x03 - read register outputs or memories or read word outputs or memories - 0x03 - read register outputs or memories or read word outputs or memories
- 0x04 - read input registers or memories or read word outputs or memories - 0x04 - read input registers or memories or read word outputs or memories
- 0x05 - forces a single coil to either ON or OFF - 0x05 - forces a single coil to either ON or OFF
- 0x06 - write register outputs or memories - 0x06 - write register outputs or memories
- 0x08 - Diagnostics (Serial Line only) - 0x08 - Diagnostics (Serial Line only)
- 0x0F - force multiple coils - 0x0F - force multiple coils
...@@ -58,47 +58,47 @@ ...@@ -58,47 +58,47 @@
в которой указываются настроечные параметры по умолчанию. в которой указываются настроечные параметры по умолчанию.
Пример: Пример:
\code \code
<MBSlave1 name="MBSlave1" addr="0x31" <MBSlave1 name="MBSlave1" addr="0x31"
afterSendPause="0" afterSendPause="0"
reg_from_id="0" reg_from_id="0"
replyTimeout="60" replyTimeout="60"
askcount_id="" askcount_id=""
respond_invert="" respond_invert=""
respond_id="" respond_id=""
timeout="" timeout=""
heartbeat_id="" heartbeat_id=""
initPause="" initPause=""
force="" force=""
... ...
\endcode \endcode
- \b addr - адрес данного устройства - \b addr - адрес данного устройства
- \b afterSendPause - принудительная пауза после посылки ответа - \b afterSendPause - принудительная пауза после посылки ответа
- \b reg_from_id - номер регистра брать из ID датчика - \b reg_from_id - номер регистра брать из ID датчика
- \b replyTimeout - таймаут на формирование ответа. Если ответ на запрос будет сформирован за большее время, он не будет отослан. - \b replyTimeout - таймаут на формирование ответа. Если ответ на запрос будет сформирован за большее время, он не будет отослан.
- \b askcount_id - идентификатор датчика для счётчика запросов - \b askcount_id - идентификатор датчика для счётчика запросов
- \b respond_id - идентификатор датчика наличия связи. Выставляется в "1" когда связь есть. - \b respond_id - идентификатор датчика наличия связи. Выставляется в "1" когда связь есть.
- \b respond_invert - инвертировать логику выставления датчика связи (т.е. выставлять "1" - когда нет связи). - \b respond_invert - инвертировать логику выставления датчика связи (т.е. выставлять "1" - когда нет связи).
- \b heartbeat_id - идентификтор датчика "сердцебиения". См. \ref sec_SM_HeartBeat - \b heartbeat_id - идентификтор датчика "сердцебиения". См. \ref sec_SM_HeartBeat
- \b initPause - пауза перед началом работы, после активации. По умолчанию 3000 мсек. - \b initPause - пауза перед началом работы, после активации. По умолчанию 3000 мсек.
- \b force - [1,0] перезаписывать ли значения в SharedMemory каждый раз (а не по изменению). - \b force - [1,0] перезаписывать ли значения в SharedMemory каждый раз (а не по изменению).
- \b timeout msec - таймаут, для определения отсутствия связи - \b timeout msec - таймаут, для определения отсутствия связи
Специфичные для RTU настройки: Специфичные для RTU настройки:
\code \code
device="/dev/ttyS0" speed="9600" use485F="1" transmitCtl="0"> device="/dev/ttyS0" speed="9600" use485F="1" transmitCtl="0">
\endcode \endcode
- \b device - устройство (порт) - \b device - устройство (порт)
- \b speed - скорость обмена - \b speed - скорость обмена
- \b use485F - [0,1] - использовать специальный класс для обмена по RS485 на контрллерах фаствел (убирает echo программным путём). - \b use485F - [0,1] - использовать специальный класс для обмена по RS485 на контрллерах фаствел (убирает echo программным путём).
- \b transmitCtl - [0,1] - управлять ли приёмопередатчиков (ну программном уровне). Обычно это на аппаратном или драйвером. - \b transmitCtl - [0,1] - управлять ли приёмопередатчиков (ну программном уровне). Обычно это на аппаратном или драйвером.
Специфичные для TCP настройки: Специфичные для TCP настройки:
\code \code
iaddr="localhost" iport="502" iaddr="localhost" iport="502"
\endcode \endcode
- \b iaddr - ip адрес данного устройства - \b iaddr - ip адрес данного устройства
- \b iport - tcp порт. - \b iport - tcp порт.
\par Параметры запуска \par Параметры запуска
...@@ -108,12 +108,12 @@ ...@@ -108,12 +108,12 @@
Далее приведены основные параметры: Далее приведены основные параметры:
\b --xxx-name ID - идентификатор процесса. \b --xxx-name ID - идентификатор процесса.
\b --xxx-my-addr addr - slave-адрес для данного устройства. \b --xxx-my-addr addr - slave-адрес для данного устройства.
\b --xxx-timeout или \b timeout msec - таймаут на определение отсутсвия связи. \b --xxx-timeout или \b timeout msec - таймаут на определение отсутсвия связи.
\b --xxx-reply-timeout msec - таймаут на формирование ответа. \b --xxx-reply-timeout msec - таймаут на формирование ответа.
\b --xxx-initPause или \b initPause msec - пауза перед началом работы, после активации. По умолчанию 50 мсек. \b --xxx-initPause или \b initPause msec - пауза перед началом работы, после активации. По умолчанию 50 мсек.
...@@ -131,7 +131,7 @@ ...@@ -131,7 +131,7 @@
\b --xxx-activate-timeout msec . По умолчанию 2000. - время ожидания готовности SharedMemory к работе. \b --xxx-activate-timeout msec . По умолчанию 2000. - время ожидания готовности SharedMemory к работе.
\b --xxx-allow-setdatetime 0,1 - Включить функцию 0x50. Выставление даты и времени. \b --xxx-allow-setdatetime 0,1 - Включить функцию 0x50. Выставление даты и времени.
\par Настройки протокола RTU: \par Настройки протокола RTU:
...@@ -184,10 +184,10 @@ ...@@ -184,10 +184,10 @@
\warning Регистр должен быть уникальным. И может повторятся только если указан параметр \a nbyte. \warning Регистр должен быть уникальным. И может повторятся только если указан параметр \a nbyte.
\section sec_MBSlave_FileTransfer Настройка передачи файлов в ModbusSlave (0x66) \section sec_MBSlave_FileTransfer Настройка передачи файлов в ModbusSlave (0x66)
Данная реализация позволяет передавать по протоколу Modbus заранее заданные файлы. Данная реализация позволяет передавать по протоколу Modbus заранее заданные файлы.
Настройка происходвится в конфигурационном файле. Настройка происходвится в конфигурационном файле.
\code \code
<filelist> <filelist>
<!-- Список файлов разрешённых для передачи по modbus <!-- Список файлов разрешённых для передачи по modbus
directory - каталог где лежит файл. Можно не задавать directory - каталог где лежит файл. Можно не задавать
...@@ -200,54 +200,54 @@ ...@@ -200,54 +200,54 @@
<item directory="/tmp/" id="3" name="configure.xml.gz"/> <item directory="/tmp/" id="3" name="configure.xml.gz"/>
<item directory="ConfDir" id="4" name="SERIAL"/> <item directory="ConfDir" id="4" name="SERIAL"/>
</filelist> </filelist>
\endcode \endcode
- \b id - задаёт идентификтор файла (собственно он и будет запрашиваться. - \b id - задаёт идентификтор файла (собственно он и будет запрашиваться.
- \b name - название файла - \b name - название файла
- \b directory - каталог где храниться файл. - \b directory - каталог где храниться файл.
\section sec_MBSlave_MEIRDI Поддержка "MODBUS Encapsulated Interface" (0x2B)[0x0E] \section sec_MBSlave_MEIRDI Поддержка "MODBUS Encapsulated Interface" (0x2B)[0x0E]
\code \code
<MEI> <MEI>
<!-- ВНИМАНИЕ: должен заполняться в соответсвии со стандартом. ObjectID и DeviceID не случайны.. --> <!-- ВНИМАНИЕ: должен заполняться в соответсвии со стандартом. ObjectID и DeviceID не случайны.. -->
<device id="0x01"> <device id="0x01">
<object id="0" comm="VendorName"> <object id="0" comm="VendorName">
<string value="etersoft"/> <string value="etersoft"/>
</object> </object>
<object id="1" comm="ProductCode"> <object id="1" comm="ProductCode">
<string value="uniset"/> <string value="uniset"/>
</object> </object>
<object id="2" comm="MajorMinorRevision"> <object id="2" comm="MajorMinorRevision">
<string value="1.6"/> <string value="1.6"/>
</object> </object>
</device> </device>
<device id="0x02"> <device id="0x02">
<object id="3" comm="VendorURL"> <object id="3" comm="VendorURL">
<string value="http://www.etersoft.ru"/> <string value="http://www.etersoft.ru"/>
</object> </object>
<object id="4" comm="ProductName"> <object id="4" comm="ProductName">
<string value="uniset"/> <string value="uniset"/>
</object> </object>
<object id="5" comm="ModelName"> <object id="5" comm="ModelName">
<string value="uniset:MBSlave"/> <string value="uniset:MBSlave"/>
</object> </object>
<object id="6" comm="UserApplicationName"> <object id="6" comm="UserApplicationName">
<string value="MBSlave1"/> <string value="MBSlave1"/>
</object> </object>
</device> </device>
<device id="0x03"> <device id="0x03">
<object id="128" comm="private objects"> <object id="128" comm="private objects">
<string id="129" value="etersoft"/> <string id="129" value="etersoft"/>
<string id="130" value="uniset"/> <string id="130" value="uniset"/>
<string id="131" value="1.6"/> <string id="131" value="1.6"/>
<string id="132" value="http://www.etersoft.ru"/> <string id="132" value="http://www.etersoft.ru"/>
<string id="133" value="MBSlave1"/> <string id="133" value="MBSlave1"/>
</object> </object>
</device> </device>
</MEI> </MEI>
\endcode \endcode
\section sec_MBSlave_DIAG Диагностические функции (0x08) \section sec_MBSlave_DIAG Диагностические функции (0x08)
*/ */
......
...@@ -15,6 +15,8 @@ MBTCPMultiSlave::MBTCPMultiSlave( UniSetTypes::ObjectId objId, UniSetTypes::Obje ...@@ -15,6 +15,8 @@ MBTCPMultiSlave::MBTCPMultiSlave( UniSetTypes::ObjectId objId, UniSetTypes::Obje
MBSlave(objId,shmId,ic,prefix), MBSlave(objId,shmId,ic,prefix),
sesscount_id(DefaultObjectId) sesscount_id(DefaultObjectId)
{ {
auto conf = uniset_conf();
cnode = conf->getNode(myname); cnode = conf->getNode(myname);
if( cnode == NULL ) if( cnode == NULL )
throw UniSetTypes::SystemError("(MBSlave): Not found conf-node for " + myname ); throw UniSetTypes::SystemError("(MBSlave): Not found conf-node for " + myname );
...@@ -111,6 +113,7 @@ void MBTCPMultiSlave::help_print( int argc, const char* const* argv ) ...@@ -111,6 +113,7 @@ void MBTCPMultiSlave::help_print( int argc, const char* const* argv )
MBTCPMultiSlave* MBTCPMultiSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID, SharedMemory* ic, MBTCPMultiSlave* MBTCPMultiSlave::init_mbslave( int argc, const char* const* argv, UniSetTypes::ObjectId icID, SharedMemory* ic,
const string& prefix ) const string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","MBSlave1"); string name = conf->getArgParam("--" + prefix + "-name","MBSlave1");
if( name.empty() ) if( name.empty() )
{ {
......
...@@ -36,4 +36,4 @@ pkgconfig_DATA = libUniSet2MBSlave.pc ...@@ -36,4 +36,4 @@ pkgconfig_DATA = libUniSet2MBSlave.pc
all-local: all-local:
ln -sf ../ModbusSlave/$(devel_include_HEADERS) ../include ln -sf ../ModbusSlave/$(devel_include_HEADERS) ../include
#SUBDIRS=tests SUBDIRS=tests
...@@ -28,8 +28,7 @@ int main(int argc, const char **argv) ...@@ -28,8 +28,7 @@ int main(int argc, const char **argv)
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv,confile);
string logfilename(conf->getArgParam("--mbs-logfile")); string logfilename(conf->getArgParam("--mbs-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -28,8 +28,7 @@ int main(int argc, const char **argv) ...@@ -28,8 +28,7 @@ int main(int argc, const char **argv)
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv,confile);
string logfilename(conf->getArgParam("--mbs-logfile")); string logfilename(conf->getArgParam("--mbs-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -11,11 +11,11 @@ tests_with_sm_CPPFLAGS = -I$(top_builddir)/include -I$(top_builddir)/extensions ...@@ -11,11 +11,11 @@ tests_with_sm_CPPFLAGS = -I$(top_builddir)/include -I$(top_builddir)/extensions
-I$(top_builddir)/extensions/ModbusSlave \ -I$(top_builddir)/extensions/ModbusSlave \
-I$(top_builddir)/extensions/SharedMemory $(SIGC_CFLAGS) $(COMCPP_CFLAGS) -I$(top_builddir)/extensions/SharedMemory $(SIGC_CFLAGS) $(COMCPP_CFLAGS)
$(top_builddir)/extensions/lib/libUniSet2Extensions.la: #$(top_builddir)/extensions/lib/libUniSet2Extensions.la:
cd $(top_builddir)/extensions/lib/ && make # cd $(top_builddir)/extensions/lib/ && make
$(top_builddir)/extensions/ModbusSlave/libUniSet2MBSlave.la: #$(top_builddir)/extensions/ModbusSlave/libUniSet2MBSlave.la:
cd $(top_builddir)/extensions/ModbusSlave/ && make # cd $(top_builddir)/extensions/ModbusSlave/ && make
include $(top_builddir)/testsuite/testsuite-common.mk include $(top_builddir)/testsuite/testsuite-common.mk
......
...@@ -18,923 +18,928 @@ static UInterface* ui = nullptr; ...@@ -18,923 +18,928 @@ static UInterface* ui = nullptr;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void InitTest() void InitTest()
{ {
CHECK( conf!=0 ); auto conf = uniset_conf();
CHECK( conf!=nullptr );
if( ui == nullptr )
{ if( ui == nullptr )
ui = new UInterface(); {
// UI понадобиться для проверки записанных в SM значений. ui = new UInterface();
CHECK( ui->getObjectIndex() != nullptr ); // UI понадобиться для проверки записанных в SM значений.
CHECK( ui->getConf() == UniSetTypes::conf ); CHECK( ui->getObjectIndex() != nullptr );
CHECK( ui->waitReady(slaveID,5000) ); CHECK( ui->getConf() == conf );
} CHECK( ui->waitReady(slaveID,5000) );
}
if( mb == nullptr )
{ if( mb == nullptr )
mb = new ModbusTCPMaster(); {
ost::InetAddress ia(addr.c_str()); mb = new ModbusTCPMaster();
mb->setTimeout(2000); ost::InetAddress ia(addr.c_str());
REQUIRE_NOTHROW( mb->connect(ia,port) ); mb->setTimeout(2000);
} REQUIRE_NOTHROW( mb->connect(ia,port) );
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#if 0 #if 0
TEST_CASE("(0x01): read coil status","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x01): read coil status","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
// read 1 bit // read 1 bit
{ {
ModbusRTU::ReadCoilRetMessage ret(slaveaddr); ModbusRTU::ReadCoilRetMessage ret(slaveaddr);
REQUIRE_NOTHROW( ret = mb->read01(slaveaddr,1000,1) ); REQUIRE_NOTHROW( ret = mb->read01(slaveaddr,1000,1) );
ModbusRTU::DataBits b(ret.data[0]); ModbusRTU::DataBits b(ret.data[0]);
REQUIRE( b[0] == 1 ); REQUIRE( b[0] == 1 );
} }
// read 3 bit // read 3 bit
{ {
ModbusRTU::ReadCoilRetMessage ret(slaveaddr); ModbusRTU::ReadCoilRetMessage ret(slaveaddr);
REQUIRE_NOTHROW( ret = mb->read01(slaveaddr,1000,3) ); REQUIRE_NOTHROW( ret = mb->read01(slaveaddr,1000,3) );
ModbusRTU::DataBits b(ret.data[0]); ModbusRTU::DataBits b(ret.data[0]);
REQUIRE( b[0] == 1 ); REQUIRE( b[0] == 1 );
REQUIRE( b[1] == 1 ); REQUIRE( b[1] == 1 );
REQUIRE( b[2] == 0 ); REQUIRE( b[2] == 0 );
} }
} }
TEST_CASE("(0x02): read input status","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x02): read input status","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
SECTION("read 1 bit") SECTION("read 1 bit")
{ {
ModbusRTU::ReadInputStatusRetMessage ret(slaveaddr); ModbusRTU::ReadInputStatusRetMessage ret(slaveaddr);
REQUIRE_NOTHROW( ret = mb->read02(slaveaddr,1000,1) ); REQUIRE_NOTHROW( ret = mb->read02(slaveaddr,1000,1) );
ModbusRTU::DataBits b(ret.data[0]); ModbusRTU::DataBits b(ret.data[0]);
REQUIRE( b[0] == 1 ); REQUIRE( b[0] == 1 );
} }
SECTION("read 3 bit") SECTION("read 3 bit")
{ {
ModbusRTU::ReadInputStatusRetMessage ret(slaveaddr); ModbusRTU::ReadInputStatusRetMessage ret(slaveaddr);
REQUIRE_NOTHROW( ret = mb->read02(slaveaddr,1000,3) ); REQUIRE_NOTHROW( ret = mb->read02(slaveaddr,1000,3) );
ModbusRTU::DataBits b(ret.data[0]); ModbusRTU::DataBits b(ret.data[0]);
REQUIRE( b[0] == 1 ); REQUIRE( b[0] == 1 );
REQUIRE( b[1] == 1 ); REQUIRE( b[1] == 1 );
REQUIRE( b[2] == 0 ); REQUIRE( b[2] == 0 );
} }
} }
#endif #endif
TEST_CASE("Function (0x03): 'read register outputs or memories or read word outputs or memories'","[modbus][mbslave][mbtcpslave]") TEST_CASE("Function (0x03): 'read register outputs or memories or read word outputs or memories'","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
ModbusRTU::ModbusData tREG=10; ModbusRTU::ModbusData tREG=10;
SECTION("Test: read one reg..") SECTION("Test: read one reg..")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,1); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,1);
REQUIRE( ret.data[0] == 10 ); REQUIRE( ret.data[0] == 10 );
} }
SECTION("Test: read many registers..") SECTION("Test: read many registers..")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,3); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,3);
REQUIRE( ret.data[0] == 10 ); REQUIRE( ret.data[0] == 10 );
REQUIRE( ret.data[1] == 11 ); REQUIRE( ret.data[1] == 11 );
REQUIRE( (signed short)(ret.data[2]) == -10 ); REQUIRE( (signed short)(ret.data[2]) == -10 );
} }
SECTION("Test: read MAXDATA count..") SECTION("Test: read MAXDATA count..")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,ModbusRTU::MAXDATALEN); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,ModbusRTU::MAXDATALEN);
REQUIRE( ret.count == ModbusRTU::MAXDATALEN ); REQUIRE( ret.count == ModbusRTU::MAXDATALEN );
} }
SECTION("Test: read TOO many registers") SECTION("Test: read TOO many registers")
{ {
try try
{ {
mb->read03(slaveaddr,-23,1200); mb->read03(slaveaddr,-23,1200);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
SECTION("Test: read unknown registers") SECTION("Test: read unknown registers")
{ {
try try
{ {
mb->read03(slaveaddr,-23,1); mb->read03(slaveaddr,-23,1);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
SECTION("Test: incorrect number") SECTION("Test: incorrect number")
{ {
try try
{ {
mb->read03(slaveaddr,tREG,-3); mb->read03(slaveaddr,tREG,-3);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
SECTION("Test: zero number") SECTION("Test: zero number")
{ {
try try
{ {
mb->read03(slaveaddr,tREG,0); mb->read03(slaveaddr,tREG,0);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
} }
TEST_CASE("Function (0x04): 'read input registers or memories or read word outputs or memories'","[modbus][mbslave][mbtcpslave]") TEST_CASE("Function (0x04): 'read input registers or memories or read word outputs or memories'","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
ModbusRTU::ModbusData tREG=10; ModbusRTU::ModbusData tREG=10;
SECTION("Test: read one reg..") SECTION("Test: read one reg..")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1);
REQUIRE( ret.data[0] == 10 ); REQUIRE( ret.data[0] == 10 );
} }
SECTION("Test: read one reg..") SECTION("Test: read one reg..")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1);
REQUIRE( ret.data[0] == 10 ); REQUIRE( ret.data[0] == 10 );
} }
SECTION("Test: read many registers..") SECTION("Test: read many registers..")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,4); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,4);
REQUIRE( ret.data[0] == 10 ); REQUIRE( ret.data[0] == 10 );
REQUIRE( ret.data[1] == 11 ); REQUIRE( ret.data[1] == 11 );
REQUIRE( (signed short)(ret.data[2]) == -10 ); REQUIRE( (signed short)(ret.data[2]) == -10 );
REQUIRE( (signed short)(ret.data[3]) == -10000 ); REQUIRE( (signed short)(ret.data[3]) == -10000 );
} }
SECTION("Test: read MAXDATA count..") SECTION("Test: read MAXDATA count..")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,ModbusRTU::MAXDATALEN); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,ModbusRTU::MAXDATALEN);
REQUIRE( ret.count == ModbusRTU::MAXDATALEN ); REQUIRE( ret.count == ModbusRTU::MAXDATALEN );
} }
SECTION("Test: read TOO many registers") SECTION("Test: read TOO many registers")
{ {
try try
{ {
mb->read04(slaveaddr,-23,1200); mb->read04(slaveaddr,-23,1200);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
SECTION("Test: read unknown registers") SECTION("Test: read unknown registers")
{ {
try try
{ {
mb->read04(slaveaddr,-23,1); mb->read04(slaveaddr,-23,1);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
SECTION("Test: incorrect number") SECTION("Test: incorrect number")
{ {
try try
{ {
mb->read04(slaveaddr,tREG,-3); mb->read04(slaveaddr,tREG,-3);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
SECTION("Test: zero number") SECTION("Test: zero number")
{ {
try try
{ {
mb->read04(slaveaddr,tREG,0); mb->read04(slaveaddr,tREG,0);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erTimeOut ); REQUIRE( ex.err == ModbusRTU::erTimeOut );
} }
} }
} }
TEST_CASE("(0x05): forces a single coil to either ON or OFF","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x05): forces a single coil to either ON or OFF","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
ObjectId tID = 1007; ObjectId tID = 1007;
ModbusRTU::ModbusData tREG=14; ModbusRTU::ModbusData tREG=14;
SECTION("Test: ON") SECTION("Test: ON")
{ {
ModbusRTU::ForceSingleCoilRetMessage ret = mb->write05(slaveaddr,tREG,true); ModbusRTU::ForceSingleCoilRetMessage ret = mb->write05(slaveaddr,tREG,true);
CHECK( ret.start == tREG ); CHECK( ret.start == tREG );
CHECK( ret.cmd() == true ); CHECK( ret.cmd() == true );
CHECK( ui->getValue(tID) == 1 ); CHECK( ui->getValue(tID) == 1 );
} }
SECTION("Test: OFF") SECTION("Test: OFF")
{ {
ModbusRTU::ForceSingleCoilRetMessage ret = mb->write05(slaveaddr,tREG,false); ModbusRTU::ForceSingleCoilRetMessage ret = mb->write05(slaveaddr,tREG,false);
CHECK( ret.start == tREG ); CHECK( ret.start == tREG );
CHECK( ret.cmd() == false ); CHECK( ret.cmd() == false );
CHECK( ui->getValue(tID) == 0 ); CHECK( ui->getValue(tID) == 0 );
} }
} }
TEST_CASE("(0x06): write register outputs or memories","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x06): write register outputs or memories","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
ObjectId tID = 1008; ObjectId tID = 1008;
ModbusRTU::ModbusData tREG=15; ModbusRTU::ModbusData tREG=15;
SECTION("Test: write register") SECTION("Test: write register")
{ {
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,10); ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,10);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.data == 10 ); REQUIRE( ret.data == 10 );
REQUIRE( ui->getValue(tID) == 10 ); REQUIRE( ui->getValue(tID) == 10 );
} }
SECTION("Test: write negative value") SECTION("Test: write negative value")
{ {
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,-10); ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,-10);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( (signed short)ret.data == -10 ); REQUIRE( (signed short)ret.data == -10 );
REQUIRE( (signed short)ui->getValue(tID) == -10 ); REQUIRE( (signed short)ui->getValue(tID) == -10 );
} }
SECTION("Test: write zero value") SECTION("Test: write zero value")
{ {
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,0); ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,tREG,0);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.data == 0 ); REQUIRE( ret.data == 0 );
REQUIRE( ui->getValue(tID) == 0 ); REQUIRE( ui->getValue(tID) == 0 );
} }
SECTION("Test: write OVERFLOW VALUE") SECTION("Test: write OVERFLOW VALUE")
{ {
WARN("FIXME: what to do in this situation?!"); WARN("FIXME: what to do in this situation?!");
#if 0 #if 0
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,15,100000); ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,15,100000);
REQUIRE( ret.start == 15 ); REQUIRE( ret.start == 15 );
REQUIRE( ret.data == 34464 ); REQUIRE( ret.data == 34464 );
REQUIRE( ui->getValue(1008) == 34464 ); REQUIRE( ui->getValue(1008) == 34464 );
#endif #endif
} }
SECTION("Test: write unknown register") SECTION("Test: write unknown register")
{ {
try try
{ {
mb->write06(slaveaddr,-23,10); mb->write06(slaveaddr,-23,10);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
} }
#if 0 #if 0
SECTION("(0x08): Diagnostics (Serial Line only)") SECTION("(0x08): Diagnostics (Serial Line only)")
{ {
} }
#endif #endif
#if 0 #if 0
\TODO Переписать реализацию MBSlave... ввести понятие nbit. \TODO Переписать реализацию MBSlave... ввести понятие nbit.
TEST_CASE("(0x0F): force multiple coils","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x0F): force multiple coils","[modbus][mbslave][mbtcpslave]")
{ {
WARN("FIXME: 'force coil status'. Use 'nbit'?"): WARN("FIXME: 'force coil status'. Use 'nbit'?"):
InitTest(); InitTest();
ObjectId tID = 1009; ObjectId tID = 1009;
ModbusRTU::ModbusData tREG=16; ModbusRTU::ModbusData tREG=16;
SECTION("Test: write 2 bit to 1") SECTION("Test: write 2 bit to 1")
{ {
ModbusRTU::ForceCoilsMessage msg(slaveaddr,tREG); ModbusRTU::ForceCoilsMessage msg(slaveaddr,tREG);
ModbusRTU::DataBits b(3); ModbusRTU::DataBits b(3);
msg.addData(b); msg.addData(b);
ModbusRTU::ForceCoilsRetMessage ret = mb->write0F(msg); ModbusRTU::ForceCoilsRetMessage ret = mb->write0F(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 8 ); REQUIRE( ret.quant == 8 );
REQUIRE( ui->getValue(tID) == 1 ); REQUIRE( ui->getValue(tID) == 1 );
REQUIRE( ui->getValue(tID+1) == 1 ); REQUIRE( ui->getValue(tID+1) == 1 );
} }
SECTION("Test: write 2 bit to 0") SECTION("Test: write 2 bit to 0")
{ {
ModbusRTU::ForceCoilsMessage msg(slaveaddr,tREG); ModbusRTU::ForceCoilsMessage msg(slaveaddr,tREG);
ModbusRTU::DataBits b(0); ModbusRTU::DataBits b(0);
msg.addData(b); msg.addData(b);
ModbusRTU::ForceCoilsRetMessage ret = mb->write0F(msg); ModbusRTU::ForceCoilsRetMessage ret = mb->write0F(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 8 ); REQUIRE( ret.quant == 8 );
REQUIRE( ui->getValue(tID) == 0 ); REQUIRE( ui->getValue(tID) == 0 );
REQUIRE( ui->getValue(tID+1) == 0 ); REQUIRE( ui->getValue(tID+1) == 0 );
} }
} }
#endif #endif
TEST_CASE("(0x10): write register outputs or memories","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x10): write register outputs or memories","[modbus][mbslave][mbtcpslave]")
{ {
InitTest(); InitTest();
InitTest(); InitTest();
ObjectId tID = 1025; ObjectId tID = 1025;
ModbusRTU::ModbusData tREG=18; ModbusRTU::ModbusData tREG=18;
SECTION("Test: write one register") SECTION("Test: write one register")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(10); msg.addData(10);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 1 ); REQUIRE( ret.quant == 1 );
REQUIRE( ui->getValue(tID) == 10 ); REQUIRE( ui->getValue(tID) == 10 );
} }
SECTION("Test: write 3 register") SECTION("Test: write 3 register")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(10); msg.addData(10);
msg.addData(11); msg.addData(11);
msg.addData(12); msg.addData(12);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 3 ); REQUIRE( ret.quant == 3 );
REQUIRE( ui->getValue(tID) == 10 ); REQUIRE( ui->getValue(tID) == 10 );
REQUIRE( ui->getValue(tID+1) == 11 ); REQUIRE( ui->getValue(tID+1) == 11 );
REQUIRE( ui->getValue(tID+2) == 1 ); // 1 - т.к. это "DI" REQUIRE( ui->getValue(tID+2) == 1 ); // 1 - т.к. это "DI"
} }
SECTION("Test: write negative value") SECTION("Test: write negative value")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(-10); msg.addData(-10);
msg.addData(-100); msg.addData(-100);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 2 ); REQUIRE( ret.quant == 2 );
REQUIRE( (signed short)ui->getValue(tID) == -10 ); REQUIRE( (signed short)ui->getValue(tID) == -10 );
REQUIRE( (signed short)ui->getValue(tID+1) == -100 ); REQUIRE( (signed short)ui->getValue(tID+1) == -100 );
} }
SECTION("Test: write zero registers") SECTION("Test: write zero registers")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(0); msg.addData(0);
msg.addData(0); msg.addData(0);
msg.addData(0); msg.addData(0);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 3 ); REQUIRE( ret.quant == 3 );
REQUIRE( ui->getValue(tID) == 0 ); REQUIRE( ui->getValue(tID) == 0 );
REQUIRE( ui->getValue(tID+1) == 0 ); REQUIRE( ui->getValue(tID+1) == 0 );
REQUIRE( ui->getValue(tID+2) == 0 ); REQUIRE( ui->getValue(tID+2) == 0 );
} }
SECTION("Test: write OVERFLOW VALUE") SECTION("Test: write OVERFLOW VALUE")
{ {
WARN("FIXME: what to do in this situation?!"); WARN("FIXME: what to do in this situation?!");
#if 0 #if 0
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,15,100000); ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06(slaveaddr,15,100000);
REQUIRE( ret.start == 15 ); REQUIRE( ret.start == 15 );
REQUIRE( ret.data == 34464 ); REQUIRE( ret.data == 34464 );
REQUIRE( ui->getValue(1008) == 34464 ); REQUIRE( ui->getValue(1008) == 34464 );
#endif #endif
} }
SECTION("Test: write 2 good registers and unknown register") SECTION("Test: write 2 good registers and unknown register")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+1); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+1);
msg.addData(10); msg.addData(10);
msg.addData(11); msg.addData(11);
msg.addData(12); // BAD REG.. msg.addData(12); // BAD REG..
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG+1 ); REQUIRE( ret.start == tREG+1 );
WARN("FIXME: 'ret.quant' must be '3' or '2'?!"); WARN("FIXME: 'ret.quant' must be '3' or '2'?!");
REQUIRE( ret.quant == 3 ); // "2" ?!! \TODO узнать как нужно поступать по стандарту! REQUIRE( ret.quant == 3 ); // "2" ?!! \TODO узнать как нужно поступать по стандарту!
REQUIRE( ui->getValue(tID+1) == 10 ); REQUIRE( ui->getValue(tID+1) == 10 );
REQUIRE( ui->getValue(tID+2) == 1 ); // 1 - т.к. это "DI" REQUIRE( ui->getValue(tID+2) == 1 ); // 1 - т.к. это "DI"
REQUIRE( ui->getValue(tID+3) == 0 ); REQUIRE( ui->getValue(tID+3) == 0 );
} }
SECTION("Test: write ALL unknown registers") SECTION("Test: write ALL unknown registers")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000);
msg.addData(10); msg.addData(10);
msg.addData(11); msg.addData(11);
msg.addData(12); msg.addData(12);
try try
{ {
mb->write10(msg); mb->write10(msg);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
SECTION("Test: write bad format packet..(incorrect data count)") SECTION("Test: write bad format packet..(incorrect data count)")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000);
msg.addData(10); msg.addData(10);
msg.addData(11); msg.addData(11);
msg.addData(12); msg.addData(12);
msg.quant-=1; msg.quant-=1;
try try
{ {
mb->write10(msg); mb->write10(msg);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
SECTION("Test: write bad format packet..(incorrect size of bytes)") SECTION("Test: write bad format packet..(incorrect size of bytes)")
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG+20000);
msg.addData(10); msg.addData(10);
msg.addData(11); msg.addData(11);
msg.addData(12); msg.addData(12);
msg.bcnt -= 1; msg.bcnt -= 1;
try try
{ {
mb->write10(msg); mb->write10(msg);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
} }
TEST_CASE("Read(0x03,0x04): vtypes..","[modbus][mbslave][mbtcpslave]") TEST_CASE("Read(0x03,0x04): vtypes..","[modbus][mbslave][mbtcpslave]")
{ {
using namespace VTypes; using namespace VTypes;
InitTest(); InitTest();
SECTION("Test: read vtype 'I2'") SECTION("Test: read vtype 'I2'")
{ {
ModbusRTU::ModbusData tREG = 100; ModbusRTU::ModbusData tREG = 100;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,I2::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,I2::wsize());
I2 i2(ret.data,ret.count); I2 i2(ret.data,ret.count);
REQUIRE( (int)i2 == -100000 ); REQUIRE( (int)i2 == -100000 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,I2::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,I2::wsize());
I2 i2(ret.data,ret.count); I2 i2(ret.data,ret.count);
REQUIRE( (int)i2 == -100000 ); REQUIRE( (int)i2 == -100000 );
} }
} }
SECTION("Test: read vtype 'I2r'") SECTION("Test: read vtype 'I2r'")
{ {
ModbusRTU::ModbusData tREG = 102; ModbusRTU::ModbusData tREG = 102;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,I2r::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,I2r::wsize());
I2r i2r(ret.data,ret.count); I2r i2r(ret.data,ret.count);
REQUIRE( (int)i2r == -100000 ); REQUIRE( (int)i2r == -100000 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,I2r::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,I2r::wsize());
I2r i2r(ret.data,ret.count); I2r i2r(ret.data,ret.count);
REQUIRE( (int)i2r == -100000 ); REQUIRE( (int)i2r == -100000 );
} }
} }
SECTION("Test: read vtype 'U2'") SECTION("Test: read vtype 'U2'")
{ {
ModbusRTU::ModbusData tREG = 104; ModbusRTU::ModbusData tREG = 104;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,U2::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,U2::wsize());
U2 u2(ret.data,ret.count); U2 u2(ret.data,ret.count);
REQUIRE( (unsigned int)u2 == 4294967295 ); REQUIRE( (unsigned int)u2 == 4294967295 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,U2::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,U2::wsize());
U2 u2(ret.data,ret.count); U2 u2(ret.data,ret.count);
REQUIRE( (unsigned int)u2 == 4294967295 ); REQUIRE( (unsigned int)u2 == 4294967295 );
} }
} }
SECTION("Test: read vtype 'U2r'") SECTION("Test: read vtype 'U2r'")
{ {
ModbusRTU::ModbusData tREG = 106; ModbusRTU::ModbusData tREG = 106;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,U2r::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,U2r::wsize());
U2r u2r(ret.data,ret.count); U2r u2r(ret.data,ret.count);
REQUIRE( (unsigned int)u2r == 4294967295 ); REQUIRE( (unsigned int)u2r == 4294967295 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,U2r::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,U2r::wsize());
U2r u2r(ret.data,ret.count); U2r u2r(ret.data,ret.count);
REQUIRE( (unsigned int)u2r == 4294967295 ); REQUIRE( (unsigned int)u2r == 4294967295 );
} }
} }
SECTION("Test: read vtype 'F2'") SECTION("Test: read vtype 'F2'")
{ {
ModbusRTU::ModbusData tREG = 110; ModbusRTU::ModbusData tREG = 110;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F2::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F2::wsize());
F2 f2(ret.data,ret.count); F2 f2(ret.data,ret.count);
REQUIRE( (float)f2 == 2.5 ); REQUIRE( (float)f2 == 2.5 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F2::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F2::wsize());
F2 f2(ret.data,ret.count); F2 f2(ret.data,ret.count);
REQUIRE( (float)f2 == 2.5 ); REQUIRE( (float)f2 == 2.5 );
} }
} }
SECTION("Test: read vtype 'F2r'") SECTION("Test: read vtype 'F2r'")
{ {
ModbusRTU::ModbusData tREG = 112; ModbusRTU::ModbusData tREG = 112;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F2r::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F2r::wsize());
F2r f2r(ret.data,ret.count); F2r f2r(ret.data,ret.count);
REQUIRE( (float)f2r == 2.5 ); REQUIRE( (float)f2r == 2.5 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F2r::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F2r::wsize());
F2r f2r(ret.data,ret.count); F2r f2r(ret.data,ret.count);
REQUIRE( (float)f2r == 2.5 ); REQUIRE( (float)f2r == 2.5 );
} }
} }
SECTION("Test: read vtype 'F4'") SECTION("Test: read vtype 'F4'")
{ {
ModbusRTU::ModbusData tREG = 114; ModbusRTU::ModbusData tREG = 114;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F4::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,F4::wsize());
F4 f4(ret.data,ret.count); F4 f4(ret.data,ret.count);
REQUIRE( (float)f4 == 2.5 ); REQUIRE( (float)f4 == 2.5 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F4::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,F4::wsize());
F4 f4(ret.data,ret.count); F4 f4(ret.data,ret.count);
REQUIRE( (float)f4 == 2.5 ); REQUIRE( (float)f4 == 2.5 );
} }
} }
SECTION("Test: read vtype 'Byte N1'") SECTION("Test: read vtype 'Byte N1'")
{ {
ModbusRTU::ModbusData tREG = 108; ModbusRTU::ModbusData tREG = 108;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,Byte::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,Byte::wsize());
Byte b(ret.data[0]); Byte b(ret.data[0]);
REQUIRE( (unsigned short)b == 200 ); REQUIRE( (unsigned short)b == 200 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,Byte::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,Byte::wsize());
Byte b(ret.data[0]); Byte b(ret.data[0]);
REQUIRE( (unsigned short)b == 200 ); REQUIRE( (unsigned short)b == 200 );
} }
} }
SECTION("Test: read vtype 'Byte N2'") SECTION("Test: read vtype 'Byte N2'")
{ {
ModbusRTU::ModbusData tREG = 109; ModbusRTU::ModbusData tREG = 109;
SECTION("Test: read03") SECTION("Test: read03")
{ {
ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,Byte::wsize()); ModbusRTU::ReadOutputRetMessage ret = mb->read03(slaveaddr,tREG,Byte::wsize());
Byte b(ret.data[0]); Byte b(ret.data[0]);
REQUIRE( (unsigned short)b == 200 ); REQUIRE( (unsigned short)b == 200 );
} }
SECTION("Test: read04") SECTION("Test: read04")
{ {
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,Byte::wsize()); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,Byte::wsize());
Byte b(ret.data[0]); Byte b(ret.data[0]);
REQUIRE( (unsigned short)b == 200 ); REQUIRE( (unsigned short)b == 200 );
} }
} }
} }
// ------------------------------------------------------------- // -------------------------------------------------------------
static void test_write10_I2( int val ) static void test_write10_I2( int val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 100; ModbusRTU::ModbusData tREG = 100;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
I2 tmp(val); I2 tmp(val);
msg.addData( tmp.raw.v[0] ); msg.addData( tmp.raw.v[0] );
msg.addData( tmp.raw.v[1] ); msg.addData( tmp.raw.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == I2::wsize() ); REQUIRE( ret.quant == I2::wsize() );
REQUIRE( ui->getValue(2001) == val ); REQUIRE( ui->getValue(2001) == val );
} }
static void test_write10_I2r( int val ) static void test_write10_I2r( int val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 102; ModbusRTU::ModbusData tREG = 102;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
I2r tmp(val); I2r tmp(val);
msg.addData( tmp.raw_backorder.v[0] ); msg.addData( tmp.raw_backorder.v[0] );
msg.addData( tmp.raw_backorder.v[1] ); msg.addData( tmp.raw_backorder.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == I2r::wsize() ); REQUIRE( ret.quant == I2r::wsize() );
REQUIRE( ui->getValue(2002) == val ); REQUIRE( ui->getValue(2002) == val );
} }
static void test_write10_U2( unsigned int val ) static void test_write10_U2( unsigned int val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 104; ModbusRTU::ModbusData tREG = 104;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
U2 tmp(val); U2 tmp(val);
msg.addData( tmp.raw.v[0] ); msg.addData( tmp.raw.v[0] );
msg.addData( tmp.raw.v[1] ); msg.addData( tmp.raw.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == U2::wsize() ); REQUIRE( ret.quant == U2::wsize() );
REQUIRE( (unsigned int)ui->getValue(2003) == val ); REQUIRE( (unsigned int)ui->getValue(2003) == val );
} }
static void test_write10_U2r( unsigned int val ) static void test_write10_U2r( unsigned int val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 106; ModbusRTU::ModbusData tREG = 106;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
U2r tmp(val); U2r tmp(val);
msg.addData( tmp.raw_backorder.v[0] ); msg.addData( tmp.raw_backorder.v[0] );
msg.addData( tmp.raw_backorder.v[1] ); msg.addData( tmp.raw_backorder.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == U2r::wsize() ); REQUIRE( ret.quant == U2r::wsize() );
REQUIRE( (unsigned int)ui->getValue(2004) == val ); REQUIRE( (unsigned int)ui->getValue(2004) == val );
} }
static void test_write10_F2( const float& val ) static void test_write10_F2( const float& val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 110; ModbusRTU::ModbusData tREG = 110;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
F2 tmp(val); F2 tmp(val);
msg.addData( tmp.raw.v[0] ); msg.addData( tmp.raw.v[0] );
msg.addData( tmp.raw.v[1] ); msg.addData( tmp.raw.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == F2::wsize() ); REQUIRE( ret.quant == F2::wsize() );
IOController_i::SensorInfo si; auto conf = uniset_conf();
si.id = 2007; IOController_i::SensorInfo si;
si.node = conf->getLocalNode(); si.id = 2007;
IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si); si.node = conf->getLocalNode();
float fval = (float)ui->getValue(si.id) / pow10(cal.precision); IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si);
float fval = (float)ui->getValue(si.id) / pow10(cal.precision);
REQUIRE( fval == val );
REQUIRE( fval == val );
} }
static void test_write10_F2r( const float& val ) static void test_write10_F2r( const float& val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 112; ModbusRTU::ModbusData tREG = 112;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
F2r tmp(val); F2r tmp(val);
msg.addData( tmp.raw_backorder.v[0] ); msg.addData( tmp.raw_backorder.v[0] );
msg.addData( tmp.raw_backorder.v[1] ); msg.addData( tmp.raw_backorder.v[1] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == F2r::wsize() ); REQUIRE( ret.quant == F2r::wsize() );
IOController_i::SensorInfo si; auto conf = uniset_conf();
si.id = 2008; IOController_i::SensorInfo si;
si.node = conf->getLocalNode(); si.id = 2008;
IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si); si.node = conf->getLocalNode();
float fval = (float)ui->getValue(si.id) / pow10(cal.precision); IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si);
float fval = (float)ui->getValue(si.id) / pow10(cal.precision);
REQUIRE( fval == val );
REQUIRE( fval == val );
} }
static void test_write10_F4raw( const float& val ) static void test_write10_F4raw( const float& val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 120; ModbusRTU::ModbusData tREG = 120;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
F4 tmp(val); F4 tmp(val);
msg.addData( tmp.raw.v[0] ); msg.addData( tmp.raw.v[0] );
msg.addData( tmp.raw.v[1] ); msg.addData( tmp.raw.v[1] );
msg.addData( tmp.raw.v[2] ); msg.addData( tmp.raw.v[2] );
msg.addData( tmp.raw.v[3] ); msg.addData( tmp.raw.v[3] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == F4::wsize() ); REQUIRE( ret.quant == F4::wsize() );
IOController_i::SensorInfo si; auto conf = uniset_conf();
si.id = 2013; IOController_i::SensorInfo si;
si.node = conf->getLocalNode(); si.id = 2013;
si.node = conf->getLocalNode();
long raw = ui->getValue(si.id);
float fval = 0; long raw = ui->getValue(si.id);
memcpy( &fval,&raw,std::min(sizeof(fval),sizeof(raw)) ); float fval = 0;
REQUIRE( fval == val ); memcpy( &fval,&raw,std::min(sizeof(fval),sizeof(raw)) );
REQUIRE( fval == val );
} }
static void test_write10_F4prec( const float& val ) static void test_write10_F4prec( const float& val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 114; ModbusRTU::ModbusData tREG = 114;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
F4 tmp(val); F4 tmp(val);
msg.addData( tmp.raw.v[0] ); msg.addData( tmp.raw.v[0] );
msg.addData( tmp.raw.v[1] ); msg.addData( tmp.raw.v[1] );
msg.addData( tmp.raw.v[2] ); msg.addData( tmp.raw.v[2] );
msg.addData( tmp.raw.v[3] ); msg.addData( tmp.raw.v[3] );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == F4::wsize() ); REQUIRE( ret.quant == F4::wsize() );
IOController_i::SensorInfo si; auto conf = uniset_conf();
si.id = 2009; IOController_i::SensorInfo si;
si.node = conf->getLocalNode(); si.id = 2009;
IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si); si.node = conf->getLocalNode();
float fval = (float)ui->getValue(si.id) / pow10(cal.precision); IOController_i::CalibrateInfo cal = ui->getCalibrateInfo(si);
float fval = (float)ui->getValue(si.id) / pow10(cal.precision);
REQUIRE( fval == val );
REQUIRE( fval == val );
} }
static void test_write10_byte1( unsigned char val ) static void test_write10_byte1( unsigned char val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 108; ModbusRTU::ModbusData tREG = 108;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
Byte tmp(val,0); Byte tmp(val,0);
msg.addData( (unsigned short)tmp ); msg.addData( (unsigned short)tmp );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == Byte::wsize() ); REQUIRE( ret.quant == Byte::wsize() );
REQUIRE( ui->getValue(2005) == (long)val ); REQUIRE( ui->getValue(2005) == (long)val );
} }
static void test_write10_byte2( unsigned char val ) static void test_write10_byte2( unsigned char val )
{ {
using namespace VTypes; using namespace VTypes;
ModbusRTU::ModbusData tREG = 109; ModbusRTU::ModbusData tREG = 109;
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
Byte tmp(0,val); Byte tmp(0,val);
msg.addData( (unsigned short)tmp ); msg.addData( (unsigned short)tmp );
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == Byte::wsize() ); REQUIRE( ret.quant == Byte::wsize() );
REQUIRE( ui->getValue(2006) == (long)val ); REQUIRE( ui->getValue(2006) == (long)val );
} }
TEST_CASE("Write(0x10): vtypes..","[modbus][mbslave][mbtcpslave]") TEST_CASE("Write(0x10): vtypes..","[modbus][mbslave][mbtcpslave]")
{ {
using namespace VTypes; using namespace VTypes;
InitTest(); InitTest();
SECTION("Test: write vtype 'I2'") SECTION("Test: write vtype 'I2'")
{ {
test_write10_I2(numeric_limits<int>::max()); test_write10_I2(numeric_limits<int>::max());
test_write10_I2(0); test_write10_I2(0);
test_write10_I2(numeric_limits<int>::min()); test_write10_I2(numeric_limits<int>::min());
} }
SECTION("Test: write vtype 'I2r'") SECTION("Test: write vtype 'I2r'")
{ {
test_write10_I2r(numeric_limits<int>::max()); test_write10_I2r(numeric_limits<int>::max());
test_write10_I2r(0); test_write10_I2r(0);
test_write10_I2r(numeric_limits<int>::min()); test_write10_I2r(numeric_limits<int>::min());
} }
SECTION("Test: write vtype 'U2'") SECTION("Test: write vtype 'U2'")
{ {
test_write10_U2(numeric_limits<unsigned int>::max()); test_write10_U2(numeric_limits<unsigned int>::max());
test_write10_U2(0); test_write10_U2(0);
test_write10_U2(numeric_limits<unsigned int>::min()); test_write10_U2(numeric_limits<unsigned int>::min());
} }
SECTION("Test: write vtype 'U2r'") SECTION("Test: write vtype 'U2r'")
{ {
test_write10_U2r(numeric_limits<unsigned int>::max()); test_write10_U2r(numeric_limits<unsigned int>::max());
test_write10_U2r(0); test_write10_U2r(0);
test_write10_U2r(numeric_limits<unsigned int>::min()); test_write10_U2r(numeric_limits<unsigned int>::min());
} }
SECTION("Test: write vtype 'F2'") SECTION("Test: write vtype 'F2'")
{ {
test_write10_F2(-0.05); test_write10_F2(-0.05);
test_write10_F2(0); test_write10_F2(0);
test_write10_F2(100000.23); test_write10_F2(100000.23);
} }
SECTION("Test: write vtype 'F2r'") SECTION("Test: write vtype 'F2r'")
{ {
test_write10_F2r(-0.05); test_write10_F2r(-0.05);
test_write10_F2r(0); test_write10_F2r(0);
test_write10_F2r(100000.23); test_write10_F2r(100000.23);
} }
SECTION("Test: write vtype 'F4'(raw)") SECTION("Test: write vtype 'F4'(raw)")
{ {
test_write10_F4raw(numeric_limits<float>::max()); test_write10_F4raw(numeric_limits<float>::max());
test_write10_F4raw(0); test_write10_F4raw(0);
test_write10_F4raw(numeric_limits<float>::min()); test_write10_F4raw(numeric_limits<float>::min());
} }
SECTION("Test: write vtype 'F4'(precision)") SECTION("Test: write vtype 'F4'(precision)")
{ {
test_write10_F4prec(15.55555); test_write10_F4prec(15.55555);
test_write10_F4prec(0); test_write10_F4prec(0);
test_write10_F4prec(-15.00001); test_write10_F4prec(-15.00001);
} }
SECTION("Test: write vtype 'Byte N1'") SECTION("Test: write vtype 'Byte N1'")
{ {
test_write10_byte1(numeric_limits<unsigned char>::max()); test_write10_byte1(numeric_limits<unsigned char>::max());
test_write10_byte1(0); test_write10_byte1(0);
test_write10_byte1(numeric_limits<unsigned char>::min()); test_write10_byte1(numeric_limits<unsigned char>::min());
test_write10_byte1(numeric_limits<char>::max()); test_write10_byte1(numeric_limits<char>::max());
test_write10_byte1(numeric_limits<char>::min()); test_write10_byte1(numeric_limits<char>::min());
} }
SECTION("Test: write vtype 'Byte N2'") SECTION("Test: write vtype 'Byte N2'")
{ {
test_write10_byte2(numeric_limits<unsigned char>::max()); test_write10_byte2(numeric_limits<unsigned char>::max());
test_write10_byte2(0); test_write10_byte2(0);
test_write10_byte2(numeric_limits<unsigned char>::min()); test_write10_byte2(numeric_limits<unsigned char>::min());
test_write10_byte2(numeric_limits<char>::max()); test_write10_byte2(numeric_limits<char>::max());
test_write10_byte2(numeric_limits<char>::min()); test_write10_byte2(numeric_limits<char>::min());
} }
} }
#if 0 #if 0
TEST_CASE("(0x14): read file record","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x14): read file record","[modbus][mbslave][mbtcpslave]")
{ {
} }
TEST_CASE("(0x15): write file record","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x15): write file record","[modbus][mbslave][mbtcpslave]")
{ {
} }
TEST_CASE("(0x2B): Modbus Encapsulated Interface","[modbus][mbslave][mbtcpslave]") TEST_CASE("(0x2B): Modbus Encapsulated Interface","[modbus][mbslave][mbtcpslave]")
{ {
} }
TEST_CASE("(0x50): set date and time") TEST_CASE("(0x50): set date and time")
{ {
} }
TEST_CASE("(0x53): call remote service") TEST_CASE("(0x53): call remote service")
{ {
} }
TEST_CASE("(0x65): read,write,delete alarm journal") TEST_CASE("(0x65): read,write,delete alarm journal")
{ {
} }
TEST_CASE("(0x66): file transfer") TEST_CASE("(0x66): file transfer")
{ {
} }
#endif #endif
TEST_CASE("access mode","[modbus][mbslvae][mbtcpslave]") TEST_CASE("access mode","[modbus][mbslvae][mbtcpslave]")
{ {
SECTION("test 'RO' register") SECTION("test 'RO' register")
{ {
ModbusRTU::ModbusData tREG=124; ModbusRTU::ModbusData tREG=124;
// read // read
ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1); ModbusRTU::ReadInputRetMessage ret = mb->read04(slaveaddr,tREG,1);
REQUIRE( ret.data[0] == 1002 ); REQUIRE( ret.data[0] == 1002 );
// write // write
try try
{ {
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(33); msg.addData(33);
mb->write10(msg); mb->write10(msg);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
} }
SECTION("test 'WO' register") SECTION("test 'WO' register")
{ {
ModbusRTU::ModbusData tREG=125; ModbusRTU::ModbusData tREG=125;
// read // read
try try
{ {
mb->read04(slaveaddr,tREG,1); mb->read04(slaveaddr,tREG,1);
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
REQUIRE( ex.err == ModbusRTU::erBadDataAddress ); REQUIRE( ex.err == ModbusRTU::erBadDataAddress );
} }
// write // write
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(555); msg.addData(555);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 1 ); REQUIRE( ret.quant == 1 );
REQUIRE( ui->getValue(2015) == 555 ); REQUIRE( ui->getValue(2015) == 555 );
} }
SECTION("test 'RW' register") SECTION("test 'RW' register")
{ {
ModbusRTU::ModbusData tREG=126; ModbusRTU::ModbusData tREG=126;
// write // write
ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG); ModbusRTU::WriteOutputMessage msg(slaveaddr,tREG);
msg.addData(555); msg.addData(555);
ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg); ModbusRTU::WriteOutputRetMessage ret = mb->write10(msg);
REQUIRE( ret.start == tREG ); REQUIRE( ret.start == tREG );
REQUIRE( ret.quant == 1 ); REQUIRE( ret.quant == 1 );
REQUIRE( ui->getValue(2016) == 555 ); REQUIRE( ui->getValue(2016) == 555 );
// read // read
ModbusRTU::ReadInputRetMessage rret = mb->read04(slaveaddr,tREG,1); ModbusRTU::ReadInputRetMessage rret = mb->read04(slaveaddr,tREG,1);
REQUIRE( rret.data[0] == 555 ); REQUIRE( rret.data[0] == 555 );
} }
} }
...@@ -15,27 +15,27 @@ using namespace UniSetExtensions; ...@@ -15,27 +15,27 @@ using namespace UniSetExtensions;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char* argv[] ) int main(int argc, char* argv[] )
{ {
Catch::Session session; Catch::Session session;
if( argc>1 && ( strcmp(argv[1],"--help")==0 || strcmp(argv[1],"-h")==0 ) ) if( argc>1 && ( strcmp(argv[1],"--help")==0 || strcmp(argv[1],"-h")==0 ) )
{ {
cout << "--confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl; cout << "--confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
SharedMemory::help_print(argc, argv); SharedMemory::help_print(argc, argv);
cout << endl << endl << "--------------- CATCH HELP --------------" << endl; cout << endl << endl << "--------------- CATCH HELP --------------" << endl;
session.showHelp("test_with_sm"); session.showHelp("test_with_sm");
return 0; return 0;
} }
int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore ); int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore );
if( returnCode != 0 ) // Indicates a command line error if( returnCode != 0 ) // Indicates a command line error
return returnCode; return returnCode;
try try
{ {
uniset_init(argc,argv); auto conf = uniset_init(argc,argv);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
bool apart = findArgParam("--apart",argc,argv) != -1; bool apart = findArgParam("--apart",argc,argv) != -1;
SharedMemory* shm = SharedMemory::init_smemory(argc, argv); SharedMemory* shm = SharedMemory::init_smemory(argc, argv);
if( !shm ) if( !shm )
return 1; return 1;
...@@ -56,18 +56,18 @@ int main(int argc, char* argv[] ) ...@@ -56,18 +56,18 @@ int main(int argc, char* argv[] )
int tout = 6000; int tout = 6000;
PassiveTimer pt(tout); PassiveTimer pt(tout);
while( !pt.checkTime() && !act->exist() ) while( !pt.checkTime() && !act->exist() )
msleep(100); msleep(100);
if( !act->exist() ) if( !act->exist() )
{ {
cerr << "(tests_with_sm): SharedMemory not exist! (timeout=" << tout << ")" << endl; cerr << "(tests_with_sm): SharedMemory not exist! (timeout=" << tout << ")" << endl;
return 1; return 1;
} }
int ret = session.run(); int ret = session.run();
act->oaDestroy(); act->oaDestroy();
return ret; return ret;
} }
catch( SystemError& err ) catch( SystemError& err )
{ {
......
...@@ -98,6 +98,7 @@ void RRDServer::initRRD( xmlNode* cnode, int tmID ) ...@@ -98,6 +98,7 @@ void RRDServer::initRRD( xmlNode* cnode, int tmID )
// try // try
{ {
auto conf = uniset_conf();
xmlNode* snode = conf->getXMLSensorsSection(); xmlNode* snode = conf->getXMLSensorsSection();
if(!snode) if(!snode)
...@@ -225,6 +226,8 @@ RRDServer* RRDServer::init_rrdstorage( int argc, const char* const* argv, ...@@ -225,6 +226,8 @@ RRDServer* RRDServer::init_rrdstorage( int argc, const char* const* argv,
UniSetTypes::ObjectId icID, SharedMemory* ic, UniSetTypes::ObjectId icID, SharedMemory* ic,
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","RRDServer"); string name = conf->getArgParam("--" + prefix + "-name","RRDServer");
if( name.empty() ) if( name.empty() )
{ {
......
...@@ -23,8 +23,7 @@ int main( int argc, const char** argv ) ...@@ -23,8 +23,7 @@ int main( int argc, const char** argv )
try try
{ {
string confile=UniSetTypes::getArgParam("--confile",argc, argv, "configure.xml"); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
string logfilename(conf->getArgParam("--rrdstorage-logfile")); string logfilename(conf->getArgParam("--rrdstorage-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -7,7 +7,7 @@ using namespace UniSetTypes; ...@@ -7,7 +7,7 @@ using namespace UniSetTypes;
using namespace UniSetExtensions; using namespace UniSetExtensions;
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
SMViewer::SMViewer( UniSetTypes::ObjectId shmID ): SMViewer::SMViewer( UniSetTypes::ObjectId shmID ):
SViewer(conf->getControllersSection(),true) SViewer(uniset_conf()->getControllersSection(),true)
{ {
shm = new SMInterface(shmID,&ui,DefaultObjectId,0); shm = new SMInterface(shmID,&ui,DefaultObjectId,0);
} }
......
...@@ -18,8 +18,7 @@ int main( int argc, const char **argv ) ...@@ -18,8 +18,7 @@ int main( int argc, const char **argv )
return 0; return 0;
} }
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init( argc, argv );
conf = new Configuration( argc, argv, confile );
ObjectId shmID = DefaultObjectId; ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id"); string sID = conf->getArgParam("--smemory-id");
......
...@@ -43,11 +43,13 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std: ...@@ -43,11 +43,13 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std:
{ {
mutex_start.setName(myname + "_mutex_start"); mutex_start.setName(myname + "_mutex_start");
auto conf = uniset_conf();
string cname(confname); string cname(confname);
if( cname.empty() ) if( cname.empty() )
cname = ORepHelpers::getShortName(conf->oind->getMapName(id)); cname = ORepHelpers::getShortName( conf->oind->getMapName(id));
xmlNode* cnode = conf->getNode(cname); xmlNode* cnode = conf->getNode(cname);
if( cnode == NULL ) if( cnode == NULL )
throw SystemError("Not found conf-node for " + cname ); throw SystemError("Not found conf-node for " + cname );
...@@ -71,9 +73,9 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std: ...@@ -71,9 +73,9 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std:
heartbeat_node = conf->getArgParam("--heartbeat-node"); heartbeat_node = conf->getArgParam("--heartbeat-node");
if( heartbeat_node.empty() ) if( heartbeat_node.empty() )
{ {
dwarn << myname << "(init): --heartbeat-node NULL ===> heartbeat NOT USED..." << endl; dwarn << myname << "(init): --heartbeat-node NULL ===> heartbeat NOT USED..." << endl;
} }
else else
dinfo << myname << "(init): heartbeat-node: " << heartbeat_node << endl; dinfo << myname << "(init): heartbeat-node: " << heartbeat_node << endl;
...@@ -267,7 +269,7 @@ void SharedMemory::sigterm( int signo ) ...@@ -267,7 +269,7 @@ void SharedMemory::sigterm( int signo )
if( signo == SIGTERM && wdt ) if( signo == SIGTERM && wdt )
wdt->stop(); wdt->stop();
// raise(SIGKILL); // raise(SIGKILL);
IONotifyController_LT::sigterm(signo); IONotifyController_LT::sigterm(signo);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void SharedMemory::checkHeartBeat() void SharedMemory::checkHeartBeat()
...@@ -374,7 +376,7 @@ bool SharedMemory::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterato ...@@ -374,7 +376,7 @@ bool SharedMemory::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterato
} }
else else
{ {
hi.d_sid = conf->getSensorID(it.getProp("heartbeat_ds_name")); hi.d_sid = uniset_conf()->getSensorID(it.getProp("heartbeat_ds_name"));
if( hi.d_sid == DefaultObjectId ) if( hi.d_sid == DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -410,6 +412,7 @@ bool SharedMemory::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterato ...@@ -410,6 +412,7 @@ bool SharedMemory::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterato
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
SharedMemory* SharedMemory::init_smemory( int argc, const char* const* argv ) SharedMemory* SharedMemory::init_smemory( int argc, const char* const* argv )
{ {
auto conf = uniset_conf();
string dfile = conf->getArgParam("--datfile", conf->getConfFileName()); string dfile = conf->getArgParam("--datfile", conf->getConfFileName());
if( dfile[0]!='.' && dfile[0]!='/' ) if( dfile[0]!='.' && dfile[0]!='/' )
...@@ -439,7 +442,7 @@ void SharedMemory::buildEventList( xmlNode* cnode ) ...@@ -439,7 +442,7 @@ void SharedMemory::buildEventList( xmlNode* cnode )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void SharedMemory::readEventList( const std::string& oname ) void SharedMemory::readEventList( const std::string& oname )
{ {
xmlNode* enode = conf->getNode(oname); xmlNode* enode = uniset_conf()->getNode(oname);
if( enode == NULL ) if( enode == NULL )
{ {
dwarn << myname << "(readEventList): " << oname << " не найден..." << endl; dwarn << myname << "(readEventList): " << oname << " не найден..." << endl;
...@@ -508,7 +511,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode ) ...@@ -508,7 +511,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
{ {
dinfo << myname << "(buildHistoryList): ..." << endl; dinfo << myname << "(buildHistoryList): ..." << endl;
const std::shared_ptr<UniXML> xml = conf->getConfXML(); const std::shared_ptr<UniXML> xml = uniset_conf()->getConfXML();
if( !xml ) if( !xml )
{ {
dwarn << myname << "(buildHistoryList): xml=NULL?!" << endl; dwarn << myname << "(buildHistoryList): xml=NULL?!" << endl;
...@@ -525,7 +528,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode ) ...@@ -525,7 +528,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
UniXML::iterator it(n); UniXML::iterator it(n);
bool no_history = conf->getArgInt("--sm-no-history",it.getProp("no_history")); bool no_history = uniset_conf()->getArgInt("--sm-no-history",it.getProp("no_history"));
if( no_history ) if( no_history )
{ {
dwarn << myname << "(buildHistoryList): no_history='1'.. history skipped..." << endl; dwarn << myname << "(buildHistoryList): no_history='1'.. history skipped..." << endl;
...@@ -555,7 +558,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode ) ...@@ -555,7 +558,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
if( hi.filter.empty() ) if( hi.filter.empty() )
continue; continue;
hi.fuse_id = conf->getSensorID(it.getProp("fuse_id")); hi.fuse_id = uniset_conf()->getSensorID(it.getProp("fuse_id"));
if( hi.fuse_id == DefaultObjectId ) if( hi.fuse_id == DefaultObjectId )
{ {
dwarn << myname << "(buildHistory): not found sensor ID for " dwarn << myname << "(buildHistory): not found sensor ID for "
...@@ -604,7 +607,7 @@ void SharedMemory::checkHistoryFilter( UniXML::iterator& xit ) ...@@ -604,7 +607,7 @@ void SharedMemory::checkHistoryFilter( UniXML::iterator& xit )
continue; continue;
} }
ai.id = conf->getSensorID(xit.getProp("name")); ai.id = uniset_conf()->getSensorID(xit.getProp("name"));
if( ai.id == DefaultObjectId ) if( ai.id == DefaultObjectId )
{ {
dwarn << myname << "(checkHistoryFilter): not found sensor ID for " << xit.getProp("name") << endl; dwarn << myname << "(checkHistoryFilter): not found sensor ID for " << xit.getProp("name") << endl;
......
...@@ -19,8 +19,7 @@ int main(int argc, const char **argv) ...@@ -19,8 +19,7 @@ int main(int argc, const char **argv)
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--logfile", "smemory.log"); string logfilename = conf->getArgParam("--logfile", "smemory.log");
......
...@@ -33,25 +33,25 @@ std::list< ThreadCreator<IOControl>* > lst_iothr; ...@@ -33,25 +33,25 @@ std::list< ThreadCreator<IOControl>* > lst_iothr;
#endif #endif
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void activator_terminate( int signo ) void activator_terminate( int signo )
{ {
if( logserver ) if( logserver )
{ {
try try
{ {
delete logserver; delete logserver;
logserver = 0; logserver = 0;
} }
catch(...){} catch(...){}
} }
#ifdef UNISET_IO_ENABLE #ifdef UNISET_IO_ENABLE
for( auto& i: lst_iothr ) for( auto& i: lst_iothr )
{ {
try try
{ {
i->stop(); i->stop();
} }
catch(...){} catch(...){}
} }
#endif #endif
} }
...@@ -67,8 +67,7 @@ int main( int argc, const char **argv ) ...@@ -67,8 +67,7 @@ int main( int argc, const char **argv )
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv, confile);
string logfilename = conf->getArgParam("--logfile", "smemory-plus.log"); string logfilename = conf->getArgParam("--logfile", "smemory-plus.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
...@@ -217,16 +216,16 @@ int main( int argc, const char **argv ) ...@@ -217,16 +216,16 @@ int main( int argc, const char **argv )
i->start(); i->start();
#endif #endif
LogAgregator la; LogAgregator la;
la.add(ulog); la.add(ulog);
la.add(dlog); la.add(dlog);
logserver = run_logserver("smplus",la); logserver = run_logserver("smplus",la);
if( logserver == 0 ) if( logserver == 0 )
{ {
cerr << "(smemory-plus): run logserver for 'smplus' FAILED" << endl; cerr << "(smemory-plus): run logserver for 'smplus' FAILED" << endl;
return 1; return 1;
} }
act->run(false); act->run(false);
...@@ -287,45 +286,46 @@ void help_print( int argc, const char* argv[] ) ...@@ -287,45 +286,46 @@ void help_print( int argc, const char* argv[] )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
LogServer* run_logserver( const std::string& cname, DebugStream& log ) LogServer* run_logserver( const std::string& cname, DebugStream& log )
{ {
const std::shared_ptr<UniXML> xml = UniSetTypes::conf->getConfXML(); auto conf = uniset_conf();
xmlNode* cnode = UniSetTypes::conf->findNode(xml->getFirstNode(),"LogServer",cname); auto xml = conf->getConfXML();
if( cnode == 0 ) xmlNode* cnode = conf->findNode(xml->getFirstNode(),"LogServer",cname);
{ if( cnode == 0 )
cerr << "(init_ulogserver): Not found xmlnode for '" << cname << "'" << endl; {
return 0; cerr << "(init_ulogserver): Not found xmlnode for '" << cname << "'" << endl;
return 0;
}
}
UniXML::iterator it(cnode);
UniXML::iterator it(cnode);
LogServer* ls = new LogServer( log );
LogServer* ls = new LogServer( log );
timeout_t sessTimeout = conf->getArgPInt("--" + cname + "-session-timeout",it.getProp("sessTimeout"),3600000);
timeout_t cmdTimeout = conf->getArgPInt("--" + cname + "-cmd-timeout",it.getProp("cmdTimeout"),2000); timeout_t sessTimeout = conf->getArgPInt("--" + cname + "-session-timeout",it.getProp("sessTimeout"),3600000);
timeout_t outTimeout = conf->getArgPInt("--" + cname + "-out-timeout",it.getProp("outTimeout"),2000); timeout_t cmdTimeout = conf->getArgPInt("--" + cname + "-cmd-timeout",it.getProp("cmdTimeout"),2000);
timeout_t outTimeout = conf->getArgPInt("--" + cname + "-out-timeout",it.getProp("outTimeout"),2000);
ls->setSessionTimeout(sessTimeout);
ls->setCmdTimeout(cmdTimeout); ls->setSessionTimeout(sessTimeout);
ls->setOutTimeout(outTimeout); ls->setCmdTimeout(cmdTimeout);
ls->setOutTimeout(outTimeout);
std::string host = conf->getArgParam("--" + cname + "-host",it.getProp("host"));
if( host.empty() ) std::string host = conf->getArgParam("--" + cname + "-host",it.getProp("host"));
{ if( host.empty() )
cerr << "(init_ulogserver): " << cname << ": unknown host.." << endl; {
delete ls; cerr << "(init_ulogserver): " << cname << ": unknown host.." << endl;
return 0; delete ls;
} return 0;
}
ost::tpport_t port = conf->getArgPInt("--" + cname + "-port",it.getProp("port"),0);
if( port == 0 ) ost::tpport_t port = conf->getArgPInt("--" + cname + "-port",it.getProp("port"),0);
{ if( port == 0 )
cerr << "(init_ulogserver): " << cname << ": unknown port.." << endl; {
delete ls; cerr << "(init_ulogserver): " << cname << ": unknown port.." << endl;
return 0; delete ls;
} return 0;
}
cout << "logserver: " << host << ":" << port << endl;
ls->run(host, port, true); cout << "logserver: " << host << ":" << port << endl;
return ls; ls->run(host, port, true);
return ls;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -170,8 +170,8 @@ size_t UDPMessage::getMessage( UDPMessage& m, UDPPacket& p ) ...@@ -170,8 +170,8 @@ size_t UDPMessage::getMessage( UDPMessage& m, UDPPacket& p )
// проверяем наш ли пакет.. // проверяем наш ли пакет..
if( m.magic != UniSetUDP::UNETUDP_MAGICNUM ) if( m.magic != UniSetUDP::UNETUDP_MAGICNUM )
{ {
m.magic = 0; m.magic = 0;
return 0; return 0;
} }
// копируем аналоговые данные // копируем аналоговые данные
......
...@@ -18,6 +18,8 @@ sender2(0) ...@@ -18,6 +18,8 @@ sender2(0)
{ {
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(UNetExchange): objId=-1?!! Use --" + prefix +"-unet-name" ); throw UniSetTypes::SystemError("(UNetExchange): objId=-1?!! Use --" + prefix +"-unet-name" );
auto conf = uniset_conf();
cnode = conf->getNode(myname); cnode = conf->getNode(myname);
if( cnode == NULL ) if( cnode == NULL )
...@@ -376,7 +378,7 @@ void UNetExchange::startReceivers() ...@@ -376,7 +378,7 @@ void UNetExchange::startReceivers()
void UNetExchange::waitSMReady() void UNetExchange::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int ready_timeout = conf->getArgInt("--unet-sm-ready-timeout","15000"); int ready_timeout = uniset_conf()->getArgInt("--unet-sm-ready-timeout","15000");
if( ready_timeout == 0 ) if( ready_timeout == 0 )
ready_timeout = 15000; ready_timeout = 15000;
else if( ready_timeout < 0 ) else if( ready_timeout < 0 )
...@@ -656,6 +658,8 @@ void UNetExchange::help_print( int argc, const char* argv[] ) ...@@ -656,6 +658,8 @@ void UNetExchange::help_print( int argc, const char* argv[] )
UNetExchange* UNetExchange::init_unetexchange( int argc, const char* argv[], UniSetTypes::ObjectId icID, UNetExchange* UNetExchange::init_unetexchange( int argc, const char* argv[], UniSetTypes::ObjectId icID,
SharedMemory* ic, const std::string& prefix ) SharedMemory* ic, const std::string& prefix )
{ {
auto conf = uniset_conf();
string p("--" + prefix + "-name"); string p("--" + prefix + "-name");
string name = conf->getArgParam(p,"UNetExchange1"); string name = conf->getArgParam(p,"UNetExchange1");
if( name.empty() ) if( name.empty() )
......
...@@ -519,7 +519,7 @@ void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force ) ...@@ -519,7 +519,7 @@ void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force )
if( d.id != pack.d_id[i] ) if( d.id != pack.d_id[i] )
{ {
d.id = pack.d_id[i]; d.id = pack.d_id[i];
d.iotype = conf->getIOType(d.id); d.iotype = uniset_conf()->getIOType(d.id);
shm->initIterator(d.ioit); shm->initIterator(d.ioit);
} }
} }
...@@ -540,7 +540,7 @@ void UNetReceiver::initACache( UniSetUDP::UDPMessage& pack, bool force ) ...@@ -540,7 +540,7 @@ void UNetReceiver::initACache( UniSetUDP::UDPMessage& pack, bool force )
if( d.id != pack.a_dat[i].id ) if( d.id != pack.a_dat[i].id )
{ {
d.id = pack.a_dat[i].id; d.id = pack.a_dat[i].id;
d.iotype = conf->getIOType(d.id); d.iotype = uniset_conf()->getIOType(d.id);
shm->initIterator(d.ioit); shm->initIterator(d.ioit);
} }
} }
......
...@@ -71,7 +71,7 @@ s_thr(0) ...@@ -71,7 +71,7 @@ s_thr(0)
// выставляем поля, которые не меняются // выставляем поля, которые не меняются
mypack.nodeID = conf->getLocalNode(); mypack.nodeID = uniset_conf()->getLocalNode();
mypack.procID = shm->ID(); mypack.procID = shm->ID();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -210,7 +210,7 @@ void UNetSender::start() ...@@ -210,7 +210,7 @@ void UNetSender::start()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetSender::readConfiguration() void UNetSender::readConfiguration()
{ {
xmlNode* root = conf->getXMLSensorsSection(); xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root) if(!root)
{ {
ostringstream err; ostringstream err;
...@@ -253,7 +253,7 @@ bool UNetSender::initItem( UniXML::iterator& it ) ...@@ -253,7 +253,7 @@ bool UNetSender::initItem( UniXML::iterator& it )
sid = DefaultObjectId; sid = DefaultObjectId;
} }
else else
sid = conf->getSensorID(sname); sid = uniset_conf()->getSensorID(sname);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
......
...@@ -21,7 +21,7 @@ int main( int argc, const char** argv ) ...@@ -21,7 +21,7 @@ int main( int argc, const char** argv )
return 0; return 0;
} }
uniset_init(argc,argv); auto conf = uniset_init(argc,argv);
string logfilename(conf->getArgParam("--unet-logfile")); string logfilename(conf->getArgParam("--unet-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
......
...@@ -10,7 +10,7 @@ using namespace UniSetExtensions; ...@@ -10,7 +10,7 @@ using namespace UniSetExtensions;
UniExchange::NetNodeInfo::NetNodeInfo(): UniExchange::NetNodeInfo::NetNodeInfo():
oref(CORBA::Object::_nil()), oref(CORBA::Object::_nil()),
id(DefaultObjectId), id(DefaultObjectId),
node(conf->getLocalNode()), node(uniset_conf()->getLocalNode()),
sidConnection(DefaultObjectId), sidConnection(DefaultObjectId),
smap(1) smap(1)
{ {
...@@ -26,6 +26,8 @@ mymap(1), ...@@ -26,6 +26,8 @@ mymap(1),
maxIndex(0), maxIndex(0),
smReadyTimeout(15000) smReadyTimeout(15000)
{ {
auto conf = uniset_conf();
cnode = conf->getNode(myname); cnode = conf->getNode(myname);
if( cnode == NULL ) if( cnode == NULL )
throw UniSetTypes::SystemError("(UniExchange): Not found conf-node for " + myname ); throw UniSetTypes::SystemError("(UniExchange): Not found conf-node for " + myname );
...@@ -176,7 +178,7 @@ void UniExchange::execute() ...@@ -176,7 +178,7 @@ void UniExchange::execute()
catch(...) catch(...)
{ {
dcrit << myname << "(execute): sensor not avalible " dcrit << myname << "(execute): sensor not avalible "
<< conf->oind->getNameById(it.sidConnection) << uniset_conf()->oind->getNameById(it.sidConnection)
<< endl; << endl;
} }
} }
...@@ -329,6 +331,8 @@ UniExchange* UniExchange::init_exchange( int argc, const char* const* argv, ...@@ -329,6 +331,8 @@ UniExchange* UniExchange::init_exchange( int argc, const char* const* argv,
UniSetTypes::ObjectId icID, SharedMemory* ic, UniSetTypes::ObjectId icID, SharedMemory* ic,
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf();
string p("--" + prefix + "-name"); string p("--" + prefix + "-name");
string nm(UniSetTypes::getArgParam(p,argc,argv,"UniExchange")); string nm(UniSetTypes::getArgParam(p,argc,argv,"UniExchange"));
...@@ -345,7 +349,7 @@ UniExchange* UniExchange::init_exchange( int argc, const char* const* argv, ...@@ -345,7 +349,7 @@ UniExchange* UniExchange::init_exchange( int argc, const char* const* argv,
void UniExchange::readConfiguration() void UniExchange::readConfiguration()
{ {
// readconf_ok = false; // readconf_ok = false;
xmlNode* root = conf->getXMLSensorsSection(); xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root) if(!root)
{ {
ostringstream err; ostringstream err;
...@@ -383,7 +387,7 @@ bool UniExchange::initItem( UniXML::iterator& it ) ...@@ -383,7 +387,7 @@ bool UniExchange::initItem( UniXML::iterator& it )
i.id = DefaultObjectId; i.id = DefaultObjectId;
if( it.getProp("id").empty() ) if( it.getProp("id").empty() )
i.id = conf->getSensorID(it.getProp("name")); i.id = uniset_conf()->getSensorID(it.getProp("name"));
else else
{ {
i.id = it.getIntProp("id"); i.id = it.getIntProp("id");
......
...@@ -19,8 +19,7 @@ int main(int argc, const char **argv) ...@@ -19,8 +19,7 @@ int main(int argc, const char **argv)
try try
{ {
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv);
conf = new Configuration(argc, argv, confile);
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--logfile", "smemory.log"); string logfilename = conf->getArgParam("--logfile", "smemory.log");
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2014-01-27+04:00 // generate timestamp: 2014-11-24+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef UObject_SK_H_ #ifndef UObject_SK_H_
#define UObject_SK_H_ #define UObject_SK_H_
...@@ -25,7 +25,7 @@ class UObject_SK: ...@@ -25,7 +25,7 @@ class UObject_SK:
public LT_Object public LT_Object
{ {
public: public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::conf->getNode("UObject"), const std::string& argprefix="" ); UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix="" );
UObject_SK(); UObject_SK();
virtual ~UObject_SK(); virtual ~UObject_SK();
...@@ -33,7 +33,7 @@ class UObject_SK: ...@@ -33,7 +33,7 @@ class UObject_SK:
bool alarm( UniSetTypes::ObjectId sid, bool state ); bool alarm( UniSetTypes::ObjectId sid, bool state );
long getValue( UniSetTypes::ObjectId sid ); long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value ); void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
void updateValues(); void updateValues();
void setMsg( UniSetTypes::ObjectId code, bool state ); void setMsg( UniSetTypes::ObjectId code, bool state );
...@@ -76,14 +76,14 @@ class UObject_SK: ...@@ -76,14 +76,14 @@ class UObject_SK:
// ---- end of protected variables ---- // ---- end of protected variables ----
virtual void callback(); virtual void callback() override;
virtual void processingMessage( UniSetTypes::VoidMessage* msg ); virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ); virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void askSensors( UniversalIO::UIOCommand cmd ){} virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ){} virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ){} virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ); virtual void sigterm( int signo ) override;
virtual bool activateObject(); virtual bool activateObject() override;
virtual void testMode( bool state ); virtual void testMode( bool state );
void updatePreviousValues(); void updatePreviousValues();
void checkSensors(); void checkSensors();
...@@ -100,7 +100,7 @@ class UObject_SK: ...@@ -100,7 +100,7 @@ class UObject_SK:
int resetMsgTime; int resetMsgTime;
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step()=0; virtual void step(){}
int sleep_msec; /*!< пауза между итерациями */ int sleep_msec; /*!< пауза между итерациями */
bool active; bool active;
...@@ -114,9 +114,9 @@ class UObject_SK: ...@@ -114,9 +114,9 @@ class UObject_SK:
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) { return UniSetTypes::conf->getIntProp(confnode, name); } int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) { return UniSetTypes::conf->getProp(confnode, name); } inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
int smReadyTimeout; /*!< время ожидания готовности SM */ int smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
......
...@@ -168,7 +168,7 @@ namespace VTypes ...@@ -168,7 +168,7 @@ namespace VTypes
static VType type(){ return vtByte; } static VType type(){ return vtByte; }
// ------------------------------------------ // ------------------------------------------
operator long(){ return lroundf(raw.w); } operator long(){ return lroundf(raw.w); }
operator unsigned short(){ return raw.w; } operator unsigned short(){ return raw.w; }
unsigned char operator[]( const int i ){ return raw.b[i]; } unsigned char operator[]( const int i ){ return raw.b[i]; }
......
...@@ -212,12 +212,12 @@ int DigitalFilter::median( int newval ) ...@@ -212,12 +212,12 @@ int DigitalFilter::median( int newval )
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
int DigitalFilter::currentMedian() int DigitalFilter::currentMedian()
{ {
if( !mvec_sorted ) if( !mvec_sorted )
{ {
mvec.assign(buf.begin(),buf.end()); mvec.assign(buf.begin(),buf.end());
sort(mvec.begin(),mvec.end()); sort(mvec.begin(),mvec.end());
// mvec_sorted = true; // специально не выставляю, чтобы если данные добавляются через add(), то тут надо каждый раз пересчитыать.. // mvec_sorted = true; // специально не выставляю, чтобы если данные добавляются через add(), то тут надо каждый раз пересчитыать..
} }
return mvec[maxsize/2]; return mvec[maxsize/2];
} }
......
...@@ -17,6 +17,8 @@ namespace UniSetExtensions ...@@ -17,6 +17,8 @@ namespace UniSetExtensions
{ {
if( shmID != DefaultObjectId ) if( shmID != DefaultObjectId )
return shmID; return shmID;
auto conf = uniset_conf();
string sname = conf->getArgParam("--smemory-id","SharedMemory1"); string sname = conf->getArgParam("--smemory-id","SharedMemory1");
shmID = conf->getControllerID(sname); shmID = conf->getControllerID(sname);
...@@ -54,7 +56,7 @@ namespace UniSetExtensions ...@@ -54,7 +56,7 @@ namespace UniSetExtensions
if( xmlCalibrationsNode ) if( xmlCalibrationsNode )
return xmlCalibrationsNode; return xmlCalibrationsNode;
xmlCalibrationsNode = conf->getNode("Calibrations"); xmlCalibrationsNode = uniset_conf()->getNode("Calibrations");
return xmlCalibrationsNode; return xmlCalibrationsNode;
} }
...@@ -103,7 +105,7 @@ namespace UniSetExtensions ...@@ -103,7 +105,7 @@ namespace UniSetExtensions
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void on_sigchild( int sig ) void on_sigchild( int sig )
{ {
while(1) while(1)
{ {
int istatus; int istatus;
pid_t pid = waitpid( -1, &istatus, WNOHANG ); pid_t pid = waitpid( -1, &istatus, WNOHANG );
......
...@@ -7,7 +7,7 @@ using namespace UniSetTypes; ...@@ -7,7 +7,7 @@ using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, IOBase& inf ) std::ostream& operator<<( std::ostream& os, IOBase& inf )
{ {
return os << "(" << inf.si.id << ")" << conf->oind->getMapName(inf.si.id) return os << "(" << inf.si.id << ")" << uniset_conf()->oind->getMapName(inf.si.id)
<< " default=" << inf.defval << " safety=" << inf.safety; << " default=" << inf.defval << " safety=" << inf.safety;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -136,29 +136,29 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force ...@@ -136,29 +136,29 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force
val = it->df.filterRC(val); val = it->df.filterRC(val);
} }
if( !it->rawdata ) if( !it->rawdata )
{ {
if( it->cdiagram ) // задана специальная калибровочная диаграмма if( it->cdiagram ) // задана специальная калибровочная диаграмма
{ {
if( it->craw != val ) if( it->craw != val )
{ {
it->craw = val; it->craw = val;
val = it->cdiagram->getValue(val); val = it->cdiagram->getValue(val);
it->cprev = val; it->cprev = val;
} }
else else
val = it->cprev; // просто передаём предыдущее значение val = it->cprev; // просто передаём предыдущее значение
} }
else else
{ {
IOController_i::CalibrateInfo* cal( &(it->cal) ); IOController_i::CalibrateInfo* cal( &(it->cal) );
if( cal->maxRaw!=cal->minRaw ) // задана обычная калибровка if( cal->maxRaw!=cal->minRaw ) // задана обычная калибровка
val = UniSetTypes::lcalibrate(val,cal->minRaw,cal->maxRaw,cal->minCal,cal->maxCal,true); val = UniSetTypes::lcalibrate(val,cal->minRaw,cal->maxRaw,cal->minCal,cal->maxCal,true);
} }
if( !it->noprecision && it->cal.precision > 0 ) if( !it->noprecision && it->cal.precision > 0 )
val *= lround(pow10(it->cal.precision)); val *= lround(pow10(it->cal.precision));
} }
// если предыдущее значение "обрыв", // если предыдущее значение "обрыв",
// то сбрасываем признак // то сбрасываем признак
{ {
...@@ -178,12 +178,12 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for ...@@ -178,12 +178,12 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for
{ {
long val = lroundf(fval); long val = lroundf(fval);
if( it->rawdata ) if( it->rawdata )
{ {
val = 0; val = 0;
memcpy(&val,&fval, std::min(sizeof(val),sizeof(fval))); memcpy(&val,&fval, std::min(sizeof(val),sizeof(fval)));
} }
else if( it->cal.precision > 0 ) else if( it->cal.precision > 0 )
val = lroundf( fval * pow10(it->cal.precision) ); val = lroundf( fval * pow10(it->cal.precision) );
// проверка на обрыв // проверка на обрыв
...@@ -325,7 +325,7 @@ float IOBase::processingFasAO( IOBase* it, SMInterface* shm, bool force ) ...@@ -325,7 +325,7 @@ float IOBase::processingFasAO( IOBase* it, SMInterface* shm, bool force )
if( it->rawdata ) if( it->rawdata )
{ {
float fval=0; float fval=0;
memcpy(&fval,&val, std::min(sizeof(val),sizeof(fval))); memcpy(&fval,&val, std::min(sizeof(val),sizeof(fval)));
return fval; return fval;
} }
...@@ -394,32 +394,32 @@ void IOBase::processingThreshold( IOBase* it, SMInterface* shm, bool force ) ...@@ -394,32 +394,32 @@ void IOBase::processingThreshold( IOBase* it, SMInterface* shm, bool force )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::string IOBase::initProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const std::string& defval ) std::string IOBase::initProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const std::string& defval )
{ {
if( !it.getProp(prefix+prop).empty() ) if( !it.getProp(prefix+prop).empty() )
return it.getProp(prefix+prop); return it.getProp(prefix+prop);
if( prefonly ) if( prefonly )
return defval; return defval;
if( !it.getProp(prop).empty() ) if( !it.getProp(prop).empty() )
return it.getProp(prop); return it.getProp(prop);
return defval; return defval;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int IOBase::initIntProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const int defval ) int IOBase::initIntProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const int defval )
{ {
string pp(prefix+prop); string pp(prefix+prop);
if( !it.getProp(pp).empty() ) if( !it.getProp(pp).empty() )
return it.getIntProp(pp); return it.getIntProp(pp);
if( prefonly ) if( prefonly )
return defval; return defval;
if( !it.getProp(prop).empty() ) if( !it.getProp(prop).empty() )
return it.getIntProp(prop); return it.getIntProp(prop);
return defval; return defval;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const std::string& prefix, bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const std::string& prefix,
...@@ -428,12 +428,12 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const ...@@ -428,12 +428,12 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const
int def_filtersize, float def_filterT, float def_lsparam, int def_filtersize, float def_filterT, float def_lsparam,
float def_iir_coeff_prev, float def_iir_coeff_new ) float def_iir_coeff_prev, float def_iir_coeff_new )
{ {
// Переопределять ID и name - нельзя..s // Переопределять ID и name - нельзя..s
string sname( it.getProp("name") ); string sname( it.getProp("name") );
ObjectId sid = DefaultObjectId; ObjectId sid = DefaultObjectId;
if( it.getProp("id").empty() ) if( it.getProp("id").empty() )
sid = conf->getSensorID(sname); sid = uniset_conf()->getSensorID(sname);
else else
sid = it.getPIntProp("id",DefaultObjectId); sid = it.getPIntProp("id",DefaultObjectId);
...@@ -448,16 +448,16 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const ...@@ -448,16 +448,16 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const
b->val_lock.setName(sname + "_lock"); b->val_lock.setName(sname + "_lock");
b->si.id = sid; b->si.id = sid;
b->si.node = conf->getLocalNode(); b->si.node = uniset_conf()->getLocalNode();
b->nofilter = initIntProp(it,"nofilter",prefix,init_prefix_only); b->nofilter = initIntProp(it,"nofilter",prefix,init_prefix_only);
b->ignore = initIntProp(it,"ioignore",prefix,init_prefix_only); b->ignore = initIntProp(it,"ioignore",prefix,init_prefix_only);
b->invert = initIntProp(it,"ioinvert",prefix,init_prefix_only); b->invert = initIntProp(it,"ioinvert",prefix,init_prefix_only);
b->defval = initIntProp(it,"default",prefix,init_prefix_only); b->defval = initIntProp(it,"default",prefix,init_prefix_only);
b->noprecision = initIntProp(it,"noprecision",prefix,init_prefix_only); b->noprecision = initIntProp(it,"noprecision",prefix,init_prefix_only);
b->value = b->defval; b->value = b->defval;
b->breaklim = initIntProp(it,"breaklim",prefix,init_prefix_only); b->breaklim = initIntProp(it,"breaklim",prefix,init_prefix_only);
b->rawdata = initIntProp(it,"rawdata",prefix,init_prefix_only); b->rawdata = initIntProp(it,"rawdata",prefix,init_prefix_only);
long msec = initIntProp(it,"debouncedelay",prefix,init_prefix_only, UniSetTimer::WaitUpTime); long msec = initIntProp(it,"debouncedelay",prefix,init_prefix_only, UniSetTimer::WaitUpTime);
b->ptDebounce.setTiming(msec); b->ptDebounce.setTiming(msec);
...@@ -585,7 +585,7 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const ...@@ -585,7 +585,7 @@ bool IOBase::initItem( IOBase* b, UniXML::iterator& it, SMInterface* shm, const
string tai(initProp(it,"threshold_aid",prefix,init_prefix_only)); string tai(initProp(it,"threshold_aid",prefix,init_prefix_only));
if( !tai.empty() ) if( !tai.empty() )
{ {
b->t_ai = conf->getSensorID(tai); b->t_ai = uniset_conf()->getSensorID(tai);
if( b->t_ai == DefaultObjectId ) if( b->t_ai == DefaultObjectId )
{ {
if( dlog && dlog->is_crit() ) if( dlog && dlog->is_crit() )
......
...@@ -10,6 +10,7 @@ using namespace UniSetTypes; ...@@ -10,6 +10,7 @@ using namespace UniSetTypes;
#define BEG_FUNC(name) \ #define BEG_FUNC(name) \
try \ try \
{ \ { \
auto conf = ui->getConf(); \
uniset_rwmutex_wrlock l(shmMutex); \ uniset_rwmutex_wrlock l(shmMutex); \
IONotifyController_i_var shm;\ IONotifyController_i_var shm;\
for( unsigned int i=0; i<conf->getRepeatCount(); i++)\ for( unsigned int i=0; i<conf->getRepeatCount(); i++)\
...@@ -33,6 +34,7 @@ using namespace UniSetTypes; ...@@ -33,6 +34,7 @@ using namespace UniSetTypes;
#define BEG_FUNC1(name) \ #define BEG_FUNC1(name) \
try \ try \
{ \ { \
auto conf = ui->getConf(); \
uniset_rwmutex_wrlock l(shmMutex); \ uniset_rwmutex_wrlock l(shmMutex); \
if( true ) \ if( true ) \
{ \ { \
...@@ -111,7 +113,7 @@ void SMInterface::setValue( UniSetTypes::ObjectId id, long value ) ...@@ -111,7 +113,7 @@ void SMInterface::setValue( UniSetTypes::ObjectId id, long value )
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = id; si.id = id;
si.node = conf->getLocalNode(); si.node = ui->getConf()->getLocalNode();
BEG_FUNC1(SMInterface::setValue) BEG_FUNC1(SMInterface::setValue)
ui->fastSetValue(si,value,myid); ui->fastSetValue(si,value,myid);
...@@ -137,7 +139,7 @@ void SMInterface::askSensor( UniSetTypes::ObjectId id, UniversalIO::UIOCommand c ...@@ -137,7 +139,7 @@ void SMInterface::askSensor( UniSetTypes::ObjectId id, UniversalIO::UIOCommand c
{ {
ConsumerInfo_var ci; ConsumerInfo_var ci;
ci->id = (backid==DefaultObjectId) ? myid : backid; ci->id = (backid==DefaultObjectId) ? myid : backid;
ci->node = conf->getLocalNode(); ci->node = ui->getConf()->getLocalNode();
if( ic ) if( ic )
{ {
...@@ -224,7 +226,7 @@ void SMInterface::localSetValue( IOController::IOStateList::iterator& it, ...@@ -224,7 +226,7 @@ void SMInterface::localSetValue( IOController::IOStateList::iterator& it,
// CHECK_IC_PTR(localSetValue) // CHECK_IC_PTR(localSetValue)
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = sid; si.id = sid;
si.node = conf->getLocalNode(); si.node = ui->getConf()->getLocalNode();
ic->localSetValue(it,si.id,value,sup_id); ic->localSetValue(it,si.id,value,sup_id);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -246,7 +248,7 @@ void SMInterface::localSetUndefinedState( IOController::IOStateList::iterator& i ...@@ -246,7 +248,7 @@ void SMInterface::localSetUndefinedState( IOController::IOStateList::iterator& i
{ {
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = sid; si.id = sid;
si.node = conf->getLocalNode(); si.node = ui->getConf()->getLocalNode();
setUndefinedState(si,undefined,myid); setUndefinedState(si,undefined,myid);
return; return;
} }
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2014-01-27+04:00 // generate timestamp: 2014-11-24+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include "Configuration.h" #include "Configuration.h"
#include "Exceptions.h" #include "Exceptions.h"
...@@ -38,24 +38,24 @@ idHeartBeat(DefaultObjectId), ...@@ -38,24 +38,24 @@ idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(0), confnode(0),
smReadyTimeout(0), smReadyTimeout(0),
activated(0), activated(false),
askPause(2000), askPause(2000),
end_private(false) end_private(false)
{ {
ucrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl; ucrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw Exception( string(myname+": init failed!!!") ); throw Exception( string(myname+": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
static const std::string init3_str( const std::string& s1, const std::string& s2, const std::string& s3 ) static const std::string init3_str( const std::string& s1, const std::string& s2, const std::string& s3 )
{ {
if( !s1.empty() ) if( !s1.empty() )
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
return s3; return s3;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& argprefix ): UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& argprefix ):
...@@ -73,74 +73,76 @@ idHeartBeat(DefaultObjectId), ...@@ -73,74 +73,76 @@ idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(0), activated(false),
askPause(conf->getPIntProp(cnode,"askPause",2000)), askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
end_private(false) end_private(false)
{ {
auto conf = uniset_conf();
if( UniSetTypes::findArgParam("--print-id-list",conf->getArgc(),conf->getArgv()) != -1 )
{
// abort();
} if( UniSetTypes::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
{
// abort();
}
if( getId() == DefaultObjectId )
{
ostringstream err;
err << "(UObject::init): Unknown ObjectID!";
throw SystemError( err.str() );
}
if( getId() == DefaultObjectId )
{
ostringstream err;
err << "(UObject::init): Unknown ObjectID!";
throw SystemError( err.str() );
}
UniXML::iterator it(cnode);
string heart = conf->getArgParam("--heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() )
{
idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId )
{
ostringstream err;
err << myname << ": не найден идентификатор для датчика 'HeartBeat' " << heart;
throw SystemError(err.str());
}
int heartbeatTime = conf->getArgPInt("--heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime()); UniXML::iterator it(cnode);
if( heartbeatTime>0 ) string heart = conf->getArgParam("--heartbeat-id",it.getProp("heartbeat_id"));
ptHeartBeat.setTiming(heartbeatTime); if( !heart.empty() )
else {
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId )
{
ostringstream err;
err << myname << ": не найден идентификатор для датчика 'HeartBeat' " << heart;
throw SystemError(err.str());
}
maxHeartBeat = conf->getArgPInt("--heartbeat-max",it.getProp("heartbeat_max"), 10); int heartbeatTime = conf->getArgPInt("--heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
} if( heartbeatTime>0 )
ptHeartBeat.setTiming(heartbeatTime);
else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
// Инициализация значений maxHeartBeat = conf->getArgPInt("--heartbeat-max",it.getProp("heartbeat_max"), 10);
}
sleep_msec = conf->getArgPInt("--sleep-msec","150", 150);
resetMsgTime = conf->getPIntProp(cnode,"resetMsgTime", 2000); // Инициализация значений
ptResetMsg.setTiming(resetMsgTime);
sleep_msec = conf->getArgPInt("--sleep-msec","150", 150);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout",""); resetMsgTime = conf->getPIntProp(cnode,"resetMsgTime", 2000);
if( smReadyTimeout == 0 ) ptResetMsg.setTiming(resetMsgTime);
smReadyTimeout = 60000;
else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime;
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),"")); smReadyTimeout = conf->getArgInt("--sm-ready-timeout","");
if( smReadyTimeout == 0 )
smReadyTimeout = 60000;
else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime;
activateTimeout = conf->getArgPInt("--activate-timeout", 20000); smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),""));
int msec = conf->getArgPInt("--startup-timeout", 10000); activateTimeout = conf->getArgPInt("--activate-timeout", 20000);
ptStartUpTimeout.setTiming(msec);
// ===================== <variables> ===================== int msec = conf->getArgPInt("--startup-timeout", 10000);
ptStartUpTimeout.setTiming(msec);
// ===================== end of <variables> =====================
// ===================== <variables> =====================
// ===================== end of <variables> =====================
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -151,36 +153,36 @@ UObject_SK::~UObject_SK() ...@@ -151,36 +153,36 @@ UObject_SK::~UObject_SK()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateValues() void UObject_SK::updateValues()
{ {
// Опрашиваем все входы... // Опрашиваем все входы...
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updatePreviousValues() void UObject_SK::updatePreviousValues()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::checkSensors() void UObject_SK::checkSensors()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::alarm( UniSetTypes::ObjectId _code, bool _state ) bool UObject_SK::alarm( UniSetTypes::ObjectId _code, bool _state )
{ {
if( _code == UniSetTypes::DefaultObjectId ) if( _code == UniSetTypes::DefaultObjectId )
{ {
ucrit << getName() ucrit << getName()
<< "(alarm): попытка послать сообщение с DefaultObjectId" << "(alarm): попытка послать сообщение с DefaultObjectId"
<< endl; << endl;
return false; return false;
} }
ulog1 << getName() << "(alarm): " << ( _state ? "SEND " : "RESET " ) << endl; ulog1 << getName() << "(alarm): " << ( _state ? "SEND " : "RESET " ) << endl;
ulog1 << " not found MessgeOID?!!" << endl; ulog1 << " not found MessgeOID?!!" << endl;
return false; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
...@@ -191,11 +193,11 @@ void UObject_SK::resetMsg() ...@@ -191,11 +193,11 @@ void UObject_SK::resetMsg()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::testMode( bool _state ) void UObject_SK::testMode( bool _state )
{ {
if( !_state ) if( !_state )
return; return;
// отключаем все выходы // отключаем все выходы
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -204,139 +206,139 @@ void UObject_SK::testMode( bool _state ) ...@@ -204,139 +206,139 @@ void UObject_SK::testMode( bool _state )
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UObject_SK::init_dlog( DebugStream& d ) void UObject_SK::init_dlog( DebugStream& d )
{ {
UObject_SK::mylog = d; UObject_SK::mylog = d;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UObject_SK::processingMessage( UniSetTypes::VoidMessage* _msg ) void UObject_SK::processingMessage( UniSetTypes::VoidMessage* _msg )
{ {
try try
{ {
switch( _msg->type ) switch( _msg->type )
{ {
case Message::SensorInfo: case Message::SensorInfo:
preSensorInfo( reinterpret_cast<SensorMessage*>(_msg) ); preSensorInfo( reinterpret_cast<SensorMessage*>(_msg) );
break; break;
case Message::Timer: case Message::Timer:
preTimerInfo( reinterpret_cast<TimerMessage*>(_msg) ); preTimerInfo( reinterpret_cast<TimerMessage*>(_msg) );
break; break;
case Message::SysCommand: case Message::SysCommand:
sysCommand( reinterpret_cast<SystemMessage*>(_msg) ); sysCommand( reinterpret_cast<SystemMessage*>(_msg) );
break; break;
default: default:
break; break;
} }
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
ucrit << myname << "(processingMessage): " << ex << endl; ucrit << myname << "(processingMessage): " << ex << endl;
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::sysCommand( const SystemMessage* _sm ) void UObject_SK::sysCommand( const SystemMessage* _sm )
{ {
switch( _sm->command ) switch( _sm->command )
{ {
case SystemMessage::WatchDog: case SystemMessage::WatchDog:
ulog << myname << "(sysCommand): WatchDog" << endl; ulog << myname << "(sysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() ) if( !active || !ptStartUpTimeout.checkTime() )
{ {
uwarn << myname << "(sysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl; uwarn << myname << "(sysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break; break;
} }
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
waitSM(smReadyTimeout); waitSM(smReadyTimeout);
ptStartUpTimeout.reset(); ptStartUpTimeout.reset();
// т.к. для io-переменных важно соблюдать последовательность! // т.к. для io-переменных важно соблюдать последовательность!
// сперва обновить входы.. а потом уже выходы // сперва обновить входы.. а потом уже выходы
updateValues(); updateValues();
updateOutputs(true); // принудительное обновление выходов updateOutputs(true); // принудительное обновление выходов
preAskSensors(UniversalIO::UIONotify); preAskSensors(UniversalIO::UIONotify);
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
active = true; active = true;
break; break;
} }
case SystemMessage::FoldUp: case SystemMessage::FoldUp:
case SystemMessage::Finish: case SystemMessage::Finish:
preAskSensors(UniversalIO::UIODontNotify); preAskSensors(UniversalIO::UIODontNotify);
askSensors(UniversalIO::UIODontNotify); askSensors(UniversalIO::UIODontNotify);
break; break;
case SystemMessage::LogRotate: case SystemMessage::LogRotate:
{ {
// переоткрываем логи // переоткрываем логи
mylog << myname << "(sysCommand): logRotate" << endl; mylog << myname << "(sysCommand): logRotate" << endl;
string fname( mylog.getLogFile() ); string fname( mylog.getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
mylog.logFile(fname.c_str(),true); mylog.logFile(fname.c_str(),true);
mylog << myname << "(sysCommand): ***************** mylog LOG ROTATE *****************" << endl; mylog << myname << "(sysCommand): ***************** mylog LOG ROTATE *****************" << endl;
} }
} }
break; break;
default: default:
break; break;
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::sigterm( int signo ) void UObject_SK::sigterm( int signo )
{ {
UniSetObject::sigterm(signo); UniSetObject::sigterm(signo);
active = false; active = false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::activateObject() bool UObject_SK::activateObject()
{ {
// блокирование обработки Startup // блокирование обработки Startup
// пока не пройдёт инициализация датчиков // пока не пройдёт инициализация датчиков
// см. sysCommand() // см. sysCommand()
{ {
activated = false; activated = false;
UniSetObject::activateObject(); UniSetObject::activateObject();
activated = true; activated = true;
} }
return true; return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preTimerInfo( const UniSetTypes::TimerMessage* _tm ) void UObject_SK::preTimerInfo( const UniSetTypes::TimerMessage* _tm )
{ {
timerInfo(_tm); timerInfo(_tm);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
{ {
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
_testID = smTestID; _testID = smTestID;
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
return; return;
uinfo << myname << "(waitSM): waiting SM ready " uinfo << myname << "(waitSM): waiting SM ready "
<< wait_msec << " msec" << wait_msec << " msec"
<< " testID=" << _testID << endl; << " testID=" << _testID << endl;
if( !ui.waitReady(_testID,wait_msec) ) if( !ui.waitReady(_testID,wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
<< wait_msec << " мсек"; << wait_msec << " мсек";
ucrit << err.str() << endl; ucrit << err.str() << endl;
terminate(); terminate();
abort(); abort();
// kill(SIGTERM,getpid()); // прерываем (перезапускаем) процесс... // kill(SIGTERM,getpid()); // прерываем (перезапускаем) процесс...
throw SystemError(err.str()); throw SystemError(err.str());
} }
} }
...@@ -345,153 +347,152 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -345,153 +347,152 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void UObject_SK::callback() void UObject_SK::callback()
{ {
if( !active ) if( !active )
return; return;
try try
{ {
// проверка таймеров // проверка таймеров
checkTimers(this); checkTimers(this);
if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) ) if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) )
{ {
// cout << myname << ": ********* reset messages *********" << endl; // cout << myname << ": ********* reset messages *********" << endl;
resetMsg(); resetMsg();
} }
// обработка сообщений (таймеров и т.п.) // обработка сообщений (таймеров и т.п.)
for( unsigned int i=0; i<20; i++ ) for( unsigned int i=0; i<20; i++ )
{ {
if( !receiveMessage(msg) ) if( !receiveMessage(msg) )
break; break;
processingMessage(&msg); processingMessage(&msg);
updateOutputs(false); updateOutputs(false);
// updatePreviousValues(); // updatePreviousValues();
} }
// Выполнение шага программы // Выполнение шага программы
step(); step();
// "сердцебиение" // "сердцебиение"
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() ) if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() )
{ {
ui.setValue(idHeartBeat,maxHeartBeat,UniversalIO::AI); ui.setValue(idHeartBeat,maxHeartBeat,UniversalIO::AI);
ptHeartBeat.reset(); ptHeartBeat.reset();
} }
// обновление выходов // обновление выходов
updateOutputs(false); updateOutputs(false);
updatePreviousValues(); updatePreviousValues();
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
ucrit << myname << "(execute): " << ex << endl; ucrit << myname << "(execute): " << ex << endl;
} }
catch(CORBA::SystemException& ex) catch(CORBA::SystemException& ex)
{ {
ucrit << myname << "(execute): СORBA::SystemException: " ucrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
} }
catch(...) catch(...)
{ {
ucrit << myname << "(execute): catch ..." << endl; ucrit << myname << "(execute): catch ..." << endl;
} }
if( !active ) if( !active )
return; return;
msleep( sleep_msec ); msleep( sleep_msec );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val ) void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val )
{ {
// ui.setState(sid,state);
ui.setValue(_sid,_val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm ) void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm )
{ {
sensorInfo(_sm); sensorInfo(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node ) void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node )
{ {
ui.askRemoteSensor(_sid,_cmd,_node,getId()); ui.askRemoteSensor(_sid,_cmd,_node,getId());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
{ {
try try
{ {
ucrit << myname << "(getValue): Обращение к неизвестному датчику sid="
<< _sid << endl; return ui.getValue(_sid);
} }
catch(Exception& ex) catch(Exception& ex)
{ {
ucrit << myname << "(getValue): " << ex << endl; ucrit << myname << "(getValue): " << ex << endl;
throw; throw;
} }
return 0;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !activated && !ptAct.checkTime() )
{ {
cout << myname << "(preAskSensors): wait activate..." << endl; cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300); msleep(300);
if( activated ) if( activated )
break; break;
} }
if( !activated ) if( !activated )
ucrit << myname ucrit << myname
<< "(preAskSensors): ************* don`t activated?! ************" << endl; << "(preAskSensors): ************* don`t activated?! ************" << endl;
for( ;; ) for( ;; )
{ {
try try
{ {
return; return;
} }
catch(SystemError& err) catch(SystemError& err)
{ {
ucrit << myname << "(preAskSensors): " << err << endl; ucrit << myname << "(preAskSensors): " << err << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
ucrit << myname << "(preAskSensors): " << ex << endl; ucrit << myname << "(preAskSensors): " << ex << endl;
} }
catch(...) catch(...)
{ {
ucrit << myname << "(preAskSensors): catch(...)" << endl; ucrit << myname << "(preAskSensors): catch(...)" << endl;
} }
msleep(askPause); msleep(askPause);
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) void UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state )
{ {
// блокируем сброс (т.к. он автоматически по таймеру) // блокируем сброс (т.к. он автоматически по таймеру)
if( !_state ) if( !_state )
{ {
ptResetMsg.reset(); ptResetMsg.reset();
return; return;
} }
alarm( _code, _state ); alarm( _code, _state );
ptResetMsg.reset(); ptResetMsg.reset();
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -39,8 +39,8 @@ int main(int argc, const char **argv) ...@@ -39,8 +39,8 @@ int main(int argc, const char **argv)
int num = conf->getArgPInt("--numproc",1); int num = conf->getArgPInt("--numproc",1);
for( int i=1; i<=num; i++ ) for( int i=1; i<=num; i++ )
{ {
ostringstream s; ostringstream s;
s << "TestProc" << i; s << "TestProc" << i;
......
...@@ -11,55 +11,55 @@ using namespace UniSetExtensions; ...@@ -11,55 +11,55 @@ using namespace UniSetExtensions;
TEST_CASE("Calibration","[calibration]") TEST_CASE("Calibration","[calibration]")
{ {
Calibration* cal = buildCalibrationDiagram("testcal"); Calibration* cal = buildCalibrationDiagram("testcal");
CHECK( cal!=0 ); CHECK( cal!=0 );
SECTION("getValue") SECTION("getValue")
{ {
REQUIRE( cal->getValue(1500,true) == 600 ); REQUIRE( cal->getValue(1500,true) == 600 );
REQUIRE( cal->getValue(1500,false) == Calibration::outOfRange ); REQUIRE( cal->getValue(1500,false) == Calibration::outOfRange );
REQUIRE( cal->getValue(1000) == 600 ); REQUIRE( cal->getValue(1000) == 600 );
REQUIRE( cal->getValue(933) == 466 ); REQUIRE( cal->getValue(933) == 466 );
REQUIRE( cal->getValue(800) == 300 ); REQUIRE( cal->getValue(800) == 300 );
REQUIRE( cal->getValue(700) == 250 ); REQUIRE( cal->getValue(700) == 250 );
REQUIRE( cal->getValue(600) == 200 ); REQUIRE( cal->getValue(600) == 200 );
REQUIRE( cal->getValue(650) > 200 ); REQUIRE( cal->getValue(650) > 200 );
REQUIRE( cal->getValue(650) < 250 ); REQUIRE( cal->getValue(650) < 250 );
REQUIRE( cal->getValue(200)== 60 ); REQUIRE( cal->getValue(200)== 60 );
REQUIRE( cal->getValue(50) == 20 ); REQUIRE( cal->getValue(50) == 20 );
REQUIRE( cal->getValue(10) == 0 ); REQUIRE( cal->getValue(10) == 0 );
REQUIRE( cal->getValue(5) == 0 ); REQUIRE( cal->getValue(5) == 0 );
REQUIRE( cal->getValue(0) == 0 ); REQUIRE( cal->getValue(0) == 0 );
REQUIRE( cal->getValue(-5) == 0 ); REQUIRE( cal->getValue(-5) == 0 );
REQUIRE( cal->getValue(-10) == 0 ); REQUIRE( cal->getValue(-10) == 0 );
REQUIRE( cal->getValue(-50) == -20 ); REQUIRE( cal->getValue(-50) == -20 );
REQUIRE( cal->getValue(-500) == -80 ); REQUIRE( cal->getValue(-500) == -80 );
REQUIRE( cal->getValue(-900) == -250 ); REQUIRE( cal->getValue(-900) == -250 );
REQUIRE( cal->getValue(-1000) == -300 ); REQUIRE( cal->getValue(-1000) == -300 );
REQUIRE( cal->getValue(-1050,true) == -300 ); REQUIRE( cal->getValue(-1050,true) == -300 );
REQUIRE( cal->getValue(-1050,false) == Calibration::outOfRange ); REQUIRE( cal->getValue(-1050,false) == Calibration::outOfRange );
} }
SECTION("Other function") SECTION("Other function")
{ {
REQUIRE( cal->getMinValue() == -300 ); REQUIRE( cal->getMinValue() == -300 );
REQUIRE( cal->getMaxValue() == 600 ); REQUIRE( cal->getMaxValue() == 600 );
REQUIRE( cal->getLeftValue() == -300 ); REQUIRE( cal->getLeftValue() == -300 );
REQUIRE( cal->getRightValue() == 600 ); REQUIRE( cal->getRightValue() == 600 );
REQUIRE( cal->getRawValue(-80) == -500 ); REQUIRE( cal->getRawValue(-80) == -500 );
REQUIRE( cal->getRawValue(-500,false) == Calibration::outOfRange ); REQUIRE( cal->getRawValue(-500,false) == Calibration::outOfRange );
REQUIRE( cal->getRawValue(-500,true) == -1000 ); REQUIRE( cal->getRawValue(-500,true) == -1000 );
REQUIRE( cal->getRawValue(150) == 500 ); REQUIRE( cal->getRawValue(150) == 500 );
REQUIRE( cal->getRawValue(700,false) == Calibration::outOfRange ); REQUIRE( cal->getRawValue(700,false) == Calibration::outOfRange );
REQUIRE( cal->getRawValue(700,true) == 1000 ); REQUIRE( cal->getRawValue(700,true) == 1000 );
REQUIRE( cal->getMinRaw() == -1000 ); REQUIRE( cal->getMinRaw() == -1000 );
REQUIRE( cal->getMaxRaw() == 1000 ); REQUIRE( cal->getMaxRaw() == 1000 );
REQUIRE( cal->getLeftRaw() == -1000 ); REQUIRE( cal->getLeftRaw() == -1000 );
REQUIRE( cal->getRightRaw() == 1000 ); REQUIRE( cal->getRightRaw() == 1000 );
} }
} }
...@@ -10,86 +10,86 @@ using namespace UniSetExtensions; ...@@ -10,86 +10,86 @@ using namespace UniSetExtensions;
TEST_CASE("DigitalFilter","[DigitalFilter]") TEST_CASE("DigitalFilter","[DigitalFilter]")
{ {
SECTION("..") SECTION("..")
{ {
WARN("List of tests for [DigitalFilter] is not complete (is not sufficient)"); WARN("List of tests for [DigitalFilter] is not complete (is not sufficient)");
}
SECTION("Default constructor (const data)")
{
DigitalFilter df;
DigitalFilter df10(10);
REQUIRE( df.size() == 5 );
REQUIRE( df10.size() == 10 );
for( int i=0; i<20; i++ )
{
df.add(50);
df10.add(50);
}
REQUIRE( df.current1() == 50 );
REQUIRE( df.currentRC() == 50 );
REQUIRE( df.currentMedian() == 50 );
REQUIRE( df10.current1() == 50 );
REQUIRE( df10.currentRC() == 50 );
REQUIRE( df10.currentMedian() == 50 );
} }
SECTION("Median filter") SECTION("Default constructor (const data)")
{ {
DigitalFilter df; DigitalFilter df;
for( int i=0; i<20; i++ ) DigitalFilter df10(10);
df.median(50);
REQUIRE( df.size() == 5 );
REQUIRE( df.currentMedian() == 50 ); REQUIRE( df10.size() == 10 );
DigitalFilter df1; for( int i=0; i<20; i++ )
DigitalFilter df10; {
vector<long> dat={0,234,356,344,234,320,250,250,250,250,250,250,250,251,252,251,252,252,250}; df.add(50);
for( auto v: dat ) df10.add(50);
{ }
df1.median(v);
df10.median(v); REQUIRE( df.current1() == 50 );
} REQUIRE( df.currentRC() == 50 );
REQUIRE( df.currentMedian() == 50 );
REQUIRE( df1.currentMedian() == 252 );
REQUIRE( df10.currentMedian() == 252 ); REQUIRE( df10.current1() == 50 );
REQUIRE( df10.currentRC() == 50 );
REQUIRE( df10.currentMedian() == 50 );
}
SECTION("Median filter")
{
DigitalFilter df;
for( int i=0; i<20; i++ )
df.median(50);
REQUIRE( df.currentMedian() == 50 );
DigitalFilter df1;
DigitalFilter df10;
vector<long> dat={0,234,356,344,234,320,250,250,250,250,250,250,250,251,252,251,252,252,250};
for( auto v: dat )
{
df1.median(v);
df10.median(v);
}
REQUIRE( df1.currentMedian() == 252 );
REQUIRE( df10.currentMedian() == 252 );
} }
SECTION("filter1") SECTION("filter1")
{ {
DigitalFilter df1; DigitalFilter df1;
DigitalFilter df10; DigitalFilter df10;
// "выброс" за СКО отсекается.. // "выброс" за СКО отсекается..
vector<long> dat={10,12,10,-8,10,10,-230,10,10}; vector<long> dat={10,12,10,-8,10,10,-230,10,10};
for( auto v: dat ) for( auto v: dat )
{ {
df1.add(v); df1.add(v);
df10.add(v); df10.add(v);
} }
REQUIRE( df1.current1() == 10 ); REQUIRE( df1.current1() == 10 );
REQUIRE( df10.current1() == 10 ); REQUIRE( df10.current1() == 10 );
} }
SECTION("filterRC") SECTION("filterRC")
{ {
double Ti = 0.09; // постоянная времени фильтра double Ti = 0.09; // постоянная времени фильтра
DigitalFilter df1(5,Ti); DigitalFilter df1(5,Ti);
DigitalFilter df10(10,Ti); DigitalFilter df10(10,Ti);
vector<long> dat={10,12,10,-8,10,10,-230,10,10,12,12,10,-8,-8,10,11,9,11,11,11,9,12,12,10,10,11,-4560,12,10,10,11,10,10,10,10}; vector<long> dat={10,12,10,-8,10,10,-230,10,10,12,12,10,-8,-8,10,11,9,11,11,11,9,12,12,10,10,11,-4560,12,10,10,11,10,10,10,10};
for( auto v: dat ) for( auto v: dat )
{ {
df1.add(v); df1.add(v);
df10.add(v); df10.add(v);
msleep(30); msleep(30);
} }
REQUIRE( df1.currentRC() == 10 ); REQUIRE( df1.currentRC() == 10 );
REQUIRE( df10.currentRC() == 10 ); REQUIRE( df10.currentRC() == 10 );
} }
} }
...@@ -11,7 +11,7 @@ using namespace UniSetExtensions; ...@@ -11,7 +11,7 @@ using namespace UniSetExtensions;
TEST_CASE("IOBase","[IOBase class tests]") TEST_CASE("IOBase","[IOBase class tests]")
{ {
CHECK( UniSetTypes::conf != 0 ); CHECK( uniset_conf()!=nullptr );
SECTION("Default constructor (const data)") SECTION("Default constructor (const data)")
{ {
...@@ -58,14 +58,15 @@ TEST_CASE("IOBase","[IOBase class tests]") ...@@ -58,14 +58,15 @@ TEST_CASE("IOBase","[IOBase class tests]")
SECTION("Init from xml") SECTION("Init from xml")
{ {
auto conf = uniset_conf();
xmlNode* cnode = conf->getNode("iobasetest"); xmlNode* cnode = conf->getNode("iobasetest");
CHECK( cnode != NULL ); CHECK( cnode != NULL );
UniXML::iterator it(cnode); UniXML::iterator it(cnode);
UInterface ui; UInterface ui;
ObjectId shmID = conf->getControllerID("SharedMemory"); ObjectId shmID = conf->getControllerID("SharedMemory");
CHECK( shmID != DefaultObjectId ); CHECK( shmID != DefaultObjectId );
SMInterface shm(shmID,&ui,DefaultObjectId); SMInterface shm(shmID,&ui,DefaultObjectId);
IOBase ib; IOBase ib;
IOBase::initItem(&ib,it,&shm,"",false); IOBase::initItem(&ib,it,&shm,"",false);
CHECK( ib.si.id == 1 ); CHECK( ib.si.id == 1 );
...@@ -76,156 +77,156 @@ TEST_CASE("IOBase","[IOBase class tests]") ...@@ -76,156 +77,156 @@ TEST_CASE("IOBase","[IOBase class tests]")
CHECK( ib.cal.maxRaw == 100 ); CHECK( ib.cal.maxRaw == 100 );
CHECK( ib.cal.minCal == 0 ); CHECK( ib.cal.minCal == 0 );
CHECK( ib.cal.maxCal == 50 ); CHECK( ib.cal.maxCal == 50 );
} }
SECTION("Debounce function") SECTION("Debounce function")
{ {
IOBase ib; IOBase ib;
ib.ptDebounce.setTiming(100); ib.ptDebounce.setTiming(100);
// Проверка установки сигнала (с дребезгом) // Проверка установки сигнала (с дребезгом)
CHECK_FALSE( ib.check_debounce(true) ); CHECK_FALSE( ib.check_debounce(true) );
msleep(20); msleep(20);
CHECK_FALSE( ib.check_debounce(false) ); CHECK_FALSE( ib.check_debounce(false) );
CHECK_FALSE( ib.check_debounce(true) ); CHECK_FALSE( ib.check_debounce(true) );
CHECK_FALSE( ib.check_debounce(false) ); CHECK_FALSE( ib.check_debounce(false) );
msleep(10); msleep(10);
CHECK_FALSE( ib.check_debounce(true) ); CHECK_FALSE( ib.check_debounce(true) );
msleep(40); msleep(40);
CHECK_FALSE( ib.check_debounce(false) ); CHECK_FALSE( ib.check_debounce(false) );
msleep(10); msleep(10);
CHECK_FALSE( ib.check_debounce(true) ); CHECK_FALSE( ib.check_debounce(true) );
msleep(30); msleep(30);
CHECK( ib.check_debounce(true) ); // сработал.. CHECK( ib.check_debounce(true) ); // сработал..
// Проверка сброса сигнала (с дребезгом) // Проверка сброса сигнала (с дребезгом)
msleep(30); msleep(30);
CHECK( ib.check_debounce(true) ); CHECK( ib.check_debounce(true) );
CHECK( ib.check_debounce(false) ); CHECK( ib.check_debounce(false) );
msleep(20); msleep(20);
CHECK( ib.check_debounce(false) ); CHECK( ib.check_debounce(false) );
msleep(20); msleep(20);
CHECK( ib.check_debounce(false) ); CHECK( ib.check_debounce(false) );
CHECK( ib.check_debounce(true) ); CHECK( ib.check_debounce(true) );
CHECK( ib.check_debounce(false) ); CHECK( ib.check_debounce(false) );
CHECK( ib.check_debounce(true) ); CHECK( ib.check_debounce(true) );
CHECK( ib.check_debounce(false) ); CHECK( ib.check_debounce(false) );
msleep(80); msleep(80);
CHECK_FALSE( ib.check_debounce(false) ); // сбросился CHECK_FALSE( ib.check_debounce(false) ); // сбросился
// Проверка "устойчивости" // Проверка "устойчивости"
msleep(30); msleep(30);
CHECK_FALSE( ib.check_debounce(true) ); CHECK_FALSE( ib.check_debounce(true) );
msleep(10); msleep(10);
CHECK_FALSE( ib.check_debounce(false) ); CHECK_FALSE( ib.check_debounce(false) );
msleep(90); msleep(90);
CHECK_FALSE( ib.check_debounce(false) ); CHECK_FALSE( ib.check_debounce(false) );
} }
SECTION("On delay..") SECTION("On delay..")
{ {
IOBase ib; IOBase ib;
ib.ptOnDelay.setTiming(100); ib.ptOnDelay.setTiming(100);
// простое срабатывание.. // простое срабатывание..
CHECK_FALSE( ib.check_on_delay(true) ); CHECK_FALSE( ib.check_on_delay(true) );
msleep(50); msleep(50);
CHECK_FALSE( ib.check_on_delay(true) ); CHECK_FALSE( ib.check_on_delay(true) );
msleep(60); msleep(60);
CHECK( ib.check_on_delay(true) ); CHECK( ib.check_on_delay(true) );
// сброс "без задержки" // сброс "без задержки"
CHECK_FALSE( ib.check_on_delay(false) ); CHECK_FALSE( ib.check_on_delay(false) );
// задержка засекается каждый раз при переходе "FALSE" --> "TRUE" // задержка засекается каждый раз при переходе "FALSE" --> "TRUE"
CHECK_FALSE( ib.check_on_delay(true) ); CHECK_FALSE( ib.check_on_delay(true) );
msleep(90); msleep(90);
CHECK_FALSE( ib.check_on_delay(false) ); CHECK_FALSE( ib.check_on_delay(false) );
msleep(20); msleep(20);
CHECK_FALSE( ib.check_on_delay(false) ); CHECK_FALSE( ib.check_on_delay(false) );
CHECK_FALSE( ib.check_on_delay(true) ); CHECK_FALSE( ib.check_on_delay(true) );
msleep(110); msleep(110);
CHECK( ib.check_on_delay(true) ); CHECK( ib.check_on_delay(true) );
} }
SECTION("Off delay..") SECTION("Off delay..")
{ {
IOBase ib; IOBase ib;
ib.ptOffDelay.setTiming(100); ib.ptOffDelay.setTiming(100);
// простое срабатывание.. // простое срабатывание..
CHECK( ib.check_off_delay(true) ); CHECK( ib.check_off_delay(true) );
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(50); msleep(50);
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(60); msleep(60);
CHECK_FALSE( ib.check_off_delay(false) ); CHECK_FALSE( ib.check_off_delay(false) );
// устновка "без задержки" // устновка "без задержки"
CHECK( ib.check_off_delay(true) ); CHECK( ib.check_off_delay(true) );
// задержка засекается каждый раз при переходе "TRUE" --> "FALSE" // задержка засекается каждый раз при переходе "TRUE" --> "FALSE"
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(90); msleep(90);
CHECK( ib.check_off_delay(true) ); CHECK( ib.check_off_delay(true) );
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(20); msleep(20);
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(50); msleep(50);
CHECK( ib.check_off_delay(false) ); CHECK( ib.check_off_delay(false) );
msleep(40); msleep(40);
CHECK_FALSE( ib.check_off_delay(false) ); CHECK_FALSE( ib.check_off_delay(false) );
} }
SECTION("Front '0-->1'") SECTION("Front '0-->1'")
{ {
IOBase ib; IOBase ib;
ib.front_type = IOBase::ft01; ib.front_type = IOBase::ft01;
ib.front = true; ib.front = true;
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK( ib.check_front(false) ); CHECK( ib.check_front(false) );
CHECK( ib.check_front(false) ); CHECK( ib.check_front(false) );
CHECK_FALSE( ib.check_front(true) ); CHECK_FALSE( ib.check_front(true) );
CHECK_FALSE( ib.check_front(true) ); CHECK_FALSE( ib.check_front(true) );
CHECK_FALSE( ib.check_front(false) ); CHECK_FALSE( ib.check_front(false) );
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
} }
SECTION("Front '1-->0'") SECTION("Front '1-->0'")
{ {
IOBase ib; IOBase ib;
ib.front_type = IOBase::ft10; ib.front_type = IOBase::ft10;
ib.front = true; ib.front = true;
CHECK_FALSE( ib.check_front(true) ); CHECK_FALSE( ib.check_front(true) );
CHECK_FALSE( ib.check_front(true) ); CHECK_FALSE( ib.check_front(true) );
CHECK( ib.check_front(false) ); CHECK( ib.check_front(false) );
CHECK( ib.check_front(false) ); CHECK( ib.check_front(false) );
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK_FALSE( ib.check_front(false) ); CHECK_FALSE( ib.check_front(false) );
} }
SECTION("Front 'unkown' (off)") SECTION("Front 'unkown' (off)")
{ {
IOBase ib; IOBase ib;
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK_FALSE( ib.check_front(false) ); CHECK_FALSE( ib.check_front(false) );
CHECK( ib.check_front(true) ); CHECK( ib.check_front(true) );
CHECK_FALSE( ib.check_front(false) ); CHECK_FALSE( ib.check_front(false) );
} }
SECTION("'Channel break' function") SECTION("'Channel break' function")
{ {
IOBase ib; IOBase ib;
// просто проверка.. при отключнном breaklim.. (всегда FALSE) // просто проверка.. при отключнном breaklim.. (всегда FALSE)
CHECK_FALSE( ib.check_channel_break(100) ); CHECK_FALSE( ib.check_channel_break(100) );
CHECK_FALSE( ib.check_channel_break(-100) ); CHECK_FALSE( ib.check_channel_break(-100) );
CHECK_FALSE( ib.check_channel_break(0) ); CHECK_FALSE( ib.check_channel_break(0) );
const int breakValue = 200; const int breakValue = 200;
ib.breaklim = breakValue; ib.breaklim = breakValue;
CHECK( ib.check_channel_break(breakValue - 10) ); CHECK( ib.check_channel_break(breakValue - 10) );
CHECK( ib.check_channel_break(-breakValue) ); CHECK( ib.check_channel_break(-breakValue) );
CHECK( ib.check_channel_break(0) ); CHECK( ib.check_channel_break(0) );
CHECK_FALSE( ib.check_channel_break(breakValue+1) ); CHECK_FALSE( ib.check_channel_break(breakValue+1) );
CHECK_FALSE( ib.check_channel_break(breakValue) ); CHECK_FALSE( ib.check_channel_break(breakValue) );
} }
} }
...@@ -6,21 +6,21 @@ ...@@ -6,21 +6,21 @@
int main( int argc, char* argv[] ) int main( int argc, char* argv[] )
{ {
Catch::Session session; Catch::Session session;
try try
{ {
UniSetTypes::uniset_init(argc,argv); UniSetTypes::uniset_init(argc,argv);
int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore ); int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore );
if( returnCode != 0 ) // Indicates a command line error if( returnCode != 0 ) // Indicates a command line error
return returnCode; return returnCode;
return session.run(); return session.run();
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
{ {
std::cerr << ex << std::endl; std::cerr << ex << std::endl;
} }
return 1; return 1;
} }
...@@ -14,23 +14,23 @@ using namespace UniSetExtensions; ...@@ -14,23 +14,23 @@ using namespace UniSetExtensions;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char* argv[] ) int main(int argc, char* argv[] )
{ {
Catch::Session session; Catch::Session session;
if( argc>1 && ( strcmp(argv[1],"--help")==0 || strcmp(argv[1],"-h")==0 ) ) if( argc>1 && ( strcmp(argv[1],"--help")==0 || strcmp(argv[1],"-h")==0 ) )
{ {
cout << "--confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl; cout << "--confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
SharedMemory::help_print(argc, argv); SharedMemory::help_print(argc, argv);
cout << endl << endl << "--------------- CATCH HELP --------------" << endl; cout << endl << endl << "--------------- CATCH HELP --------------" << endl;
session.showHelp("test_with_sm"); session.showHelp("test_with_sm");
return 0; return 0;
} }
int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore ); int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore );
if( returnCode != 0 ) // Indicates a command line error if( returnCode != 0 ) // Indicates a command line error
return returnCode; return returnCode;
try try
{ {
uniset_init(argc,argv); uniset_init(argc,argv);
/* /*
conf->initDebug(dlog,"dlog"); conf->initDebug(dlog,"dlog");
string logfilename = conf->getArgParam("--logfile", "smemory.log"); string logfilename = conf->getArgParam("--logfile", "smemory.log");
...@@ -52,18 +52,18 @@ int main(int argc, char* argv[] ) ...@@ -52,18 +52,18 @@ int main(int argc, char* argv[] )
int tout = 6000; int tout = 6000;
PassiveTimer pt(tout); PassiveTimer pt(tout);
while( !pt.checkTime() && !act->exist() ) while( !pt.checkTime() && !act->exist() )
msleep(100); msleep(100);
if( !act->exist() ) if( !act->exist() )
{ {
cerr << "(tests_with_sm): SharedMemory not exist! (timeout=" << tout << ")" << endl; cerr << "(tests_with_sm): SharedMemory not exist! (timeout=" << tout << ")" << endl;
return 1; return 1;
} }
int ret = session.run(); int ret = session.run();
act->oaDestroy(); act->oaDestroy();
return ret; return ret;
} }
catch( SystemError& err ) catch( SystemError& err )
{ {
......
...@@ -9,206 +9,208 @@ using namespace UniSetTypes; ...@@ -9,206 +9,208 @@ using namespace UniSetTypes;
TEST_CASE("UInterface","[UInterface]") TEST_CASE("UInterface","[UInterface]")
{ {
CHECK( conf!=0 ); CHECK( uniset_conf()!=nullptr );
std::string sidName("Input1_S"); std::string sidName("Input1_S");
std::string aidName("AI_AS"); std::string aidName("AI_AS");
ObjectId testOID = conf->getObjectID("TestProc"); auto conf = uniset_conf();
CHECK( testOID != DefaultObjectId );
ObjectId testOID = conf->getObjectID("TestProc");
ObjectId sid = conf->getSensorID(sidName); CHECK( testOID != DefaultObjectId );
CHECK( sid != DefaultObjectId );
ObjectId sid = conf->getSensorID(sidName);
ObjectId aid = conf->getSensorID(aidName); CHECK( sid != DefaultObjectId );
CHECK( aid != DefaultObjectId );
ObjectId aid = conf->getSensorID(aidName);
UInterface ui; CHECK( aid != DefaultObjectId );
CHECK( ui.getObjectIndex() != nullptr ); UInterface ui;
CHECK( ui.getConf() == UniSetTypes::conf );
CHECK( ui.getObjectIndex() != nullptr );
REQUIRE( ui.getConfIOType(sid) == UniversalIO::DI ); CHECK( ui.getConf() == uniset_conf() );
REQUIRE( ui.getConfIOType(aid) == UniversalIO::AI );
// REQUIRE( ui.getType(sid) == "IONotifyController" ); REQUIRE( ui.getConfIOType(sid) == UniversalIO::DI );
// REQUIRE( ui.getType(aid) == "IONotifyController" ); REQUIRE( ui.getConfIOType(aid) == UniversalIO::AI );
// REQUIRE( ui.getType(sid) == "IONotifyController" );
SECTION( "GET/SET" ) // REQUIRE( ui.getType(aid) == "IONotifyController" );
{
REQUIRE_THROWS_AS( ui.getValue(DefaultObjectId), UniSetTypes::ORepFailed ); SECTION( "GET/SET" )
REQUIRE_NOTHROW( ui.setValue(sid,1) ); {
REQUIRE( ui.getValue(sid) == 1 ); REQUIRE_THROWS_AS( ui.getValue(DefaultObjectId), UniSetTypes::ORepFailed );
REQUIRE_NOTHROW( ui.setValue(sid,100) ); REQUIRE_NOTHROW( ui.setValue(sid,1) );
REQUIRE( ui.getValue(sid) == 100 ); // хоть это и дискретный датчик.. функция-то универсальная.. REQUIRE( ui.getValue(sid) == 1 );
REQUIRE_NOTHROW( ui.setValue(sid,100) );
REQUIRE_THROWS_AS( ui.getValue(sid, DefaultObjectId), UniSetTypes::Exception ); REQUIRE( ui.getValue(sid) == 100 ); // хоть это и дискретный датчик.. функция-то универсальная..
REQUIRE_THROWS_AS( ui.getValue(sid, 100), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getValue(sid, DefaultObjectId), UniSetTypes::Exception );
REQUIRE_NOTHROW( ui.setValue(aid,10) ); REQUIRE_THROWS_AS( ui.getValue(sid, 100), UniSetTypes::Exception );
REQUIRE( ui.getValue(aid) == 10 );
REQUIRE_NOTHROW( ui.setValue(aid,10) );
IOController_i::SensorInfo si; REQUIRE( ui.getValue(aid) == 10 );
si.id = aid;
si.node = conf->getLocalNode(); IOController_i::SensorInfo si;
REQUIRE_NOTHROW( ui.setValue(si,15, DefaultObjectId) ); si.id = aid;
REQUIRE( ui.getRawValue(si) == 15 ); si.node = conf->getLocalNode();
REQUIRE_NOTHROW( ui.setValue(si,15, DefaultObjectId) );
REQUIRE_NOTHROW( ui.fastSetValue(si,20,DefaultObjectId) ); REQUIRE( ui.getRawValue(si) == 15 );
REQUIRE( ui.getValue(aid) == 20 );
REQUIRE_THROWS_AS( ui.getValue(aid,-2), UniSetTypes::Exception ); REQUIRE_NOTHROW( ui.fastSetValue(si,20,DefaultObjectId) );
REQUIRE( ui.getValue(aid) == 20 );
si.id = sid; REQUIRE_THROWS_AS( ui.getValue(aid,-2), UniSetTypes::Exception );
REQUIRE_NOTHROW( ui.setValue(si,15, DefaultObjectId) );
REQUIRE( ui.getValue(sid) == 15 ); si.id = sid;
REQUIRE_NOTHROW( ui.setValue(si,15, DefaultObjectId) );
si.node = -2; REQUIRE( ui.getValue(sid) == 15 );
REQUIRE_THROWS_AS( ui.setValue(si,20,DefaultObjectId), UniSetTypes::Exception );
si.node = -2;
REQUIRE_THROWS_AS( ui.getChangedTime(sid,DefaultObjectId), UniSetTypes::ORepFailed ); REQUIRE_THROWS_AS( ui.setValue(si,20,DefaultObjectId), UniSetTypes::Exception );
REQUIRE_NOTHROW( ui.getChangedTime(sid,conf->getLocalNode()) );
REQUIRE_THROWS_AS( ui.getChangedTime(sid,DefaultObjectId), UniSetTypes::ORepFailed );
si.id = aid; REQUIRE_NOTHROW( ui.getChangedTime(sid,conf->getLocalNode()) );
si.node = conf->getLocalNode();
REQUIRE_NOTHROW( ui.setUndefinedState(si,true,testOID) ); si.id = aid;
REQUIRE_NOTHROW( ui.setUndefinedState(si,false,testOID) ); si.node = conf->getLocalNode();
REQUIRE_NOTHROW( ui.setUndefinedState(si,true,testOID) );
si.id = sid; REQUIRE_NOTHROW( ui.setUndefinedState(si,false,testOID) );
si.node = conf->getLocalNode();
REQUIRE_NOTHROW( ui.setUndefinedState(si,true,testOID) ); si.id = sid;
REQUIRE_NOTHROW( ui.setUndefinedState(si,false,testOID) ); si.node = conf->getLocalNode();
REQUIRE_NOTHROW( ui.setUndefinedState(si,true,testOID) );
REQUIRE( ui.getIOType(sid,conf->getLocalNode()) == UniversalIO::DI ); REQUIRE_NOTHROW( ui.setUndefinedState(si,false,testOID) );
REQUIRE( ui.getIOType(aid,conf->getLocalNode()) == UniversalIO::AI );
} REQUIRE( ui.getIOType(sid,conf->getLocalNode()) == UniversalIO::DI );
REQUIRE( ui.getIOType(aid,conf->getLocalNode()) == UniversalIO::AI );
SECTION( "resolve" ) }
{
REQUIRE_NOTHROW( ui.resolve(sid) ); SECTION( "resolve" )
REQUIRE_THROWS_AS( ui.resolve(sid,10), UniSetTypes::ORepFailed ); {
REQUIRE_THROWS_AS( ui.resolve(sid,DefaultObjectId), UniSetTypes::ORepFailed ); REQUIRE_NOTHROW( ui.resolve(sid) );
} REQUIRE_THROWS_AS( ui.resolve(sid,10), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.resolve(sid,DefaultObjectId), UniSetTypes::ORepFailed );
SECTION( "send" ) }
{
TransportMessage tm( SensorMessage(sid,10).transport_msg() ); SECTION( "send" )
REQUIRE_NOTHROW( ui.send(sid,tm) ); {
} TransportMessage tm( SensorMessage(sid,10).transport_msg() );
REQUIRE_NOTHROW( ui.send(sid,tm) );
SECTION( "wait..exist.." ) }
{
CHECK( ui.waitReady(sid,200,50) ); SECTION( "wait..exist.." )
CHECK( ui.waitReady(sid,200,50, conf->getLocalNode()) ); {
CHECK_FALSE( ui.waitReady(sid,300,50,DefaultObjectId) ); CHECK( ui.waitReady(sid,200,50) );
CHECK_FALSE( ui.waitReady(sid,300,50,-20) ); CHECK( ui.waitReady(sid,200,50, conf->getLocalNode()) );
CHECK_FALSE( ui.waitReady(sid,-1,50) ); CHECK_FALSE( ui.waitReady(sid,300,50,DefaultObjectId) );
CHECK( ui.waitReady(sid,300,-1) ); CHECK_FALSE( ui.waitReady(sid,300,50,-20) );
CHECK_FALSE( ui.waitReady(sid,-1,50) );
CHECK( ui.waitWorking(sid,200,50) ); CHECK( ui.waitReady(sid,300,-1) );
CHECK( ui.waitWorking(sid,200,50,conf->getLocalNode()) );
CHECK_FALSE( ui.waitWorking(sid,100,50,DefaultObjectId) ); CHECK( ui.waitWorking(sid,200,50) );
CHECK_FALSE( ui.waitWorking(sid,100,50,-20) ); CHECK( ui.waitWorking(sid,200,50,conf->getLocalNode()) );
CHECK_FALSE( ui.waitWorking(sid,-1,50) ); CHECK_FALSE( ui.waitWorking(sid,100,50,DefaultObjectId) );
CHECK( ui.waitWorking(sid,100,-1) ); CHECK_FALSE( ui.waitWorking(sid,100,50,-20) );
CHECK_FALSE( ui.waitWorking(sid,-1,50) );
CHECK( ui.isExist(sid) ); CHECK( ui.waitWorking(sid,100,-1) );
CHECK( ui.isExist(sid,conf->getLocalNode()) );
CHECK_FALSE( ui.isExist(sid,DefaultObjectId) ); CHECK( ui.isExist(sid) );
CHECK_FALSE( ui.isExist(sid,100) ); CHECK( ui.isExist(sid,conf->getLocalNode()) );
} CHECK_FALSE( ui.isExist(sid,DefaultObjectId) );
CHECK_FALSE( ui.isExist(sid,100) );
SECTION( "get/set list" ) }
{
UniSetTypes::IDList lst; SECTION( "get/set list" )
lst.add(aid); {
lst.add(sid); UniSetTypes::IDList lst;
lst.add(-100); // bad sensor ID lst.add(aid);
lst.add(sid);
IOController_i::SensorInfoSeq_var seq = ui.getSensorSeq(lst); lst.add(-100); // bad sensor ID
REQUIRE( seq->length() == 3 );
IOController_i::SensorInfoSeq_var seq = ui.getSensorSeq(lst);
IOController_i::OutSeq_var olst = new IOController_i::OutSeq(); REQUIRE( seq->length() == 3 );
olst->length(2);
olst[0].si.id = sid; IOController_i::OutSeq_var olst = new IOController_i::OutSeq();
olst[0].si.node = conf->getLocalNode(); olst->length(2);
olst[0].value = 1; olst[0].si.id = sid;
olst[1].si.id = aid; olst[0].si.node = conf->getLocalNode();
olst[1].si.node = conf->getLocalNode(); olst[0].value = 1;
olst[1].value = 35; olst[1].si.id = aid;
olst[1].si.node = conf->getLocalNode();
UniSetTypes::IDSeq_var iseq = ui.setOutputSeq(olst, DefaultObjectId); olst[1].value = 35;
REQUIRE( iseq->length() == 0 );
UniSetTypes::IDSeq_var iseq = ui.setOutputSeq(olst, DefaultObjectId);
IOController_i::ShortMapSeq_var slist = ui.getSensors( sid, conf->getLocalNode() ); REQUIRE( iseq->length() == 0 );
REQUIRE( slist->length() >= 2 );
} IOController_i::ShortMapSeq_var slist = ui.getSensors( sid, conf->getLocalNode() );
REQUIRE( slist->length() >= 2 );
SECTION( "ask" ) }
{
REQUIRE_THROWS_AS( ui.askSensor(sid,UniversalIO::UIONotify), UniSetTypes::IOBadParam ); SECTION( "ask" )
REQUIRE_NOTHROW( ui.askSensor(sid,UniversalIO::UIONotify,testOID) ); {
REQUIRE_NOTHROW( ui.askSensor(aid,UniversalIO::UIONotify,testOID) ); REQUIRE_THROWS_AS( ui.askSensor(sid,UniversalIO::UIONotify), UniSetTypes::IOBadParam );
REQUIRE_NOTHROW( ui.askSensor(aid,UniversalIO::UIODontNotify,testOID) ); REQUIRE_NOTHROW( ui.askSensor(sid,UniversalIO::UIONotify,testOID) );
REQUIRE_NOTHROW( ui.askSensor(sid,UniversalIO::UIODontNotify,testOID) ); REQUIRE_NOTHROW( ui.askSensor(aid,UniversalIO::UIONotify,testOID) );
REQUIRE_NOTHROW( ui.askSensor(aid,UniversalIO::UIODontNotify,testOID) );
REQUIRE_THROWS_AS( ui.askSensor(-20,UniversalIO::UIONotify), UniSetTypes::Exception ); REQUIRE_NOTHROW( ui.askSensor(sid,UniversalIO::UIODontNotify,testOID) );
REQUIRE_NOTHROW( ui.askRemoteSensor(sid,UniversalIO::UIONotify,conf->getLocalNode(),testOID) ); REQUIRE_THROWS_AS( ui.askSensor(-20,UniversalIO::UIONotify), UniSetTypes::Exception );
REQUIRE_NOTHROW( ui.askRemoteSensor(aid,UniversalIO::UIONotify,conf->getLocalNode(),testOID) );
REQUIRE_THROWS_AS( ui.askRemoteSensor(sid,UniversalIO::UIONotify,-3,testOID), UniSetTypes::Exception ); REQUIRE_NOTHROW( ui.askRemoteSensor(sid,UniversalIO::UIONotify,conf->getLocalNode(),testOID) );
REQUIRE_NOTHROW( ui.askRemoteSensor(aid,UniversalIO::UIONotify,conf->getLocalNode(),testOID) );
UniSetTypes::IDList lst; REQUIRE_THROWS_AS( ui.askRemoteSensor(sid,UniversalIO::UIONotify,-3,testOID), UniSetTypes::Exception );
lst.add(aid);
lst.add(sid); UniSetTypes::IDList lst;
lst.add(-100); // bad sensor ID lst.add(aid);
lst.add(sid);
UniSetTypes::IDSeq_var rseq = ui.askSensorsSeq(lst,UniversalIO::UIONotify,testOID); lst.add(-100); // bad sensor ID
REQUIRE( rseq->length() == 1 ); // проверяем, что нам вернули один BAD-датчик..(-100)
} UniSetTypes::IDSeq_var rseq = ui.askSensorsSeq(lst,UniversalIO::UIONotify,testOID);
REQUIRE( rseq->length() == 1 ); // проверяем, что нам вернули один BAD-датчик..(-100)
SECTION( "Thresholds" ) }
{
REQUIRE_NOTHROW( ui.askThreshold(aid,10,UniversalIO::UIONotify,90,100,false,testOID) ); SECTION( "Thresholds" )
REQUIRE_NOTHROW( ui.askThreshold(aid,11,UniversalIO::UIONotify,50,70,false,testOID) ); {
REQUIRE_NOTHROW( ui.askThreshold(aid,12,UniversalIO::UIONotify,20,40,false,testOID) ); REQUIRE_NOTHROW( ui.askThreshold(aid,10,UniversalIO::UIONotify,90,100,false,testOID) );
REQUIRE_THROWS_AS( ui.askThreshold(aid,3,UniversalIO::UIONotify,50,20,false,testOID), IONotifyController_i::BadRange ); REQUIRE_NOTHROW( ui.askThreshold(aid,11,UniversalIO::UIONotify,50,70,false,testOID) );
REQUIRE_NOTHROW( ui.askThreshold(aid,12,UniversalIO::UIONotify,20,40,false,testOID) );
IONotifyController_i::ThresholdInfo ti1 = ui.getThresholdInfo(aid,10); REQUIRE_THROWS_AS( ui.askThreshold(aid,3,UniversalIO::UIONotify,50,20,false,testOID), IONotifyController_i::BadRange );
REQUIRE( ti1.id == 10 );
REQUIRE( ti1.lowlimit == 90 ); IONotifyController_i::ThresholdInfo ti1 = ui.getThresholdInfo(aid,10);
REQUIRE( ti1.hilimit == 100 ); REQUIRE( ti1.id == 10 );
REQUIRE( ti1.lowlimit == 90 );
IONotifyController_i::ThresholdInfo ti2 = ui.getThresholdInfo(aid,11); REQUIRE( ti1.hilimit == 100 );
REQUIRE( ti2.id == 11 );
REQUIRE( ti2.lowlimit == 50 ); IONotifyController_i::ThresholdInfo ti2 = ui.getThresholdInfo(aid,11);
REQUIRE( ti2.hilimit == 70 ); REQUIRE( ti2.id == 11 );
REQUIRE( ti2.lowlimit == 50 );
IONotifyController_i::ThresholdInfo ti3 = ui.getThresholdInfo(aid,12); REQUIRE( ti2.hilimit == 70 );
REQUIRE( ti3.id == 12 );
REQUIRE( ti3.lowlimit == 20 ); IONotifyController_i::ThresholdInfo ti3 = ui.getThresholdInfo(aid,12);
REQUIRE( ti3.hilimit == 40 ); REQUIRE( ti3.id == 12 );
REQUIRE( ti3.lowlimit == 20 );
REQUIRE_THROWS_AS( ui.getThresholdInfo(sid,10), UniSetTypes::NameNotFound ); REQUIRE( ti3.hilimit == 40 );
}
REQUIRE_THROWS_AS( ui.getThresholdInfo(sid,10), UniSetTypes::NameNotFound );
SECTION( "calibration" ) }
{
IOController_i::SensorInfo si; SECTION( "calibration" )
si.id = aid; {
si.node = conf->getLocalNode(); IOController_i::SensorInfo si;
si.id = aid;
IOController_i::CalibrateInfo ci; si.node = conf->getLocalNode();
ci.minRaw = 0;
ci.maxRaw = 4096; IOController_i::CalibrateInfo ci;
ci.minCal = -100; ci.minRaw = 0;
ci.maxCal = 100; ci.maxRaw = 4096;
ci.precision = 3; ci.minCal = -100;
REQUIRE_NOTHROW( ui.calibrate(si,ci) ); ci.maxCal = 100;
ci.precision = 3;
REQUIRE_NOTHROW( ui.calibrate(si,ci) );
IOController_i::CalibrateInfo ci2 = ui.getCalibrateInfo(si); IOController_i::CalibrateInfo ci2 = ui.getCalibrateInfo(si);
CHECK( ci.minRaw == ci2.minRaw ); CHECK( ci.minRaw == ci2.minRaw );
CHECK( ci.maxRaw == ci2.maxRaw ); CHECK( ci.maxRaw == ci2.maxRaw );
CHECK( ci.minCal == ci2.minCal ); CHECK( ci.minCal == ci2.minCal );
CHECK( ci.maxCal == ci2.maxCal ); CHECK( ci.maxCal == ci2.maxCal );
CHECK( ci.precision == ci2.precision ); CHECK( ci.precision == ci2.precision );
} }
} }
...@@ -9,296 +9,296 @@ using namespace VTypes; ...@@ -9,296 +9,296 @@ using namespace VTypes;
TEST_CASE("VTypes: I2","[vtypes][I2]") TEST_CASE("VTypes: I2","[vtypes][I2]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
I2 v; I2 v;
REQUIRE( (int)v == 0 ); REQUIRE( (int)v == 0 );
} }
SECTION("'int' constructor") SECTION("'int' constructor")
{ {
I2 v(100); I2 v(100);
REQUIRE( (int)v == 100 ); REQUIRE( (int)v == 100 );
I2 v2(-1000000); I2 v2(-1000000);
REQUIRE( (int)v2 == -1000000 ); REQUIRE( (int)v2 == -1000000 );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData data[2] = {0,0xFFFF}; ModbusRTU::ModbusData data[2] = {0,0xFFFF};
I2 v1(data,2); I2 v1(data,2);
REQUIRE( (int)v1 == -65536 ); REQUIRE( (int)v1 == -65536 );
ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF}; ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF};
I2 v2(data3,3); I2 v2(data3,3);
REQUIRE( (int)v2 == -65536 ); REQUIRE( (int)v2 == -65536 );
} }
} }
TEST_CASE("VTypes: I2r","[vtypes][I2r]") TEST_CASE("VTypes: I2r","[vtypes][I2r]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
I2r v; I2r v;
REQUIRE( (int)v == 0 ); REQUIRE( (int)v == 0 );
} }
SECTION("'int' constructor") SECTION("'int' constructor")
{ {
I2r v(100); I2r v(100);
REQUIRE( (int)v == 100 ); REQUIRE( (int)v == 100 );
I2r v1(-1000000); I2r v1(-1000000);
REQUIRE( (int)v1 == -1000000 ); REQUIRE( (int)v1 == -1000000 );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData data[2] = {0,0xFFFF}; ModbusRTU::ModbusData data[2] = {0,0xFFFF};
I2r v1(data,2); I2r v1(data,2);
REQUIRE( (int)v1 == 65535 ); REQUIRE( (int)v1 == 65535 );
ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF}; ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF};
I2r v2(data3,3); I2r v2(data3,3);
REQUIRE( (int)v2 == 65535 ); REQUIRE( (int)v2 == 65535 );
I2r tmp(-100000); I2r tmp(-100000);
ModbusRTU::ModbusData d2[2]; ModbusRTU::ModbusData d2[2];
d2[0] = tmp.raw.v[1]; d2[0] = tmp.raw.v[1];
d2[1] = tmp.raw.v[0]; d2[1] = tmp.raw.v[0];
I2r v3(d2,2); I2r v3(d2,2);
REQUIRE( (int)v3 == -100000 ); REQUIRE( (int)v3 == -100000 );
} }
} }
TEST_CASE("VTypes: U2","[vtypes][U2]") TEST_CASE("VTypes: U2","[vtypes][U2]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
U2 v; U2 v;
REQUIRE( (unsigned int)v == 0 ); REQUIRE( (unsigned int)v == 0 );
} }
SECTION("'unsigned int' constructor") SECTION("'unsigned int' constructor")
{ {
{ {
U2 v( numeric_limits<unsigned int>::max() ); U2 v( numeric_limits<unsigned int>::max() );
REQUIRE( (unsigned int)v == numeric_limits<unsigned int>::max() ); REQUIRE( (unsigned int)v == numeric_limits<unsigned int>::max() );
REQUIRE( v.raw.v[0] == 0xffff ); REQUIRE( v.raw.v[0] == 0xffff );
REQUIRE( v.raw.v[1] == 0xffff ); REQUIRE( v.raw.v[1] == 0xffff );
} }
{ {
U2 v(-1); U2 v(-1);
REQUIRE( (unsigned int)v == 4294967295 ); REQUIRE( (unsigned int)v == 4294967295 );
} }
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData data[2] = {0,0xFFFF}; ModbusRTU::ModbusData data[2] = {0,0xFFFF};
U2 v1(data,2); U2 v1(data,2);
REQUIRE( (unsigned int)v1 == 0xffff0000 ); REQUIRE( (unsigned int)v1 == 0xffff0000 );
ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF}; ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF};
U2 v2(data3,3); U2 v2(data3,3);
REQUIRE( (unsigned int)v2 == 0xffff0000 ); REQUIRE( (unsigned int)v2 == 0xffff0000 );
} }
} }
TEST_CASE("VTypes: U2r","[vtypes][U2r]") TEST_CASE("VTypes: U2r","[vtypes][U2r]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
U2r v; U2r v;
REQUIRE( (unsigned int)v == 0 ); REQUIRE( (unsigned int)v == 0 );
} }
SECTION("'unsigned int' constructor") SECTION("'unsigned int' constructor")
{ {
U2r v( numeric_limits<unsigned int>::max() ); U2r v( numeric_limits<unsigned int>::max() );
REQUIRE( (unsigned int)v == numeric_limits<unsigned int>::max() ); REQUIRE( (unsigned int)v == numeric_limits<unsigned int>::max() );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData data[2] = {0,0xFFFF}; ModbusRTU::ModbusData data[2] = {0,0xFFFF};
U2r v1(data,2); U2r v1(data,2);
REQUIRE( (unsigned int)v1 == 0x0000ffff ); REQUIRE( (unsigned int)v1 == 0x0000ffff );
ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF}; ModbusRTU::ModbusData data3[3] = {0,0xFFFF,0xFFFF};
U2r v2(data3,3); U2r v2(data3,3);
REQUIRE( (unsigned int)v2 == 0x0000ffff ); REQUIRE( (unsigned int)v2 == 0x0000ffff );
} }
} }
TEST_CASE("VTypes: F2","[vtypes][F2]") TEST_CASE("VTypes: F2","[vtypes][F2]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
F2 v; F2 v;
REQUIRE( (float)v == 0 ); REQUIRE( (float)v == 0 );
} }
SECTION("'float' constructor") SECTION("'float' constructor")
{ {
F2 v( numeric_limits<float>::max() ); F2 v( numeric_limits<float>::max() );
REQUIRE( (float)v == numeric_limits<float>::max() ); REQUIRE( (float)v == numeric_limits<float>::max() );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
float f=1.5; float f=1.5;
ModbusRTU::ModbusData data[2]; ModbusRTU::ModbusData data[2];
memcpy(data,&f,sizeof(data)); memcpy(data,&f,sizeof(data));
F2 v1(data,2); F2 v1(data,2);
REQUIRE( (float)v1 == f ); REQUIRE( (float)v1 == f );
REQUIRE( (long)v1 == 2 ); REQUIRE( (long)v1 == 2 );
REQUIRE( (int)v1 == 2 ); REQUIRE( (int)v1 == 2 );
ModbusRTU::ModbusData data3[3]; ModbusRTU::ModbusData data3[3];
memset(data3,0,sizeof(data3)); memset(data3,0,sizeof(data3));
memcpy(data3,&f,2*sizeof(ModbusRTU::ModbusData)); memcpy(data3,&f,2*sizeof(ModbusRTU::ModbusData));
F2 v2(data3,3); F2 v2(data3,3);
REQUIRE( (float)v2 == f ); REQUIRE( (float)v2 == f );
} }
} }
TEST_CASE("VTypes: F2r","[vtypes][F2r]") TEST_CASE("VTypes: F2r","[vtypes][F2r]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
F2r v; F2r v;
REQUIRE( (float)v == 0 ); REQUIRE( (float)v == 0 );
} }
SECTION("'float' constructor") SECTION("'float' constructor")
{ {
F2r v( numeric_limits<float>::max() ); F2r v( numeric_limits<float>::max() );
REQUIRE( (float)v == numeric_limits<float>::max() ); REQUIRE( (float)v == numeric_limits<float>::max() );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
float f=1.5; float f=1.5;
ModbusRTU::ModbusData data[2]; ModbusRTU::ModbusData data[2];
memcpy(data,&f,sizeof(data)); memcpy(data,&f,sizeof(data));
std::swap(data[0],data[1]); std::swap(data[0],data[1]);
F2r v1(data,2); F2r v1(data,2);
REQUIRE( (float)v1 == f ); REQUIRE( (float)v1 == f );
REQUIRE( (long)v1 == 2 ); REQUIRE( (long)v1 == 2 );
REQUIRE( (int)v1 == 2 ); REQUIRE( (int)v1 == 2 );
ModbusRTU::ModbusData data3[3]; ModbusRTU::ModbusData data3[3];
memset(data3,0,sizeof(data3)); memset(data3,0,sizeof(data3));
memcpy(data3,&f,2*sizeof(ModbusRTU::ModbusData)); memcpy(data3,&f,2*sizeof(ModbusRTU::ModbusData));
std::swap(data3[0],data3[1]); std::swap(data3[0],data3[1]);
F2r v2(data3,3); F2r v2(data3,3);
REQUIRE( (float)v2 == f ); REQUIRE( (float)v2 == f );
} }
} }
TEST_CASE("VTypes: F4","[vtypes][F4]") TEST_CASE("VTypes: F4","[vtypes][F4]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
F4 v; F4 v;
REQUIRE( (float)v == 0 ); REQUIRE( (float)v == 0 );
} }
SECTION("'float' constructor") SECTION("'float' constructor")
{ {
{ {
F4 v( numeric_limits<float>::max() ); F4 v( numeric_limits<float>::max() );
REQUIRE( (float)v == numeric_limits<float>::max() ); REQUIRE( (float)v == numeric_limits<float>::max() );
} }
{ {
F4 v( numeric_limits<float>::min() ); F4 v( numeric_limits<float>::min() );
REQUIRE( (float)v == numeric_limits<float>::min() ); REQUIRE( (float)v == numeric_limits<float>::min() );
} }
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
{ {
float f = numeric_limits<float>::max(); float f = numeric_limits<float>::max();
ModbusRTU::ModbusData data[4]; ModbusRTU::ModbusData data[4];
memcpy(data,&f,sizeof(data)); memcpy(data,&f,sizeof(data));
F4 v1(data,4); F4 v1(data,4);
REQUIRE( (float)v1 == f ); REQUIRE( (float)v1 == f );
} }
{ {
float f = numeric_limits<float>::max(); float f = numeric_limits<float>::max();
ModbusRTU::ModbusData data5[5]; ModbusRTU::ModbusData data5[5];
memset(data5,0,sizeof(data5)); memset(data5,0,sizeof(data5));
memcpy(data5,&f,4*sizeof(ModbusRTU::ModbusData)); memcpy(data5,&f,4*sizeof(ModbusRTU::ModbusData));
F4 v2(data5,5); F4 v2(data5,5);
REQUIRE( (float)v2 == f ); REQUIRE( (float)v2 == f );
} }
{ {
float f = numeric_limits<float>::min(); float f = numeric_limits<float>::min();
ModbusRTU::ModbusData data[4]; ModbusRTU::ModbusData data[4];
memcpy(data,&f,sizeof(data)); memcpy(data,&f,sizeof(data));
F4 v1(data,4); F4 v1(data,4);
REQUIRE( (float)v1 == f ); REQUIRE( (float)v1 == f );
} }
} }
} }
TEST_CASE("VTypes: Byte","[vtypes][byte]") TEST_CASE("VTypes: Byte","[vtypes][byte]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
Byte v; Byte v;
REQUIRE( v[0] == 0 ); REQUIRE( v[0] == 0 );
} }
SECTION("'2 byte' constructor") SECTION("'2 byte' constructor")
{ {
Byte v(132,255); Byte v(132,255);
REQUIRE( v[0] == 132 ); REQUIRE( v[0] == 132 );
REQUIRE( v[1] == 255 ); REQUIRE( v[1] == 255 );
} }
SECTION("'long' constructor") SECTION("'long' constructor")
{ {
long l=0xff; long l=0xff;
Byte v(l); Byte v(l);
REQUIRE( (long)v == 0xff ); REQUIRE( (long)v == 0xff );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData d = 255; ModbusRTU::ModbusData d = 255;
Byte v(d); Byte v(d);
REQUIRE( (unsigned char)v[0] == 255 ); REQUIRE( (unsigned char)v[0] == 255 );
} }
} }
TEST_CASE("VTypes: Unsigned","[vtypes][unsigned]") TEST_CASE("VTypes: Unsigned","[vtypes][unsigned]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
Unsigned v; Unsigned v;
REQUIRE( v == 0 ); REQUIRE( v == 0 );
} }
SECTION("'long' constructor") SECTION("'long' constructor")
{ {
long l=0xffff; long l=0xffff;
Unsigned v(l); Unsigned v(l);
REQUIRE( (unsigned short)v == 0xffff ); REQUIRE( (unsigned short)v == 0xffff );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData d = 65535; ModbusRTU::ModbusData d = 65535;
Unsigned v(d); Unsigned v(d);
REQUIRE( (unsigned short)v == 65535 ); REQUIRE( (unsigned short)v == 65535 );
} }
} }
TEST_CASE("VTypes: Signed","[vtypes][signed]") TEST_CASE("VTypes: Signed","[vtypes][signed]")
{ {
SECTION("Default constructor") SECTION("Default constructor")
{ {
Signed v; Signed v;
REQUIRE( v == 0 ); REQUIRE( v == 0 );
} }
SECTION("'long' constructor") SECTION("'long' constructor")
{ {
long l= -32766; long l= -32766;
Signed v(l); Signed v(l);
REQUIRE( (signed short)v == l ); REQUIRE( (signed short)v == l );
} }
SECTION("Modbus constructor") SECTION("Modbus constructor")
{ {
ModbusRTU::ModbusData d = 65535; ModbusRTU::ModbusData d = 65535;
Signed v(d); Signed v(d);
REQUIRE( (signed short)v == (signed short)d ); REQUIRE( (signed short)v == (signed short)d );
} }
} }
...@@ -229,17 +229,14 @@ namespace UniSetTypes ...@@ -229,17 +229,14 @@ namespace UniSetTypes
int heartbeat_msec; int heartbeat_msec;
}; };
/*! Глобальный указатель на конфигуратор */ /*! Глобальный указатель на конфигурацию (singleton) */
extern Configuration* conf; std::shared_ptr<Configuration> uniset_conf();
/*! Глобальный объект для вывода логов */ /*! Глобальный объект для вывода логов */
extern DebugStream ulog; extern DebugStream ulog;
// Инициализация UniSetTypes::conf. /*! инициализация "глобальной" конфигурации */
// ( учитываются параметры командной строки --confile и --id-from-config ) std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile="configure.xml" );
// force - инициализировать принудительно, даже если это повторная инициализация
void uniset_init( int argc, const char* const* argv, const std::string& xmlfile="configure.xml", bool force = false );
} // end of UniSetTypes namespace } // end of UniSetTypes namespace
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
...@@ -115,10 +115,10 @@ class DelayTimer ...@@ -115,10 +115,10 @@ class DelayTimer
return state; return state;
} }
inline bool get(){ return check(prevState); } inline bool get(){ return check(prevState); }
inline timeout_t getOnDelay(){ return onDelay; } inline timeout_t getOnDelay(){ return onDelay; }
inline timeout_t getOffDelay(){ return offDelay; } inline timeout_t getOffDelay(){ return offDelay; }
protected: protected:
PassiveTimer pt; PassiveTimer pt;
......
...@@ -95,13 +95,13 @@ class HourGlass ...@@ -95,13 +95,13 @@ class HourGlass
_state = st; _state = st;
if( !_state ) if( !_state )
{ {
timeout_t cur = t.getCurrent(); timeout_t cur = t.getCurrent();
if( cur > _size ) if( cur > _size )
cur = _size; cur = _size;
_sand -= cur; _sand -= cur;
if( _sand < 0 ) if( _sand < 0 )
_sand = 0; _sand = 0;
t.setTiming(cur); t.setTiming(cur);
} }
...@@ -123,7 +123,7 @@ class HourGlass ...@@ -123,7 +123,7 @@ class HourGlass
// получить прошедшее время // получить прошедшее время
inline timeout_t current() inline timeout_t current()
{ {
return t.getCurrent(); return t.getCurrent();
} }
// получить заданное время // получить заданное время
...@@ -145,36 +145,36 @@ class HourGlass ...@@ -145,36 +145,36 @@ class HourGlass
inline bool state(){ return _state; } inline bool state(){ return _state; }
// текущее "насыпавшееся" количество "песка" // текущее "насыпавшееся" количество "песка"
inline timeout_t amount() inline timeout_t amount()
{ {
return ( _size - remain() ); return ( _size - remain() );
} }
// остаток песка (времени) // остаток песка (времени)
inline timeout_t remain() inline timeout_t remain()
{ {
timeout_t c = t.getCurrent(); timeout_t c = t.getCurrent();
if( c > _size ) if( c > _size )
c = _size; c = _size;
// _state=false - означает, что песок пересыпается обратно.. // _state=false - означает, что песок пересыпается обратно..
if( !_state ) if( !_state )
{ {
int ret = ( _sand + c ); int ret = ( _sand + c );
if( ret > _size ) if( ret > _size )
return _size; return _size;
return ret; return ret;
} }
// _state=true - означает, что песок пересыпается.. // _state=true - означает, что песок пересыпается..
int ret = ( _sand - c ); int ret = ( _sand - c );
if( ret < 0 ) if( ret < 0 )
return 0; return 0;
return ret; return ret;
} }
protected: protected:
PassiveTimer t; /*!< таймер для отсчёта времени.. */ PassiveTimer t; /*!< таймер для отсчёта времени.. */
......
...@@ -81,7 +81,7 @@ class IOController: ...@@ -81,7 +81,7 @@ class IOController:
IOController_i::CalibrateInfo getCalibrateInfo( UniSetTypes::ObjectId sid ) override; IOController_i::CalibrateInfo getCalibrateInfo( UniSetTypes::ObjectId sid ) override;
inline IOController_i::SensorInfo SensorInfo( const UniSetTypes::ObjectId sid, inline IOController_i::SensorInfo SensorInfo( const UniSetTypes::ObjectId sid,
const UniSetTypes::ObjectId node=UniSetTypes::conf->getLocalNode()) const UniSetTypes::ObjectId node=UniSetTypes::uniset_conf()->getLocalNode())
{ {
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = sid; si.id = sid;
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
class LogSession; class LogSession;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер /*! \page pgLogServer Лог сервер
Лог сервер предназначен для возможности удалённого чтения логов (DebugStream). Лог сервер предназначен для возможности удалённого чтения логов (DebugStream).
Ему указывается host и port для прослушивания запросов, которые можно делать при помощи Ему указывается host и port для прослушивания запросов, которые можно делать при помощи
LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession). LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession).
При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов, При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов,
......
############################################################################ ############################################################################
# This file is part of the UniSet library # # This file is part of the UniSet library #
############################################################################ ############################################################################
SUBDIRS=modbus SUBDIRS=modbus
......
...@@ -24,7 +24,8 @@ ...@@ -24,7 +24,8 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#ifndef ObjectRepository_H_ #ifndef ObjectRepository_H_
#define ObjectRepository_H_ #define ObjectRepository_H_
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <memory>
#include <omniORB4/CORBA.h> #include <omniORB4/CORBA.h>
#include <omniORB4/Naming.hh> #include <omniORB4/Naming.hh>
#include <string> #include <string>
...@@ -46,7 +47,7 @@ ...@@ -46,7 +47,7 @@
{ {
public: public:
ObjectRepository( const UniSetTypes::Configuration* conf); ObjectRepository( const std::shared_ptr<UniSetTypes::Configuration>& conf );
~ObjectRepository(); ~ObjectRepository();
/** /**
...@@ -100,7 +101,7 @@ ...@@ -100,7 +101,7 @@
ObjectRepository(); ObjectRepository();
mutable std::string nsName; mutable std::string nsName;
const UniSetTypes::Configuration* uconf; std::shared_ptr<UniSetTypes::Configuration> uconf;
bool list(const std::string& section, UniSetTypes::ListObjectName *ls, unsigned int how_many, ObjectType type); bool list(const std::string& section, UniSetTypes::ListObjectName *ls, unsigned int how_many, ObjectType type);
......
...@@ -40,7 +40,7 @@ ...@@ -40,7 +40,7 @@
public: public:
// ObjectRepositoryFactory(); // ObjectRepositoryFactory();
// ObjectRepositoryFactory(int* argc=argc_ptr, char* **argv=argv_ptr); // параметры инициализации ORB // ObjectRepositoryFactory(int* argc=argc_ptr, char* **argv=argv_ptr); // параметры инициализации ORB
ObjectRepositoryFactory( UniSetTypes::Configuration* conf ); ObjectRepositoryFactory( const std::shared_ptr<UniSetTypes::Configuration>& conf );
~ObjectRepositoryFactory(); ~ObjectRepositoryFactory();
//! Создание секции //! Создание секции
......
...@@ -65,8 +65,8 @@ class UInterface ...@@ -65,8 +65,8 @@ class UInterface
{ {
public: public:
UInterface( const UniSetTypes::ObjectId backid, CORBA::ORB_var orb=NULL, std::shared_ptr<UniSetTypes::ObjectIndex> oind=nullptr ); UInterface( const UniSetTypes::ObjectId backid, CORBA::ORB_var orb=NULL, const std::shared_ptr<UniSetTypes::ObjectIndex> oind=nullptr );
UInterface( const UniSetTypes::Configuration* uconf=UniSetTypes::conf ); UInterface( const std::shared_ptr<UniSetTypes::Configuration>& uconf = UniSetTypes::uniset_conf() );
~UInterface(); ~UInterface();
// --------------------------------------------------------------- // ---------------------------------------------------------------
...@@ -154,7 +154,7 @@ class UInterface ...@@ -154,7 +154,7 @@ class UInterface
//! Получить список датчиков //! Получить список датчиков
IOController_i::ShortMapSeq* getSensors( const UniSetTypes::ObjectId id, IOController_i::ShortMapSeq* getSensors( const UniSetTypes::ObjectId id,
const UniSetTypes::ObjectId node=UniSetTypes::conf->getLocalNode() ); const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Работа с репозиторием // Работа с репозиторием
...@@ -185,10 +185,10 @@ class UInterface ...@@ -185,10 +185,10 @@ class UInterface
bool isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const; bool isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const;
bool waitReady( const UniSetTypes::ObjectId id, int msec, int pause=5000, bool waitReady( const UniSetTypes::ObjectId id, int msec, int pause=5000,
const UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); // used exist const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ); // used exist
bool waitWorking( const UniSetTypes::ObjectId id, int msec, int pause=3000, bool waitWorking( const UniSetTypes::ObjectId id, int msec, int pause=3000,
const UniSetTypes::ObjectId node = UniSetTypes::conf->getLocalNode() ); // used getValue const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ); // used getValue
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Работа с ID, Name // Работа с ID, Name
...@@ -222,8 +222,7 @@ class UInterface ...@@ -222,8 +222,7 @@ class UInterface
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Получение указателей на вспомогательные классы. // Получение указателей на вспомогательные классы.
inline const std::shared_ptr<UniSetTypes::ObjectIndex> getObjectIndex() { return oind; } inline const std::shared_ptr<UniSetTypes::ObjectIndex> getObjectIndex() { return oind; }
inline const UniSetTypes::Configuration* getConf() { return uconf; } inline const std::shared_ptr<UniSetTypes::Configuration> getConf() { return uconf; }
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Посылка сообщений // Посылка сообщений
...@@ -302,7 +301,7 @@ class UInterface ...@@ -302,7 +301,7 @@ class UInterface
mutable CORBA::ORB_var orb; mutable CORBA::ORB_var orb;
CacheOfResolve rcache; CacheOfResolve rcache;
std::shared_ptr<UniSetTypes::ObjectIndex> oind; std::shared_ptr<UniSetTypes::ObjectIndex> oind;
const UniSetTypes::Configuration* uconf; std::shared_ptr<UniSetTypes::Configuration> uconf;
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#endif #endif
......
...@@ -134,22 +134,22 @@ class UniSetActivator: ...@@ -134,22 +134,22 @@ class UniSetActivator:
struct Info struct Info
{ {
Info( pid_t p ):msgpid(p){} Info( pid_t p ):msgpid(p){}
pid_t msgpid; // pid порожденого потока обработки сообщений pid_t msgpid; // pid порожденого потока обработки сообщений
}; };
struct OInfo: struct OInfo:
public Info public Info
{ {
OInfo( UniSetObject* o, pid_t p ):Info(p),obj(o){} OInfo( UniSetObject* o, pid_t p ):Info(p),obj(o){}
UniSetObject* obj; UniSetObject* obj;
}; };
struct MInfo: struct MInfo:
public Info public Info
{ {
MInfo( UniSetManager* m, pid_t p ):Info(p),mnr(m){} MInfo( UniSetManager* m, pid_t p ):Info(p),mnr(m){}
UniSetManager* mnr; UniSetManager* mnr;
}; };
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
#ifndef UniSetTypes_H_ #ifndef UniSetTypes_H_
#define UniSetTypes_H_ #define UniSetTypes_H_
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <memory>
#include <cstdlib> #include <cstdlib>
#include <cstdio> #include <cstdio>
#include <string> #include <string>
...@@ -46,8 +47,6 @@ inline void msleep( unsigned int m ) { usleep(m*1000); } ...@@ -46,8 +47,6 @@ inline void msleep( unsigned int m ) { usleep(m*1000); }
namespace UniSetTypes namespace UniSetTypes
{ {
class Configuration; class Configuration;
extern Configuration* conf;
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Вспомогательные типы данных и константы // Вспомогательные типы данных и константы
...@@ -172,7 +171,7 @@ namespace UniSetTypes ...@@ -172,7 +171,7 @@ namespace UniSetTypes
/*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,... /*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,...
Если '=' не указано, возвращается val=0 Если '=' не указано, возвращается val=0
Если @node не указано, возвращается node=DefaultObjectId */ Если @node не указано, возвращается node=DefaultObjectId */
std::list<ParamSInfo> getSInfoList( const std::string& s, Configuration* conf=UniSetTypes::conf ); std::list<ParamSInfo> getSInfoList( const std::string& s, std::shared_ptr<UniSetTypes::Configuration> conf = nullptr );
/*! проверка является текст в строке - числом..*/ /*! проверка является текст в строке - числом..*/
bool is_digit( const std::string& s ); bool is_digit( const std::string& s );
......
...@@ -68,20 +68,20 @@ class UniXML_iterator: ...@@ -68,20 +68,20 @@ class UniXML_iterator:
bool canPrev(); bool canPrev();
bool canNext(); bool canNext();
#if 0 #if 0
friend inline bool operator==(const UniXML_iterator& lhs, const UniXML_iterator& rhs) friend inline bool operator==(const UniXML_iterator& lhs, const UniXML_iterator& rhs)
{ {
return ( lhs.curNode != 0 && rhs.curNode!=0 && lhs.curNode == rhs.curNode ); return ( lhs.curNode != 0 && rhs.curNode!=0 && lhs.curNode == rhs.curNode );
} }
friend inline bool operator!=(const UniXML_iterator& lhs, const UniXML_iterator& rhs){return !(lhs == rhs);} friend inline bool operator!=(const UniXML_iterator& lhs, const UniXML_iterator& rhs){return !(lhs == rhs);}
inline bool operator==(int a) inline bool operator==(int a)
{ {
if( a == 0 ) if( a == 0 )
return (curNode == NULL); return (curNode == NULL);
return false; return false;
} }
#endif #endif
// Перейти к следующему узлу // Перейти к следующему узлу
UniXML_iterator operator+(int); UniXML_iterator operator+(int);
...@@ -115,12 +115,12 @@ class UniXML_iterator: ...@@ -115,12 +115,12 @@ class UniXML_iterator:
inline const std::string getName() const inline const std::string getName() const
{ {
if( curNode ) if( curNode )
{ {
if( !curNode->name ) if( !curNode->name )
return ""; return "";
return (char*) curNode->name; return (char*) curNode->name;
} }
return ""; return "";
} }
...@@ -227,9 +227,9 @@ public: ...@@ -227,9 +227,9 @@ public:
xmlNode* findNode( xmlNode* node, const std::string& searchnode, const std::string& name = "") const; xmlNode* findNode( xmlNode* node, const std::string& searchnode, const std::string& name = "") const;
xmlNode* findNodeUtf8( xmlNode* node, const std::string& searchnode, const std::string& name = "") const; xmlNode* findNodeUtf8( xmlNode* node, const std::string& searchnode, const std::string& name = "") const;
// ?? // ??
//width means number of nodes of the same level as node in 1-st parameter (width number includes first node) //width means number of nodes of the same level as node in 1-st parameter (width number includes first node)
//depth means number of times we can go to the children, if 0 we can't go only to elements of the same level //depth means number of times we can go to the children, if 0 we can't go only to elements of the same level
xmlNode* extFindNode( xmlNode* node, int depth, int width, const std::string& searchnode, const std::string& name = "", bool top=true ) const; xmlNode* extFindNode( xmlNode* node, int depth, int width, const std::string& searchnode, const std::string& name = "", bool top=true ) const;
xmlNode* extFindNodeUtf8( xmlNode* node, int depth, int width, const std::string& searchnode, const std::string& name = "", bool top=true ) const; xmlNode* extFindNodeUtf8( xmlNode* node, int depth, int width, const std::string& searchnode, const std::string& name = "", bool top=true ) const;
......
...@@ -1017,7 +1017,7 @@ namespace ModbusRTU ...@@ -1017,7 +1017,7 @@ namespace ModbusRTU
/*! проверка на переполнение */ /*! проверка на переполнение */
inline bool isFull() inline bool isFull()
{ {
// (1)subf + data count // (1)subf + data count
return ( 1+count >= MAXDATALEN ); return ( 1+count >= MAXDATALEN );
} }
......
...@@ -36,10 +36,11 @@ void pyUInterface::uniset_init( int argc, char* argv[], const char* xmlfile )thr ...@@ -36,10 +36,11 @@ void pyUInterface::uniset_init( int argc, char* argv[], const char* xmlfile )thr
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
long pyUInterface::getValue( long id )throw(UException) long pyUInterface::getValue( long id )throw(UException)
{ {
if( !UniSetTypes::conf || !ui ) auto conf = UniSetTypes::uniset_conf();
if( !conf || !ui )
throw USysError(); throw USysError();
UniversalIO::IOType t = UniSetTypes::conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
try try
{ {
switch(t) switch(t)
...@@ -77,10 +78,12 @@ long pyUInterface::getValue( long id )throw(UException) ...@@ -77,10 +78,12 @@ long pyUInterface::getValue( long id )throw(UException)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void pyUInterface::setValue( long id, long val )throw(UException) void pyUInterface::setValue( long id, long val )throw(UException)
{ {
if( !UniSetTypes::conf || !ui ) auto conf = UniSetTypes::uniset_conf();
if( !conf || !ui )
throw USysError(); throw USysError();
UniversalIO::IOType t = UniSetTypes::conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
try try
{ {
switch(t) switch(t)
...@@ -116,40 +119,45 @@ void pyUInterface::setValue( long id, long val )throw(UException) ...@@ -116,40 +119,45 @@ void pyUInterface::setValue( long id, long val )throw(UException)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
long pyUInterface::getSensorID( const char* name ) long pyUInterface::getSensorID( const char* name )
{ {
if( UniSetTypes::conf ) auto conf = UniSetTypes::uniset_conf();
return UniSetTypes::conf->getSensorID(name); if( conf )
return conf->getSensorID(name);
return UniSetTypes::DefaultObjectId; return UniSetTypes::DefaultObjectId;
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
const char* pyUInterface::getName( long id ) const char* pyUInterface::getName( long id )
{ {
if( UniSetTypes::conf ) auto conf = UniSetTypes::uniset_conf();
return UniSetTypes::conf->oind->getMapName(id).c_str(); if( conf )
return conf->oind->getMapName(id).c_str();
return ""; return "";
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
const char* pyUInterface::getShortName( long id ) const char* pyUInterface::getShortName( long id )
{ {
if( UniSetTypes::conf ) auto conf = UniSetTypes::uniset_conf();
return ORepHelpers::getShortName(UniSetTypes::conf->oind->getMapName(id)).c_str(); if( conf )
return ORepHelpers::getShortName(conf->oind->getMapName(id)).c_str();
return ""; return "";
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
const char* pyUInterface::getTextName( long id ) const char* pyUInterface::getTextName( long id )
{ {
if( UniSetTypes::conf ) auto conf = UniSetTypes::uniset_conf();
return UniSetTypes::conf->oind->getTextName(id).c_str(); if( conf )
return conf->oind->getTextName(id).c_str();
return ""; return "";
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
const char* pyUInterface::getConfFileName() const char* pyUInterface::getConfFileName()
{ {
if( UniSetTypes::conf ) auto conf = UniSetTypes::uniset_conf();
return UniSetTypes::conf->getConfFileName().c_str(); if( conf )
return conf->getConfFileName().c_str();
return ""; return "";
......
...@@ -10,8 +10,8 @@ xmlfile(xfile) ...@@ -10,8 +10,8 @@ xmlfile(xfile)
{ {
try try
{ {
conf = new UniSetTypes::Configuration(p->argc,p->argv,xmlfile); conf = UniSetTypes::uniset_init(p->argc,p->argv,xmlfile);
ui = new UInterface(conf); ui = make_shared<UInterface>(conf);
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
{ {
...@@ -30,8 +30,8 @@ xmlfile(xfile) ...@@ -30,8 +30,8 @@ xmlfile(xfile)
{ {
try try
{ {
conf = new UniSetTypes::Configuration(argc,argv,xmlfile); conf = UniSetTypes::uniset_init(argc,argv,xmlfile);
ui = new UInterface(conf); ui = make_shared<UInterface>(conf);
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
{ {
...@@ -45,8 +45,6 @@ xmlfile(xfile) ...@@ -45,8 +45,6 @@ xmlfile(xfile)
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
UConnector::~UConnector() UConnector::~UConnector()
{ {
delete ui;
delete conf;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
const char* UConnector::getConfFileName() const char* UConnector::getConfFileName()
......
#ifndef UConnector_H_ #ifndef UConnector_H_
#define UConnector_H_ #define UConnector_H_
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <memory>
#include <string> #include <string>
#include "Configuration.h" #include "Configuration.h"
#include "UInterface.h" #include "UInterface.h"
...@@ -29,8 +30,8 @@ class UConnector ...@@ -29,8 +30,8 @@ class UConnector
private: private:
UniSetTypes::Configuration* conf; std::shared_ptr<UniSetTypes::Configuration> conf;
UInterface* ui; std::shared_ptr<UInterface> ui;
const char* xmlfile; const char* xmlfile;
}; };
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
......
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). * This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0 * Version 3.0.2
* *
* This file is not intended to be easily readable and contains a number of * This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make * coding conventions designed to improve portability and efficiency. Do not make
...@@ -2965,7 +2965,7 @@ static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0}; ...@@ -2965,7 +2965,7 @@ static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0};
#endif #endif
#define SWIG_name "_pyUConnector" #define SWIG_name "_pyUConnector"
#define SWIGVERSION 0x030000 #define SWIGVERSION 0x030002
#define SWIG_VERSION SWIGVERSION #define SWIG_VERSION SWIGVERSION
...@@ -3305,7 +3305,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) ...@@ -3305,7 +3305,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size)
SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
} else { } else {
#if PY_VERSION_HEX >= 0x03000000 #if PY_VERSION_HEX >= 0x03000000
#if PY_VERSION_HEX >= 0x03010000
return PyUnicode_DecodeUTF8(carray, static_cast< int >(size), "surrogateescape");
#else
return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); return PyUnicode_FromStringAndSize(carray, static_cast< int >(size));
#endif
#else #else
return PyString_FromStringAndSize(carray, static_cast< int >(size)); return PyString_FromStringAndSize(carray, static_cast< int >(size));
#endif #endif
......
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). * This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0 * Version 3.0.2
* *
* This file is not intended to be easily readable and contains a number of * This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make * coding conventions designed to improve portability and efficiency. Do not make
...@@ -2965,7 +2965,7 @@ static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0}; ...@@ -2965,7 +2965,7 @@ static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0};
#endif #endif
#define SWIG_name "_pyUExceptions" #define SWIG_name "_pyUExceptions"
#define SWIGVERSION 0x030000 #define SWIGVERSION 0x030002
#define SWIG_VERSION SWIGVERSION #define SWIG_VERSION SWIGVERSION
...@@ -3143,7 +3143,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) ...@@ -3143,7 +3143,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size)
SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
} else { } else {
#if PY_VERSION_HEX >= 0x03000000 #if PY_VERSION_HEX >= 0x03000000
#if PY_VERSION_HEX >= 0x03010000
return PyUnicode_DecodeUTF8(carray, static_cast< int >(size), "surrogateescape");
#else
return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); return PyUnicode_FromStringAndSize(carray, static_cast< int >(size));
#endif
#else #else
return PyString_FromStringAndSize(carray, static_cast< int >(size)); return PyString_FromStringAndSize(carray, static_cast< int >(size));
#endif #endif
......
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). * This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0 * Version 3.0.2
* *
* This file is not intended to be easily readable and contains a number of * This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make * coding conventions designed to improve portability and efficiency. Do not make
...@@ -2967,7 +2967,7 @@ static swig_module_info swig_module = {swig_types, 7, 0, 0, 0, 0}; ...@@ -2967,7 +2967,7 @@ static swig_module_info swig_module = {swig_types, 7, 0, 0, 0, 0};
#endif #endif
#define SWIG_name "_pyUniSet" #define SWIG_name "_pyUniSet"
#define SWIGVERSION 0x030000 #define SWIGVERSION 0x030002
#define SWIG_VERSION SWIGVERSION #define SWIG_VERSION SWIGVERSION
...@@ -3293,7 +3293,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) ...@@ -3293,7 +3293,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size)
SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
} else { } else {
#if PY_VERSION_HEX >= 0x03000000 #if PY_VERSION_HEX >= 0x03000000
#if PY_VERSION_HEX >= 0x03010000
return PyUnicode_DecodeUTF8(carray, static_cast< int >(size), "surrogateescape");
#else
return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); return PyUnicode_FromStringAndSize(carray, static_cast< int >(size));
#endif
#else #else
return PyString_FromStringAndSize(carray, static_cast< int >(size)); return PyString_FromStringAndSize(carray, static_cast< int >(size));
#endif #endif
......
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org). * This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0 * Version 3.0.2
* *
* This file is not intended to be easily readable and contains a number of * This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make * coding conventions designed to improve portability and efficiency. Do not make
...@@ -2968,7 +2968,7 @@ static swig_module_info swig_module = {swig_types, 8, 0, 0, 0, 0}; ...@@ -2968,7 +2968,7 @@ static swig_module_info swig_module = {swig_types, 8, 0, 0, 0, 0};
#endif #endif
#define SWIG_name "_pyUModbus" #define SWIG_name "_pyUModbus"
#define SWIGVERSION 0x030000 #define SWIGVERSION 0x030002
#define SWIG_VERSION SWIGVERSION #define SWIG_VERSION SWIGVERSION
...@@ -3067,7 +3067,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) ...@@ -3067,7 +3067,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size)
SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
} else { } else {
#if PY_VERSION_HEX >= 0x03000000 #if PY_VERSION_HEX >= 0x03000000
#if PY_VERSION_HEX >= 0x03010000
return PyUnicode_DecodeUTF8(carray, static_cast< int >(size), "surrogateescape");
#else
return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); return PyUnicode_FromStringAndSize(carray, static_cast< int >(size));
#endif
#else #else
return PyString_FromStringAndSize(carray, static_cast< int >(size)); return PyString_FromStringAndSize(carray, static_cast< int >(size));
#endif #endif
......
# This file was automatically generated by SWIG (http://www.swig.org). # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.0 # Version 3.0.2
# #
# Do not make changes to this file unless you know what you are doing--modify # Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead. # the SWIG interface file instead.
......
# This file was automatically generated by SWIG (http://www.swig.org). # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.0 # Version 3.0.2
# #
# Do not make changes to this file unless you know what you are doing--modify # Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead. # the SWIG interface file instead.
......
# This file was automatically generated by SWIG (http://www.swig.org). # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.0 # Version 3.0.2
# #
# Do not make changes to this file unless you know what you are doing--modify # Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead. # the SWIG interface file instead.
......
# This file was automatically generated by SWIG (http://www.swig.org). # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.0 # Version 3.0.2
# #
# Do not make changes to this file unless you know what you are doing--modify # Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead. # the SWIG interface file instead.
......
...@@ -1042,16 +1042,16 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout ...@@ -1042,16 +1042,16 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout
ostringstream err; ostringstream err;
err << "(0x50): bad crc. calc.crc=" << dat2str(tcrc) err << "(0x50): bad crc. calc.crc=" << dat2str(tcrc)
<< " msg.crc=" << dat2str(mSet.crc); << " msg.crc=" << dat2str(mSet.crc);
if( dlog.is_warn() ) if( dlog.is_warn() )
dlog.warn() << err.str() << endl; dlog.warn() << err.str() << endl;
return erBadCheckSum; return erBadCheckSum;
} }
} }
if( !mSet.checkFormat() ) if( !mSet.checkFormat() )
{ {
if( dlog.is_warn() ) if( dlog.is_warn() )
dlog.warn() << "(0x50): некорректные значения..." << endl; dlog.warn() << "(0x50): некорректные значения..." << endl;
return erBadDataValue; // return erInvalidFormat; return erBadDataValue; // return erInvalidFormat;
} }
...@@ -1070,13 +1070,13 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout ...@@ -1070,13 +1070,13 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout
if( rlen1 < szDataLen ) if( rlen1 < szDataLen )
{ {
rbuf.len = bcnt + rlen1 - szModbusHeader; rbuf.len = bcnt + rlen1 - szModbusHeader;
if( dlog.is_warn() ) if( dlog.is_warn() )
{ {
dlog.warn() << "(0x66): buf: " << rbuf << endl; dlog.warn() << "(0x66): buf: " << rbuf << endl;
dlog.warn() << "(0x66)(" dlog.warn() << "(0x66)("
<< rbuf.func << "):(fnFileTransfer) " << rbuf.func << "):(fnFileTransfer) "
<< "Получили данных меньше чем ждали...(" << "Получили данных меньше чем ждали...("
<< rlen1 << " < " << szDataLen << ")" << endl; << rlen1 << " < " << szDataLen << ")" << endl;
} }
cleanupChannel(); cleanupChannel();
return erInvalidFormat; return erInvalidFormat;
...@@ -1102,8 +1102,8 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout ...@@ -1102,8 +1102,8 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout
ostringstream err; ostringstream err;
err << "(0x66): bad crc. calc.crc=" << dat2str(tcrc) err << "(0x66): bad crc. calc.crc=" << dat2str(tcrc)
<< " msg.crc=" << dat2str(mFT.crc); << " msg.crc=" << dat2str(mFT.crc);
if( dlog.is_warn() ) if( dlog.is_warn() )
dlog.warn() << err.str() << endl; dlog.warn() << err.str() << endl;
return erBadCheckSum; return erBadCheckSum;
} }
...@@ -1236,14 +1236,14 @@ mbErrCode ModbusClient::send( ModbusMessage& msg ) ...@@ -1236,14 +1236,14 @@ mbErrCode ModbusClient::send( ModbusMessage& msg )
} }
catch( mbException& ex ) catch( mbException& ex )
{ {
if( dlog.is_crit() ) if( dlog.is_crit() )
dlog.crit() << "(send): " << ex << endl; dlog.crit() << "(send): " << ex << endl;
return ex.err; return ex.err;
} }
catch( Exception& ex ) // SystemError catch( Exception& ex ) // SystemError
{ {
if( dlog.is_crit() ) if( dlog.is_crit() )
dlog.crit() << "(send): " << ex << endl; dlog.crit() << "(send): " << ex << endl;
return erHardwareError; return erHardwareError;
} }
......
...@@ -40,7 +40,7 @@ using namespace UniversalIO; ...@@ -40,7 +40,7 @@ using namespace UniversalIO;
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UInterface::UInterface( const UniSetTypes::Configuration* _uconf ): UInterface::UInterface( const std::shared_ptr<UniSetTypes::Configuration>& _uconf ):
rep(_uconf), rep(_uconf),
myid(UniSetTypes::DefaultObjectId), myid(UniSetTypes::DefaultObjectId),
orb(CORBA::ORB::_nil()), orb(CORBA::ORB::_nil()),
...@@ -51,15 +51,15 @@ UInterface::UInterface( const UniSetTypes::Configuration* _uconf ): ...@@ -51,15 +51,15 @@ UInterface::UInterface( const UniSetTypes::Configuration* _uconf ):
init(); init();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UInterface::UInterface( const ObjectId backid, CORBA::ORB_var orb, shared_ptr<ObjectIndex> _oind ): UInterface::UInterface( const ObjectId backid, CORBA::ORB_var orb, const shared_ptr<ObjectIndex> _oind ):
rep(UniSetTypes::conf), rep(UniSetTypes::uniset_conf()),
myid(backid), myid(backid),
orb(orb), orb(orb),
rcache(200,40), rcache(200,40),
oind(_oind), oind(_oind),
uconf(UniSetTypes::conf) uconf(UniSetTypes::uniset_conf())
{ {
if( oind == NULL ) if( oind == nullptr )
oind = uconf->oind; oind = uconf->oind;
init(); init();
...@@ -1287,7 +1287,7 @@ IONotifyController_i::ThresholdInfo ...@@ -1287,7 +1287,7 @@ IONotifyController_i::ThresholdInfo
{ {
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = sid; si.id = sid;
si.node = conf->getLocalNode(); si.node = uconf->getLocalNode();
return getThresholdInfo(si,tid); return getThresholdInfo(si,tid);
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
...@@ -1609,7 +1609,7 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I ...@@ -1609,7 +1609,7 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I
CORBA::Object_var oref; CORBA::Object_var oref;
try try
{ {
oref = rcache.resolve(sid,conf->getLocalNode()); oref = rcache.resolve(sid,uconf->getLocalNode());
} }
catch( NameNotFound ){} catch( NameNotFound ){}
...@@ -1618,7 +1618,7 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I ...@@ -1618,7 +1618,7 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I
try try
{ {
if( CORBA::is_nil(oref) ) if( CORBA::is_nil(oref) )
oref = resolve(sid,conf->getLocalNode()); oref = resolve(sid,uconf->getLocalNode());
IOController_i_var iom = IOController_i::_narrow(oref); IOController_i_var iom = IOController_i::_narrow(oref);
...@@ -1635,29 +1635,29 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I ...@@ -1635,29 +1635,29 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I
catch(UniSetTypes::TimeOut){} catch(UniSetTypes::TimeOut){}
catch(IOController_i::NameNotFound &ex) catch(IOController_i::NameNotFound &ex)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::NameNotFound("UI(getSensorSeq): "+string(ex.err)); throw UniSetTypes::NameNotFound("UI(getSensorSeq): "+string(ex.err));
} }
catch(IOController_i::IOBadParam& ex) catch(IOController_i::IOBadParam& ex)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam("UI(getSensorSeq): "+string(ex.err)); throw UniSetTypes::IOBadParam("UI(getSensorSeq): "+string(ex.err));
} }
catch(ORepFailed) catch(ORepFailed)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
// не смогли получить ссылку на объект // не смогли получить ссылку на объект
throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): resolve failed ",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): resolve failed ",sid,uconf->getLocalNode()));
} }
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): method no implement",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): method no implement",sid,uconf->getLocalNode()));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): object not exist",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(getSensorSeq): object not exist",sid,uconf->getLocalNode()));
} }
catch(CORBA::COMM_FAILURE& ex) catch(CORBA::COMM_FAILURE& ex)
{ {
...@@ -1668,8 +1668,8 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I ...@@ -1668,8 +1668,8 @@ IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( const UniSetTypes::I
// ошибка системы коммуникации // ошибка системы коммуникации
// uwarn << "UI(getValue): CORBA::SystemException" << endl; // uwarn << "UI(getValue): CORBA::SystemException" << endl;
} }
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::TimeOut(set_err("UI(getSensorSeq): Timeout",sid,conf->getLocalNode())); throw UniSetTypes::TimeOut(set_err("UI(getSensorSeq): Timeout",sid,uconf->getLocalNode()));
} }
// -------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------
...@@ -1770,7 +1770,7 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst ...@@ -1770,7 +1770,7 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst
CORBA::Object_var oref; CORBA::Object_var oref;
try try
{ {
oref = rcache.resolve(sid,conf->getLocalNode()); oref = rcache.resolve(sid,uconf->getLocalNode());
} }
catch( NameNotFound ){} catch( NameNotFound ){}
...@@ -1779,7 +1779,7 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst ...@@ -1779,7 +1779,7 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst
try try
{ {
if( CORBA::is_nil(oref) ) if( CORBA::is_nil(oref) )
oref = resolve(sid,conf->getLocalNode()); oref = resolve(sid,uconf->getLocalNode());
IONotifyController_i_var iom = IONotifyController_i::_narrow(oref); IONotifyController_i_var iom = IONotifyController_i::_narrow(oref);
...@@ -1800,29 +1800,29 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst ...@@ -1800,29 +1800,29 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst
catch(UniSetTypes::TimeOut){} catch(UniSetTypes::TimeOut){}
catch(IOController_i::NameNotFound &ex) catch(IOController_i::NameNotFound &ex)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::NameNotFound("UI(getSensorSeq): "+string(ex.err)); throw UniSetTypes::NameNotFound("UI(getSensorSeq): "+string(ex.err));
} }
catch(IOController_i::IOBadParam& ex) catch(IOController_i::IOBadParam& ex)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam("UI(getSensorSeq): "+string(ex.err)); throw UniSetTypes::IOBadParam("UI(getSensorSeq): "+string(ex.err));
} }
catch(ORepFailed) catch(ORepFailed)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
// не смогли получить ссылку на объект // не смогли получить ссылку на объект
throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): resolve failed ",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): resolve failed ",sid,uconf->getLocalNode()));
} }
catch(CORBA::NO_IMPLEMENT) catch(CORBA::NO_IMPLEMENT)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): method no implement",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): method no implement",sid,uconf->getLocalNode()));
} }
catch(CORBA::OBJECT_NOT_EXIST) catch(CORBA::OBJECT_NOT_EXIST)
{ {
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): object not exist",sid,conf->getLocalNode())); throw UniSetTypes::IOBadParam(set_err("UI(askSensorSeq): object not exist",sid,uconf->getLocalNode()));
} }
catch(CORBA::COMM_FAILURE& ex) catch(CORBA::COMM_FAILURE& ex)
{ {
...@@ -1833,11 +1833,11 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst ...@@ -1833,11 +1833,11 @@ UniSetTypes::IDSeq_var UInterface::askSensorsSeq( const UniSetTypes::IDList& lst
// ошибка системы коммуникации // ошибка системы коммуникации
// uwarn << "UI(getValue): CORBA::SystemException" << endl; // uwarn << "UI(getValue): CORBA::SystemException" << endl;
} }
rcache.erase(sid,conf->getLocalNode()); rcache.erase(sid,uconf->getLocalNode());
throw UniSetTypes::TimeOut(set_err("UI(askSensorSeq): Timeout",sid,conf->getLocalNode())); throw UniSetTypes::TimeOut(set_err("UI(askSensorSeq): Timeout",sid,uconf->getLocalNode()));
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
IOController_i::ShortMapSeq* UInterface::getSensors( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) IOController_i::ShortMapSeq* UInterface::getSensors( const UniSetTypes::ObjectId id, UniSetTypes::ObjectId node )
{ {
if ( id == DefaultObjectId ) if ( id == DefaultObjectId )
throw ORepFailed("UI(getSensors): error node=UniSetTypes::DefaultObjectId"); throw ORepFailed("UI(getSensors): error node=UniSetTypes::DefaultObjectId");
...@@ -1913,11 +1913,11 @@ IOController_i::ShortMapSeq* UInterface::getSensors( const UniSetTypes::ObjectId ...@@ -1913,11 +1913,11 @@ IOController_i::ShortMapSeq* UInterface::getSensors( const UniSetTypes::ObjectId
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const ObjectId node ) bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const ObjectId node )
{ {
if( msec < 0 ) if( msec < 0 )
msec = 0; msec = 0;
if( pmsec < 0 ) if( pmsec < 0 )
pmsec = 0; pmsec = 0;
PassiveTimer ptReady(msec); PassiveTimer ptReady(msec);
bool ready = false; bool ready = false;
...@@ -1939,11 +1939,11 @@ bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const Object ...@@ -1939,11 +1939,11 @@ bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const Object
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const ObjectId node ) bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const ObjectId node )
{ {
if( msec < 0 ) if( msec < 0 )
msec = 0; msec = 0;
if( pmsec < 0 ) if( pmsec < 0 )
pmsec = 0; pmsec = 0;
PassiveTimer ptReady(msec); PassiveTimer ptReady(msec);
bool ready = false; bool ready = false;
...@@ -1965,10 +1965,10 @@ bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const Obje ...@@ -1965,10 +1965,10 @@ bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const Obje
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UniversalIO::IOType UInterface::getConfIOType( const UniSetTypes::ObjectId id ) const UniversalIO::IOType UInterface::getConfIOType( const UniSetTypes::ObjectId id ) const
{ {
if( !conf ) if( !uconf )
return UniversalIO::UnknownIOType; return UniversalIO::UnknownIOType;
xmlNode* x = conf->getXMLObjectNode(id); xmlNode* x = uconf->getXMLObjectNode(id);
if( !x ) if( !x )
return UniversalIO::UnknownIOType; return UniversalIO::UnknownIOType;
......
...@@ -150,13 +150,13 @@ protected: ...@@ -150,13 +150,13 @@ protected:
/// ///
virtual streamsize xsputn(char_type const * p, streamsize n) { virtual streamsize xsputn(char_type const * p, streamsize n) {
sb2->sputn(p, n); sb2->sputn(p, n);
sb3->sputn(p, n); sb3->sputn(p, n);
return sb1->sputn(p, n); return sb1->sputn(p, n);
} }
/// ///
virtual int_type overflow(int_type c = traits_type::eof()) { virtual int_type overflow(int_type c = traits_type::eof()) {
sb2->sputc(c); sb2->sputc(c);
sb3->sputc(c); sb3->sputc(c);
return sb1->sputc(c); return sb1->sputc(c);
} }
#else #else
...@@ -165,19 +165,19 @@ protected: ...@@ -165,19 +165,19 @@ protected:
/// ///
virtual int sync() { virtual int sync() {
sb2->sync(); sb2->sync();
sb3->sync(); sb3->sync();
return sb1->sync(); return sb1->sync();
} }
/// ///
virtual streamsize xsputn(char_type const * p, streamsize n) { virtual streamsize xsputn(char_type const * p, streamsize n) {
sb2->xsputn(p, n); sb2->xsputn(p, n);
sb2->xsputn(p, n); sb2->xsputn(p, n);
return sb1->xsputn(p, n); return sb1->xsputn(p, n);
} }
/// ///
virtual int_type overflow(int_type c = EOF) { virtual int_type overflow(int_type c = EOF) {
sb2->overflow(c); sb2->overflow(c);
sb3->owerflow(c); sb3->owerflow(c);
return sb1->overflow(c); return sb1->overflow(c);
} }
#endif #endif
...@@ -186,8 +186,8 @@ private: ...@@ -186,8 +186,8 @@ private:
streambuf * sb1; streambuf * sb1;
/// ///
streambuf * sb2; streambuf * sb2;
/// ///
streambuf * sb3; streambuf * sb3;
}; };
/// ///
...@@ -235,17 +235,17 @@ private: ...@@ -235,17 +235,17 @@ private:
class stringsigbuf : public streambuf { class stringsigbuf : public streambuf {
public: public:
stringsigbuf():sb(new stringbuf()) stringsigbuf():sb(new stringbuf())
{ {
} }
~stringsigbuf() ~stringsigbuf()
{ {
if( sb ) if( sb )
{ {
delete sb; delete sb;
sb = 0; sb = 0;
} }
} }
/// ///
stringsigbuf( stringbuf* b ) stringsigbuf( stringbuf* b )
......
...@@ -71,7 +71,7 @@ void IORFile::unlinkIOR( const ObjectId id ) const ...@@ -71,7 +71,7 @@ void IORFile::unlinkIOR( const ObjectId id ) const
string IORFile::genFName( const ObjectId id ) const string IORFile::genFName( const ObjectId id ) const
{ {
ostringstream fname; ostringstream fname;
fname << conf->getLockDir() << id; fname << uniset_conf()->getLockDir() << id;
return std::move( fname.str() ); return std::move( fname.str() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -87,6 +87,7 @@ std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi ) ...@@ -87,6 +87,7 @@ std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi )
std::ostream& ObjectIndex_Array::printMap( std::ostream& os ) std::ostream& ObjectIndex_Array::printMap( std::ostream& os )
{ {
auto oind = uniset_conf()->oind;
for( unsigned int i=0;;i++) for( unsigned int i=0;;i++)
{ {
if( !objectInfo[i].repName ) if( !objectInfo[i].repName )
...@@ -95,7 +96,7 @@ std::ostream& ObjectIndex_Array::printMap( std::ostream& os ) ...@@ -95,7 +96,7 @@ std::ostream& ObjectIndex_Array::printMap( std::ostream& os )
assert (i==objectInfo[i].id); assert (i==objectInfo[i].id);
os << setw(5) << objectInfo[i].id << " " os << setw(5) << objectInfo[i].id << " "
<< setw(45) << conf->oind->getBaseName(objectInfo[i].repName) << setw(45) << oind->getBaseName(objectInfo[i].repName)
<< " " << objectInfo[i].textName << endl; << " " << objectInfo[i].textName << endl;
} }
......
...@@ -36,7 +36,7 @@ using namespace UniSetTypes; ...@@ -36,7 +36,7 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
ObjectRepository::ObjectRepository( const Configuration* _conf ): ObjectRepository::ObjectRepository( const std::shared_ptr<UniSetTypes::Configuration>& _conf ):
nsName(_conf->getNSName()), nsName(_conf->getNSName()),
uconf(_conf) uconf(_conf)
{ {
......
...@@ -35,7 +35,7 @@ using namespace UniSetTypes; ...@@ -35,7 +35,7 @@ using namespace UniSetTypes;
using namespace std; using namespace std;
using namespace omni; using namespace omni;
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
ObjectRepositoryFactory::ObjectRepositoryFactory( Configuration* _conf ): ObjectRepositoryFactory::ObjectRepositoryFactory( const std::shared_ptr<UniSetTypes::Configuration>& _conf ):
ObjectRepository(_conf) ObjectRepository(_conf)
{ {
} }
......
...@@ -41,7 +41,7 @@ PassiveObject::PassiveObject( UniSetTypes::ObjectId id ): ...@@ -41,7 +41,7 @@ PassiveObject::PassiveObject( UniSetTypes::ObjectId id ):
mngr(0), mngr(0),
id(id) id(id)
{ {
string myfullname = conf->oind->getNameById(id); string myfullname = uniset_conf()->oind->getNameById(id);
myname = ORepHelpers::getShortName(myfullname.c_str()); myname = ORepHelpers::getShortName(myfullname.c_str());
} }
...@@ -49,7 +49,7 @@ PassiveObject::PassiveObject( ObjectId id, ProxyManager* mngr ): ...@@ -49,7 +49,7 @@ PassiveObject::PassiveObject( ObjectId id, ProxyManager* mngr ):
mngr(mngr), mngr(mngr),
id(id) id(id)
{ {
string myfullname = conf->oind->getNameById(id); string myfullname = uniset_conf()->oind->getNameById(id);
myname = ORepHelpers::getShortName(myfullname.c_str()); myname = ORepHelpers::getShortName(myfullname.c_str());
if( mngr ) if( mngr )
......
...@@ -84,7 +84,7 @@ bool ProxyManager::activateObject() ...@@ -84,7 +84,7 @@ bool ProxyManager::activateObject()
uinfo << myname << "(registered): попытка " uinfo << myname << "(registered): попытка "
<< i+1 << " регистриую (id=" << it.first << ") " << i+1 << " регистриую (id=" << it.first << ") "
<< " (pname=" << it.second->getName() << ") " << " (pname=" << it.second->getName() << ") "
<< conf->oind->getNameById(it.first) << endl; << uniset_conf()->oind->getNameById(it.first) << endl;
ui.registered(it.first, getRef(),true); ui.registered(it.first, getRef(),true);
break; break;
......
...@@ -80,10 +80,10 @@ UniSetActivatorPtr UniSetActivator::inst; ...@@ -80,10 +80,10 @@ UniSetActivatorPtr UniSetActivator::inst;
UniSetActivatorPtr UniSetActivator::Instance( const UniSetTypes::ObjectId id ) UniSetActivatorPtr UniSetActivator::Instance( const UniSetTypes::ObjectId id )
{ {
if( inst == nullptr ) if( inst == nullptr )
{ {
inst = shared_ptr<UniSetActivator>( new UniSetActivator(id) ); inst = shared_ptr<UniSetActivator>( new UniSetActivator(id) );
gActivator = inst; gActivator = inst;
} }
return inst; return inst;
} }
...@@ -92,7 +92,7 @@ UniSetActivatorPtr UniSetActivator::Instance( const UniSetTypes::ObjectId id ) ...@@ -92,7 +92,7 @@ UniSetActivatorPtr UniSetActivator::Instance( const UniSetTypes::ObjectId id )
void UniSetActivator::Destroy() void UniSetActivator::Destroy()
{ {
inst.reset(); inst.reset();
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -121,6 +121,7 @@ void UniSetActivator::init() ...@@ -121,6 +121,7 @@ void UniSetActivator::init()
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
myname = "UniSetActivator"; myname = "UniSetActivator";
auto conf = uniset_conf();
orb = conf->getORB(); orb = conf->getORB();
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj); PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj);
...@@ -363,10 +364,10 @@ void UniSetActivator::work() ...@@ -363,10 +364,10 @@ void UniSetActivator::work()
ulogsys << myname << "(work): orb thread stopped!" << endl; ulogsys << myname << "(work): orb thread stopped!" << endl;
try try
{ {
ulogsys << myname << "(oaDestroy): orb destroy... " << endl; ulogsys << myname << "(oaDestroy): orb destroy... " << endl;
orb->destroy(); orb->destroy();
} }
catch(omniORB::fatalException& fe) catch(omniORB::fatalException& fe)
{ {
......
...@@ -516,7 +516,7 @@ int UniSetManager::getObjectsInfo( UniSetManager* mngr, SimpleInfoSeq* seq, ...@@ -516,7 +516,7 @@ int UniSetManager::getObjectsInfo( UniSetManager* mngr, SimpleInfoSeq* seq,
catch(...) catch(...)
{ {
uwarn << myname << "(getObjectsInfo): не смог получить у объекта " uwarn << myname << "(getObjectsInfo): не смог получить у объекта "
<< conf->oind->getNameById( (*it)->getId() ) << " информацию" << endl; << uniset_conf()->oind->getNameById( (*it)->getId() ) << " информацию" << endl;
} }
} }
......
...@@ -168,6 +168,8 @@ void UniSetObject::init_object() ...@@ -168,6 +168,8 @@ void UniSetObject::init_object()
refmutex.setName(myname + "_refmutex"); refmutex.setName(myname + "_refmutex");
// mutex_act.setName(myname + "_mutex_act"); // mutex_act.setName(myname + "_mutex_act");
auto conf = uniset_conf();
SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000); SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000);
MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage")); MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage"));
if( MaxCountRemoveOfMessage <= 0 ) if( MaxCountRemoveOfMessage <= 0 )
...@@ -705,7 +707,7 @@ bool UniSetObject::activate() ...@@ -705,7 +707,7 @@ bool UniSetObject::activate()
throw ORepFailed(err.c_str()); throw ORepFailed(err.c_str());
} }
if( conf->isTransientIOR() ) if( uniset_conf()->isTransientIOR() )
{ {
// activate witch generate id // activate witch generate id
poa->activate_object(static_cast<PortableServer::ServantBase*>(this)); poa->activate_object(static_cast<PortableServer::ServantBase*>(this));
......
...@@ -104,7 +104,7 @@ long UniSetTypes::setoutregion(long ret, long calMin, long calMax) ...@@ -104,7 +104,7 @@ long UniSetTypes::setoutregion(long ret, long calMin, long calMax)
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniSetTypes::IDList::IDList(): UniSetTypes::IDList::IDList():
node(UniSetTypes::conf->getLocalNode()) node(UniSetTypes::uniset_conf()->getLocalNode())
{ {
} }
...@@ -232,8 +232,11 @@ bool UniSetTypes::is_digit( const std::string& s ) ...@@ -232,8 +232,11 @@ bool UniSetTypes::is_digit( const std::string& s )
//return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false; //return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
std::list<UniSetTypes::ParamSInfo> UniSetTypes::getSInfoList( const string& str, Configuration* conf ) std::list<UniSetTypes::ParamSInfo> UniSetTypes::getSInfoList( const string& str, std::shared_ptr<Configuration> conf )
{ {
if( conf == nullptr )
conf = uniset_conf();
std::list<UniSetTypes::ParamSInfo> res; std::list<UniSetTypes::ParamSInfo> res;
auto lst = UniSetTypes::explode_str(str,','); auto lst = UniSetTypes::explode_str(str,',');
...@@ -374,27 +377,27 @@ string UniSetTypes::dateToString(time_t tm, const std::string& brk ) ...@@ -374,27 +377,27 @@ string UniSetTypes::dateToString(time_t tm, const std::string& brk )
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
int UniSetTypes::uni_atoi( const char* str ) int UniSetTypes::uni_atoi( const char* str )
{ {
// if str is NULL or sscanf failed, we return 0 // if str is NULL or sscanf failed, we return 0
if( str == nullptr ) if( str == nullptr )
return 0; return 0;
// приходиться самостоятельно проверять на наличие префикса "0x" // приходиться самостоятельно проверять на наличие префикса "0x"
// чтобы применить соответствующую функцию. // чтобы применить соответствующую функцию.
// причём для чисел применяется atoll, // причём для чисел применяется atoll,
// чтобы корректно обрабатывать большие числа типа std::numeric_limits<unsigned int>::max() // чтобы корректно обрабатывать большие числа типа std::numeric_limits<unsigned int>::max()
// \warning есть сомнения, что на 64bit-тах это будет корректно работать.. // \warning есть сомнения, что на 64bit-тах это будет корректно работать..
int n = 0; int n = 0;
if( strlen(str) > 2 ) if( strlen(str) > 2 )
{ {
if( str[0]=='0' && str[1]=='x' ) if( str[0]=='0' && str[1]=='x' )
{ {
std::sscanf(str, "%x", &n); std::sscanf(str, "%x", &n);
return n; return n;
} }
} }
n = std::atoll(str); // универсальнее получать unsigned..чтобы не потерять "большие числа".. n = std::atoll(str); // универсальнее получать unsigned..чтобы не потерять "большие числа"..
return n; return n;
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
...@@ -49,7 +49,7 @@ IOController::IOController(const string& name, const string& section): ...@@ -49,7 +49,7 @@ IOController::IOController(const string& name, const string& section):
IOController::IOController(ObjectId id): IOController::IOController(ObjectId id):
UniSetManager(id), UniSetManager(id),
ioMutex(string(conf->oind->getMapName(id))+"_ioMutex"), ioMutex(string(uniset_conf()->oind->getMapName(id))+"_ioMutex"),
isPingDBServer(true) isPingDBServer(true)
{ {
} }
...@@ -145,7 +145,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const ...@@ -145,7 +145,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const
// ------------- // -------------
ostringstream err; ostringstream err;
err << myname << "(localGetValue): Not found sensor (" << sid << ") " err << myname << "(localGetValue): Not found sensor (" << sid << ") "
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -168,7 +168,7 @@ void IOController::localSetUndefinedState( IOStateList::iterator& li, ...@@ -168,7 +168,7 @@ void IOController::localSetUndefinedState( IOStateList::iterator& li,
{ {
ostringstream err; ostringstream err;
err << myname << "(localSetUndefined): Unknown sensor (" << sid << ")" err << myname << "(localSetUndefined): Unknown sensor (" << sid << ")"
<< "name: " << conf->oind->getNameById(sid); << "name: " << uniset_conf()->oind->getNameById(sid);
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
...@@ -255,7 +255,7 @@ void IOController::localSetValue( IOController::IOStateList::iterator& li, ...@@ -255,7 +255,7 @@ void IOController::localSetValue( IOController::IOStateList::iterator& li,
{ {
ostringstream err; ostringstream err;
err << myname << "(localSaveValue): Unknown sensor (" << sid << ")" err << myname << "(localSaveValue): Unknown sensor (" << sid << ")"
<< "name: " << conf->oind->getNameById(sid); << "name: " << uniset_conf()->oind->getNameById(sid);
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
...@@ -271,7 +271,7 @@ void IOController::localSetValue( IOController::IOStateList::iterator& li, ...@@ -271,7 +271,7 @@ void IOController::localSetValue( IOController::IOStateList::iterator& li,
if( checkIOFilters(li->second,value,sup_id) || blocked ) if( checkIOFilters(li->second,value,sup_id) || blocked )
{ {
uinfo << myname << ": save sensor value (" << sid << ")" uinfo << myname << ": save sensor value (" << sid << ")"
<< " name: " << conf->oind->getNameById(sid) << " name: " << uniset_conf()->oind->getNameById(sid)
<< " value="<< value << endl; << " value="<< value << endl;
long prev = li->second.value; long prev = li->second.value;
...@@ -328,7 +328,7 @@ IOType IOController::getIOType( UniSetTypes::ObjectId sid ) ...@@ -328,7 +328,7 @@ IOType IOController::getIOType( UniSetTypes::ObjectId sid )
return ali->second.type; return ali->second.type;
ostringstream err; ostringstream err;
err << myname << "(getIOType): датчик имя: " << conf->oind->getNameById(sid) << " не найден"; err << myname << "(getIOType): датчик имя: " << uniset_conf()->oind->getNameById(sid) << " не найден";
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -352,7 +352,7 @@ void IOController::ioRegistration( USensorInfo&& ainf, bool force ) ...@@ -352,7 +352,7 @@ void IOController::ioRegistration( USensorInfo&& ainf, bool force )
{ {
ostringstream err; ostringstream err;
err << "Попытка повторной регистрации датчика("<< ainf.si.id << "). имя: " err << "Попытка повторной регистрации датчика("<< ainf.si.id << "). имя: "
<< conf->oind->getNameById(ainf.si.id); << uniset_conf()->oind->getNameById(ainf.si.id);
throw ObjectNameAlready(err.str().c_str()); throw ObjectNameAlready(err.str().c_str());
} }
} }
...@@ -380,7 +380,7 @@ void IOController::ioRegistration( USensorInfo&& ainf, bool force ) ...@@ -380,7 +380,7 @@ void IOController::ioRegistration( USensorInfo&& ainf, bool force )
{ {
uinfo << myname uinfo << myname
<< "(ioRegistration): регистрирую " << "(ioRegistration): регистрирую "
<< conf->oind->getNameById(ainf.si.id) << endl; << uniset_conf()->oind->getNameById(ainf.si.id) << endl;
ui.registered( ainf.si.id, getRef(), true ); ui.registered( ainf.si.id, getRef(), true );
return; return;
...@@ -414,7 +414,7 @@ void IOController::logging( UniSetTypes::SensorMessage& sm ) ...@@ -414,7 +414,7 @@ void IOController::logging( UniSetTypes::SensorMessage& sm )
{ {
// struct timezone tz; // struct timezone tz;
// gettimeofday(&sm.tm,&tz); // gettimeofday(&sm.tm,&tz);
ObjectId dbID = conf->getDBServer(); ObjectId dbID = uniset_conf()->getDBServer();
// значит на этом узле нет DBServer-а // значит на этом узле нет DBServer-а
if( dbID == UniSetTypes::DefaultObjectId ) if( dbID == UniSetTypes::DefaultObjectId )
return; return;
...@@ -437,7 +437,7 @@ void IOController::logging( UniSetTypes::SensorMessage& sm ) ...@@ -437,7 +437,7 @@ void IOController::logging( UniSetTypes::SensorMessage& sm )
void IOController::dumpToDB() void IOController::dumpToDB()
{ {
// значит на этом узле нет DBServer-а // значит на этом узле нет DBServer-а
if( conf->getDBServer() == UniSetTypes::DefaultObjectId ) if( uniset_conf()->getDBServer() == UniSetTypes::DefaultObjectId )
return; return;
{ // lock { // lock
...@@ -500,7 +500,7 @@ IOController_i::SensorIOInfo IOController::getSensorIOInfo( const UniSetTypes::O ...@@ -500,7 +500,7 @@ IOController_i::SensorIOInfo IOController::getSensorIOInfo( const UniSetTypes::O
// ------------- // -------------
ostringstream err; ostringstream err;
err << myname << "(getSensorIOInfo): Unknown sensor (" << sid << ")" err << myname << "(getSensorIOInfo): Unknown sensor (" << sid << ")"
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
uinfo << err.str() << endl; uinfo << err.str() << endl;
...@@ -514,7 +514,7 @@ CORBA::Long IOController::getRawValue( UniSetTypes::ObjectId sid ) ...@@ -514,7 +514,7 @@ CORBA::Long IOController::getRawValue( UniSetTypes::ObjectId sid )
{ {
ostringstream err; ostringstream err;
err << myname << "(getRawValue): Unknown analog sensor (" << sid << ")" err << myname << "(getRawValue): Unknown analog sensor (" << sid << ")"
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
...@@ -542,11 +542,11 @@ void IOController::calibrate( UniSetTypes::ObjectId sid, ...@@ -542,11 +542,11 @@ void IOController::calibrate( UniSetTypes::ObjectId sid,
{ {
ostringstream err; ostringstream err;
err << myname << "(calibrate): Unknown analog sensor (" << sid << ")" err << myname << "(calibrate): Unknown analog sensor (" << sid << ")"
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
uinfo << myname <<"(calibrate): from " << conf->oind->getNameById(adminId) << endl; uinfo << myname <<"(calibrate): from " << uniset_conf()->oind->getNameById(adminId) << endl;
it->second.ci = ci; it->second.ci = ci;
} }
...@@ -558,7 +558,7 @@ IOController_i::CalibrateInfo IOController::getCalibrateInfo( UniSetTypes::Objec ...@@ -558,7 +558,7 @@ IOController_i::CalibrateInfo IOController::getCalibrateInfo( UniSetTypes::Objec
{ {
ostringstream err; ostringstream err;
err << myname << "(calibrate): Unknown analog sensor (" << sid << ")" err << myname << "(calibrate): Unknown analog sensor (" << sid << ")"
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
} }
return it->second.ci; return it->second.ci;
...@@ -717,7 +717,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( UniSetTypes::ObjectId ...@@ -717,7 +717,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( UniSetTypes::ObjectId
// ------------- // -------------
ostringstream err; ostringstream err;
err << myname << "(getChangedTime): вход(выход) с именем " err << myname << "(getChangedTime): вход(выход) с именем "
<< conf->oind->getNameById(sid) << " не найден"; << uniset_conf()->oind->getNameById(sid) << " не найден";
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -753,7 +753,7 @@ IOController::ChangeSignal IOController::signal_change_value( UniSetTypes::Objec ...@@ -753,7 +753,7 @@ IOController::ChangeSignal IOController::signal_change_value( UniSetTypes::Objec
{ {
ostringstream err; ostringstream err;
err << myname << "(signal_change_value): вход(выход) с именем " err << myname << "(signal_change_value): вход(выход) с именем "
<< conf->oind->getNameById(sid) << " не найден"; << uniset_conf()->oind->getNameById(sid) << " не найден";
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -775,7 +775,7 @@ IOController::ChangeUndefinedStateSignal IOController::signal_change_undefined_s ...@@ -775,7 +775,7 @@ IOController::ChangeUndefinedStateSignal IOController::signal_change_undefined_s
{ {
ostringstream err; ostringstream err;
err << myname << "(signal_change_undefine): вход(выход) с именем " err << myname << "(signal_change_undefine): вход(выход) с именем "
<< conf->oind->getNameById(sid) << " не найден"; << uniset_conf()->oind->getNameById(sid) << " не найден";
uinfo << err.str() << endl; uinfo << err.str() << endl;
......
...@@ -42,7 +42,7 @@ IONotifyController::IONotifyController(): ...@@ -42,7 +42,7 @@ IONotifyController::IONotifyController():
restorer(NULL), restorer(NULL),
askIOMutex("askIOMutex"), askIOMutex("askIOMutex"),
trshMutex("trshMutex"), trshMutex("trshMutex"),
maxAttemtps(conf->getPIntField("ConsumerMaxAttempts", 5)) maxAttemtps(uniset_conf()->getPIntField("ConsumerMaxAttempts", 5))
{ {
} }
...@@ -52,7 +52,7 @@ IONotifyController::IONotifyController(const string& name, const string& section ...@@ -52,7 +52,7 @@ IONotifyController::IONotifyController(const string& name, const string& section
restorer(d), restorer(d),
askIOMutex(name+"askIOMutex"), askIOMutex(name+"askIOMutex"),
trshMutex(name+"trshMutex"), trshMutex(name+"trshMutex"),
maxAttemtps(conf->getPIntField("ConsumerMaxAttempts", 5)) maxAttemtps(uniset_conf()->getPIntField("ConsumerMaxAttempts", 5))
{ {
// добавляем фильтры // добавляем фильтры
addIOFilter( sigc::mem_fun(this,&IONotifyController::myIOFilter) ); addIOFilter( sigc::mem_fun(this,&IONotifyController::myIOFilter) );
...@@ -61,9 +61,9 @@ IONotifyController::IONotifyController(const string& name, const string& section ...@@ -61,9 +61,9 @@ IONotifyController::IONotifyController(const string& name, const string& section
IONotifyController::IONotifyController( ObjectId id, NCRestorer* d ): IONotifyController::IONotifyController( ObjectId id, NCRestorer* d ):
IOController(id), IOController(id),
restorer(d), restorer(d),
askIOMutex(string(conf->oind->getMapName(id))+"_askIOMutex"), askIOMutex(string(uniset_conf()->oind->getMapName(id))+"_askIOMutex"),
trshMutex(string(conf->oind->getMapName(id))+"_trshMutex"), trshMutex(string(uniset_conf()->oind->getMapName(id))+"_trshMutex"),
maxAttemtps(conf->getPIntField("ConsumerMaxAttempts", 5)) maxAttemtps(uniset_conf()->getPIntField("ConsumerMaxAttempts", 5))
{ {
signal_change_undefined_state().connect(sigc::mem_fun(*this, &IONotifyController::onChangeUndefinedState)); signal_change_undefined_state().connect(sigc::mem_fun(*this, &IONotifyController::onChangeUndefinedState));
signal_init().connect(sigc::mem_fun(*this, &IONotifyController::initItem)); signal_init().connect(sigc::mem_fun(*this, &IONotifyController::initItem));
...@@ -133,9 +133,9 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid, ...@@ -133,9 +133,9 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
const UniSetTypes::ConsumerInfo& ci, UniversalIO::UIOCommand cmd ) const UniSetTypes::ConsumerInfo& ci, UniversalIO::UIOCommand cmd )
{ {
uinfo << "(askSensor): поступил " << ( cmd == UIODontNotify ? "отказ" :"заказ" ) << " от " uinfo << "(askSensor): поступил " << ( cmd == UIODontNotify ? "отказ" :"заказ" ) << " от "
<< conf->oind->getNameById(ci.id) << "@" << ci.node << uniset_conf()->oind->getNameById(ci.id) << "@" << ci.node
<< " на аналоговый датчик " << " на аналоговый датчик "
<< conf->oind->getNameById(sid) << endl; << uniset_conf()->oind->getNameById(sid) << endl;
// если такого аналогового датчика нет, здесь сработает исключение... // если такого аналогового датчика нет, здесь сработает исключение...
auto li = myioEnd(); auto li = myioEnd();
...@@ -156,7 +156,7 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid, ...@@ -156,7 +156,7 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
{ {
SensorMessage smsg; SensorMessage smsg;
smsg.id = sid; smsg.id = sid;
smsg.node = conf->getLocalNode(); smsg.node = uniset_conf()->getLocalNode();
smsg.consumer = ci.id; smsg.consumer = ci.id;
smsg.supplier = getId(); smsg.supplier = getId();
smsg.sensor_type = li->second.type; smsg.sensor_type = li->second.type;
...@@ -178,17 +178,17 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid, ...@@ -178,17 +178,17 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
uwarn << myname << "(askSensor): " << conf->oind->getNameById(sid) << " error: "<< ex << endl; uwarn << myname << "(askSensor): " << uniset_conf()->oind->getNameById(sid) << " error: "<< ex << endl;
} }
catch( CORBA::SystemException& ex ) catch( CORBA::SystemException& ex )
{ {
uwarn << myname << "(askSensor): " << conf->oind->getNameById(ci.id) << "@" << ci.node uwarn << myname << "(askSensor): " << uniset_conf()->oind->getNameById(ci.id) << "@" << ci.node
<< " недоступен!!(CORBA::SystemException): " << " недоступен!!(CORBA::SystemException): "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
} }
catch(...) catch(...)
{ {
uwarn << myname << "(askSensor): " << conf->oind->getNameById(ci.id) << "@" << ci.node uwarn << myname << "(askSensor): " << uniset_conf()->oind->getNameById(ci.id) << "@" << ci.node
<< " catch..." << endl; << " catch..." << endl;
} }
} }
...@@ -317,7 +317,7 @@ void IONotifyController::localSetValue( IOController::IOStateList::iterator& li, ...@@ -317,7 +317,7 @@ void IONotifyController::localSetValue( IOController::IOStateList::iterator& li,
{ {
ostringstream err; ostringstream err;
err << myname << "(localSetValue): вход(выход) с именем " err << myname << "(localSetValue): вход(выход) с именем "
<< conf->oind->getNameById(sid) << " не найден"; << uniset_conf()->oind->getNameById(sid) << " не найден";
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -337,7 +337,7 @@ void IONotifyController::localSetValue( IOController::IOStateList::iterator& li, ...@@ -337,7 +337,7 @@ void IONotifyController::localSetValue( IOController::IOStateList::iterator& li,
// Рассылаем уведомления только в слуае изменения значения // Рассылаем уведомления только в слуае изменения значения
sm.id = sid; sm.id = sid;
sm.node = conf->getLocalNode(); sm.node = uniset_conf()->getLocalNode();
sm.value = li->second.value; sm.value = li->second.value;
sm.undefined = li->second.undefined; sm.undefined = li->second.undefined;
sm.priority = (Message::Priority)li->second.priority; sm.priority = (Message::Priority)li->second.priority;
...@@ -408,18 +408,18 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage ...@@ -408,18 +408,18 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage
catch(Exception& ex) catch(Exception& ex)
{ {
uwarn << myname << "(IONotifyController::send): " << ex uwarn << myname << "(IONotifyController::send): " << ex
<< " for " << conf->oind->getNameById(li->id) << "@" << li->node << endl; << " for " << uniset_conf()->oind->getNameById(li->id) << "@" << li->node << endl;
} }
catch( CORBA::SystemException& ex ) catch( CORBA::SystemException& ex )
{ {
uwarn << myname << "(IONotifyController::send): " uwarn << myname << "(IONotifyController::send): "
<< conf->oind->getNameById(li->id) << "@" << li->node << " (CORBA::SystemException): " << uniset_conf()->oind->getNameById(li->id) << "@" << li->node << " (CORBA::SystemException): "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
} }
catch(...) catch(...)
{ {
ucrit << myname << "(IONotifyController::send): " ucrit << myname << "(IONotifyController::send): "
<< conf->oind->getNameById(li->id) << "@" << li->node << uniset_conf()->oind->getNameById(li->id) << "@" << li->node
<< " catch..." << endl; << " catch..." << endl;
} }
...@@ -545,7 +545,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp ...@@ -545,7 +545,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
ThresholdExtList lst; // создаем новый список ThresholdExtList lst; // создаем новый список
ThresholdsListInfo tli; ThresholdsListInfo tli;
tli.si.id = sid; tli.si.id = sid;
tli.si.node = conf->getLocalNode(); tli.si.node = uniset_conf()->getLocalNode();
tli.list = std::move(lst); tli.list = std::move(lst);
tli.type = li->second.type; tli.type = li->second.type;
tli.ait = myioEnd(); tli.ait = myioEnd();
...@@ -595,7 +595,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp ...@@ -595,7 +595,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
{ {
SensorMessage sm; SensorMessage sm;
sm.id = sid; sm.id = sid;
sm.node = conf->getLocalNode(); sm.node = uniset_conf()->getLocalNode();
sm.value = val; sm.value = val;
sm.undefined = li->second.undefined; sm.undefined = li->second.undefined;
sm.sensor_type = li->second.type; sm.sensor_type = li->second.type;
...@@ -743,7 +743,7 @@ void IONotifyController::checkThreshold( IOStateList::iterator& li, ...@@ -743,7 +743,7 @@ void IONotifyController::checkThreshold( IOStateList::iterator& li,
SensorMessage sm; SensorMessage sm;
sm.id = sid; sm.id = sid;
sm.node = conf->getLocalNode(); sm.node = uniset_conf()->getLocalNode();
sm.sensor_type = li->second.type; sm.sensor_type = li->second.type;
sm.priority = (Message::Priority)li->second.priority; sm.priority = (Message::Priority)li->second.priority;
sm.ci = li->second.ci; sm.ci = li->second.ci;
...@@ -853,7 +853,7 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet ...@@ -853,7 +853,7 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet
{ {
ostringstream err; ostringstream err;
err << myname << "(getThresholds): Not found sensor (" << sid << ") " err << myname << "(getThresholds): Not found sensor (" << sid << ") "
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -861,16 +861,16 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet ...@@ -861,16 +861,16 @@ IONotifyController_i::ThresholdInfo IONotifyController::getThresholdInfo( UniSet
for( auto it2= it->second.list.begin(); it2!=it->second.list.end(); ++it2 ) for( auto it2= it->second.list.begin(); it2!=it->second.list.end(); ++it2 )
{ {
/*! \warning На самом деле список разрешает иметь много порогов с одинаковым ID, для разных "заказчиков". /*! \warning На самом деле список разрешает иметь много порогов с одинаковым ID, для разных "заказчиков".
Но здесь мы возвращаем первый встретившийся.. Но здесь мы возвращаем первый встретившийся..
*/ */
if( it2->id == tid ) if( it2->id == tid )
return IONotifyController_i::ThresholdInfo( *it2 ); return IONotifyController_i::ThresholdInfo( *it2 );
} }
ostringstream err; ostringstream err;
err << myname << "(getThresholds): Not found for sensor (" << sid << ") " err << myname << "(getThresholds): Not found for sensor (" << sid << ") "
<< conf->oind->getNameById(sid) << " ThresholdID='" << tid << "'"; << uniset_conf()->oind->getNameById(sid) << " ThresholdID='" << tid << "'";
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -885,7 +885,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy ...@@ -885,7 +885,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy
{ {
ostringstream err; ostringstream err;
err << myname << "(getThresholds): Not found sensor (" << sid << ") " err << myname << "(getThresholds): Not found sensor (" << sid << ") "
<< conf->oind->getNameById(sid); << uniset_conf()->oind->getNameById(sid);
uinfo << err.str() << endl; uinfo << err.str() << endl;
throw IOController_i::NameNotFound(err.str().c_str()); throw IOController_i::NameNotFound(err.str().c_str());
...@@ -902,7 +902,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy ...@@ -902,7 +902,7 @@ IONotifyController_i::ThresholdList* IONotifyController::getThresholds( UniSetTy
catch( Exception& ex ) catch( Exception& ex )
{ {
uwarn << myname << "(getThresholdsList): для датчика " uwarn << myname << "(getThresholdsList): для датчика "
<< conf->oind->getNameById(it->second.si.id) << uniset_conf()->oind->getNameById(it->second.si.id)
<< " " << ex << endl; << " " << ex << endl;
} }
...@@ -944,7 +944,7 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList() ...@@ -944,7 +944,7 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
catch(Exception& ex) catch(Exception& ex)
{ {
uwarn << myname << "(getThresholdsList): для датчика " uwarn << myname << "(getThresholdsList): для датчика "
<< conf->oind->getNameById(it->second.si.id) << uniset_conf()->oind->getNameById(it->second.si.id)
<< " " << ex << endl; << " " << ex << endl;
continue; continue;
} }
......
...@@ -64,7 +64,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo&& inf, IONotifyControlle ...@@ -64,7 +64,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo&& inf, IONotifyControlle
default: default:
ucrit << ic->getName() << "(askDumper::addlist): НЕИЗВЕСТНЫЙ ТИП ДАТЧИКА! -> " ucrit << ic->getName() << "(askDumper::addlist): НЕИЗВЕСТНЫЙ ТИП ДАТЧИКА! -> "
<< conf->oind->getNameById(inf.si.id) << endl; << uniset_conf()->oind->getNameById(inf.si.id) << endl;
return; return;
break; break;
...@@ -83,7 +83,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo&& inf, IONotifyControlle ...@@ -83,7 +83,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo&& inf, IONotifyControlle
default: default:
ucrit << ic->getName() << "(NCRestorer::addlist): НЕИЗВЕСТНЫЙ ТИП ДАТЧИКА!-> " ucrit << ic->getName() << "(NCRestorer::addlist): НЕИЗВЕСТНЫЙ ТИП ДАТЧИКА!-> "
<< conf->oind->getNameById(inf.si.id) << endl; << uniset_conf()->oind->getNameById(inf.si.id) << endl;
break; break;
} }
} }
...@@ -155,8 +155,8 @@ void NCRestorer::init_depends_signals( IONotifyController* ic ) ...@@ -155,8 +155,8 @@ void NCRestorer::init_depends_signals( IONotifyController* ic )
continue; continue;
uinfo << ic->getName() << "(NCRestorer::init_depends_signals): " uinfo << ic->getName() << "(NCRestorer::init_depends_signals): "
<< " init depend: '" << conf->oind->getMapName(it->second.si.id) << "'" << " init depend: '" << uniset_conf()->oind->getMapName(it->second.si.id) << "'"
<< " dep_name=(" << it->second.d_si.id << ")'" << conf->oind->getMapName(it->second.d_si.id) << "'" << " dep_name=(" << it->second.d_si.id << ")'" << uniset_conf()->oind->getMapName(it->second.d_si.id) << "'"
<< endl; << endl;
IOController::ChangeSignal s = ic->signal_change_value(it->second.d_si.id); IOController::ChangeSignal s = ic->signal_change_value(it->second.d_si.id);
......
...@@ -85,8 +85,8 @@ void NCRestorer_XML::init( const std::string& fname ) ...@@ -85,8 +85,8 @@ void NCRestorer_XML::init( const std::string& fname )
*/ */
try try
{ {
if( fname == conf->getConfFileName() ) if( fname == uniset_conf()->getConfFileName() )
uxml = conf->getConfXML(); uxml = uniset_conf()->getConfXML();
else else
uxml = make_shared<UniXML>(fname); uxml = make_shared<UniXML>(fname);
} }
...@@ -163,12 +163,12 @@ void NCRestorer_XML::read_list( const std::shared_ptr<UniXML>& xml, xmlNode* nod ...@@ -163,12 +163,12 @@ void NCRestorer_XML::read_list( const std::shared_ptr<UniXML>& xml, xmlNode* nod
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void NCRestorer_XML::read( IONotifyController* ic, const string& fn ) void NCRestorer_XML::read( IONotifyController* ic, const string& fn )
{ {
const std::shared_ptr<UniXML> confxml = conf->getConfXML(); const std::shared_ptr<UniXML> confxml = uniset_conf()->getConfXML();
if( !fn.empty() ) if( !fn.empty() )
{ {
// оптимизация (не загружаем второй раз xml-файл) // оптимизация (не загружаем второй раз xml-файл)
if( fn == conf->getConfFileName() && confxml ) if( fn == uniset_conf()->getConfFileName() && confxml )
read( ic, confxml ); read( ic, confxml );
else else
{ {
...@@ -180,7 +180,7 @@ void NCRestorer_XML::read( IONotifyController* ic, const string& fn ) ...@@ -180,7 +180,7 @@ void NCRestorer_XML::read( IONotifyController* ic, const string& fn )
else if( !fname.empty() ) else if( !fname.empty() )
{ {
// оптимизация (не загружаем второй раз xml-файл) // оптимизация (не загружаем второй раз xml-файл)
if( fname == conf->getConfFileName() && confxml ) if( fname == uniset_conf()->getConfFileName() && confxml )
read( ic, confxml ); read( ic, confxml );
else if( uxml && uxml->isOpen() && uxml->filename == fn ) else if( uxml && uxml->isOpen() && uxml->filename == fn )
read(ic,uxml); read(ic,uxml);
...@@ -197,8 +197,8 @@ void NCRestorer_XML::read( IONotifyController* ic, const std::shared_ptr<UniXML> ...@@ -197,8 +197,8 @@ void NCRestorer_XML::read( IONotifyController* ic, const std::shared_ptr<UniXML>
{ {
xmlNode* node; xmlNode* node;
if( xml == conf->getConfXML() ) if( xml == uniset_conf()->getConfXML() )
node = conf->getXMLSensorsSection(); node = uniset_conf()->getXMLSensorsSection();
else else
node = xml->findNode( xml->getFirstNode(),"sensors"); node = xml->findNode( xml->getFirstNode(),"sensors");
...@@ -232,7 +232,7 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i ...@@ -232,7 +232,7 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i
if( !id.empty() ) if( !id.empty() )
sid = uni_atoi( id ); sid = uni_atoi( id );
else else
sid = conf->getSensorID(sname); sid = uniset_conf()->getSensorID(sname);
if( sid == UniSetTypes::DefaultObjectId ) if( sid == UniSetTypes::DefaultObjectId )
{ {
...@@ -240,10 +240,10 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i ...@@ -240,10 +240,10 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i
return false; return false;
} }
ObjectId snode = conf->getLocalNode(); ObjectId snode = uniset_conf()->getLocalNode();
string snodename(xml->getProp(it,"node")); string snodename(xml->getProp(it,"node"));
if( !snodename.empty() ) if( !snodename.empty() )
snode = conf->getNodeID(snodename); snode = uniset_conf()->getNodeID(snodename);
if( snode == UniSetTypes::DefaultObjectId ) if( snode == UniSetTypes::DefaultObjectId )
{ {
...@@ -309,7 +309,7 @@ bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* ...@@ -309,7 +309,7 @@ bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode*
string d_txt( xml->getProp(it, "depend") ); string d_txt( xml->getProp(it, "depend") );
if( !d_txt.empty() ) if( !d_txt.empty() )
{ {
inf.d_si.id = conf->getSensorID(d_txt); inf.d_si.id = uniset_conf()->getSensorID(d_txt);
if( inf.d_si.id == UniSetTypes::DefaultObjectId ) if( inf.d_si.id == UniSetTypes::DefaultObjectId )
{ {
ucrit << "(NCRestorer_XML:getSensorInfo): sensor='" ucrit << "(NCRestorer_XML:getSensorInfo): sensor='"
...@@ -319,7 +319,7 @@ bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* ...@@ -319,7 +319,7 @@ bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode*
return false; return false;
} }
inf.d_si.node = conf->getLocalNode(); inf.d_si.node = uniset_conf()->getLocalNode();
// по умолчанию срабатывание на "1" // по умолчанию срабатывание на "1"
inf.d_value = xml->getProp(it,"depend_value").empty() ? 1 : xml->getIntProp(it,"depend_value"); inf.d_value = xml->getProp(it,"depend_value").empty() ? 1 : xml->getIntProp(it,"depend_value");
...@@ -363,7 +363,7 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -363,7 +363,7 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
uwarn << ic->getName() uwarn << ic->getName()
<< "(read_thresholds): не смог получить информацию о пороге" << "(read_thresholds): не смог получить информацию о пороге"
<< " для датчика " << " для датчика "
<< conf->oind->getNameById(inf.si.id) << endl; << uniset_conf()->oind->getNameById(inf.si.id) << endl;
continue; continue;
} }
...@@ -384,7 +384,7 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -384,7 +384,7 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
uwarn << ic->getName() uwarn << ic->getName()
<< "(read_thresholds): не смог получить список заказчиков" << "(read_thresholds): не смог получить список заказчиков"
<< " для порога " << ti.id << " для порога " << ti.id
<< " датчика " << conf->oind->getNameById(inf.si.id) << endl; << " датчика " << uniset_conf()->oind->getNameById(inf.si.id) << endl;
} }
} }
} }
...@@ -447,7 +447,7 @@ bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml,xmlNod ...@@ -447,7 +447,7 @@ bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml,xmlNod
string sid_name = uit.getProp("sid"); string sid_name = uit.getProp("sid");
if( !sid_name.empty() ) if( !sid_name.empty() )
{ {
ti.sid = conf->getSensorID(sid_name); ti.sid = uniset_conf()->getSensorID(sid_name);
if( ti.sid == UniSetTypes::DefaultObjectId ) if( ti.sid == UniSetTypes::DefaultObjectId )
{ {
ucrit << "(NCRestorer_XML:getThresholdInfo): " ucrit << "(NCRestorer_XML:getThresholdInfo): "
...@@ -455,7 +455,7 @@ bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml,xmlNod ...@@ -455,7 +455,7 @@ bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml,xmlNod
} }
else else
{ {
UniversalIO::IOType iotype = conf->getIOType(ti.sid); UniversalIO::IOType iotype = uniset_conf()->getIOType(ti.sid);
// Пока что IONotifyController поддерживает работу только с 'DI'. // Пока что IONotifyController поддерживает работу только с 'DI'.
if( iotype != UniversalIO::DI ) if( iotype != UniversalIO::DI )
{ {
......
...@@ -41,7 +41,7 @@ DBServer::DBServer(ObjectId id): ...@@ -41,7 +41,7 @@ DBServer::DBServer(ObjectId id):
{ {
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
id = conf->getDBServer(); id = uniset_conf()->getDBServer();
if( id == DefaultObjectId ) if( id == DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -53,11 +53,11 @@ DBServer::DBServer(ObjectId id): ...@@ -53,11 +53,11 @@ DBServer::DBServer(ObjectId id):
} }
DBServer::DBServer(): DBServer::DBServer():
UniSetObject_LT(conf->getDBServer()) UniSetObject_LT(uniset_conf()->getDBServer())
{ {
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
ObjectId id = conf->getDBServer(); ObjectId id = uniset_conf()->getDBServer();
if( id == DefaultObjectId ) if( id == DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -81,7 +81,7 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage *msg ) ...@@ -81,7 +81,7 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage *msg )
break; break;
default: default:
UniSetObject_LT::processingMessage(msg); UniSetObject_LT::processingMessage(msg);
break; break;
} }
......
...@@ -71,11 +71,23 @@ ostream& UniSetTypes::Configuration::help(ostream& os) ...@@ -71,11 +71,23 @@ ostream& UniSetTypes::Configuration::help(ostream& os)
<< "--ulog-add-levels level1,info,system,warn --ulog-log-in-file myprogrpam.log\n\n"; << "--ulog-add-levels level1,info,system,warn --ulog-log-in-file myprogrpam.log\n\n";
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace UniSetTypes namespace UniSetTypes
{ {
DebugStream ulog; DebugStream ulog;
Configuration* conf = 0;
static shared_ptr<Configuration> uconf;
std::shared_ptr<Configuration> uniset_conf()
{
if( uconf == nullptr )
throw SystemError("Don`t init uniset configuration! First use uniset_init().");
return uconf; // см. uniset_init..
}
// -------------------------------------------------------------------------
Configuration::Configuration(): Configuration::Configuration():
oind(NULL), oind(NULL),
...@@ -147,8 +159,8 @@ Configuration::Configuration( int argc, const char* const* argv, const string& f ...@@ -147,8 +159,8 @@ Configuration::Configuration( int argc, const char* const* argv, const string& f
if( fileConf.empty() ) if( fileConf.empty() )
setConfFileName(); setConfFileName();
ObjectIndex_Array* _oi = new ObjectIndex_Array(omap); ObjectIndex_Array* _oi = new ObjectIndex_Array(omap);
oind = shared_ptr<ObjectIndex>(_oi); oind = shared_ptr<ObjectIndex>(_oi);
initConfiguration(argc,argv); initConfiguration(argc,argv);
} }
...@@ -158,7 +170,7 @@ void Configuration::initConfiguration( int argc, const char* const* argv ) ...@@ -158,7 +170,7 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
// PassiveTimer pt(UniSetTimer::WaitUpTime); // PassiveTimer pt(UniSetTimer::WaitUpTime);
ulogsys << "*** configure from file: " << fileConfName << endl; ulogsys << "*** configure from file: " << fileConfName << endl;
iorfile = make_shared<IORFile>(); iorfile = make_shared<IORFile>();
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
xmlSensorsSec = 0; xmlSensorsSec = 0;
...@@ -183,8 +195,8 @@ void Configuration::initConfiguration( int argc, const char* const* argv ) ...@@ -183,8 +195,8 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
try try
{ {
if( unixml == nullptr ) if( unixml == nullptr )
unixml = std::shared_ptr<UniXML>( new UniXML() ); unixml = std::shared_ptr<UniXML>( new UniXML() );
if( !unixml->isOpen() ) if( !unixml->isOpen() )
{ {
...@@ -216,15 +228,15 @@ void Configuration::initConfiguration( int argc, const char* const* argv ) ...@@ -216,15 +228,15 @@ void Configuration::initConfiguration( int argc, const char* const* argv )
try try
{ {
if( it.getIntProp("idfromfile") == 0 ) if( it.getIntProp("idfromfile") == 0 )
{ {
ObjectIndex_XML* oi = new ObjectIndex_XML(unixml); //(fileConfName); ObjectIndex_XML* oi = new ObjectIndex_XML(unixml); //(fileConfName);
oind = shared_ptr<ObjectIndex>(oi); oind = shared_ptr<ObjectIndex>(oi);
} }
else else
{ {
ObjectIndex_idXML* oi = new ObjectIndex_idXML(unixml); //(fileConfName); ObjectIndex_idXML* oi = new ObjectIndex_idXML(unixml); //(fileConfName);
oind = shared_ptr<ObjectIndex>(oi); oind = shared_ptr<ObjectIndex>(oi);
} }
} }
catch(Exception& ex ) catch(Exception& ex )
{ {
...@@ -982,19 +994,18 @@ UniversalIO::IOType Configuration::getIOType( const std::string& name ) ...@@ -982,19 +994,18 @@ UniversalIO::IOType Configuration::getIOType( const std::string& name )
return UniversalIO::UnknownIOType; return UniversalIO::UnknownIOType;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void uniset_init( int argc, const char* const* argv, const std::string& xmlfile, bool force ) std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile )
{ {
if( UniSetTypes::uconf )
{
cerr << "Reusable call uniset_init... ignore.." << endl;
return UniSetTypes::uconf;
}
string confile = UniSetTypes::getArgParam( "--confile", argc, argv, xmlfile ); string confile = UniSetTypes::getArgParam( "--confile", argc, argv, xmlfile );
ulog.setLogName("ulog"); ulog.setLogName("ulog");
if( UniSetTypes::conf ) UniSetTypes::uconf = make_shared<Configuration>(argc, argv, confile);
{ return UniSetTypes::uconf;
if( !force && confile == UniSetTypes::conf->getConfFileName() )
return;
delete UniSetTypes::conf;
}
UniSetTypes::conf = new Configuration(argc, argv, confile);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of UniSetTypes namespace } // end of UniSetTypes namespace
...@@ -35,7 +35,7 @@ namespace UniSetTypes ...@@ -35,7 +35,7 @@ namespace UniSetTypes
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
Message::Message(): Message::Message():
type(Unused), priority(Medium), type(Unused), priority(Medium),
node(UniSetTypes::conf->getLocalNode()), node(UniSetTypes::uniset_conf()->getLocalNode()),
supplier(DefaultObjectId), supplier(DefaultObjectId),
consumer(DefaultObjectId) consumer(DefaultObjectId)
{ {
......
...@@ -72,11 +72,11 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it, ...@@ -72,11 +72,11 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it,
string otype(it.getProp("type")); string otype(it.getProp("type"));
if( otype == "controllers" ) if( otype == "controllers" )
cname = conf->getControllersSection()+"/"+cname; cname = uniset_conf()->getControllersSection()+"/"+cname;
else if( otype == "objects" ) else if( otype == "objects" )
cname = conf->getObjectsSection()+"/"+cname; cname = uniset_conf()->getObjectsSection()+"/"+cname;
else if( otype == "services" ) else if( otype == "services" )
cname = conf->getServicesSection()+"/"+cname; cname = uniset_conf()->getServicesSection()+"/"+cname;
else else
{ {
uwarn << "(Restorer_XML:getConsumerInfo): неизвестный тип объекта " uwarn << "(Restorer_XML:getConsumerInfo): неизвестный тип объекта "
...@@ -84,7 +84,7 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it, ...@@ -84,7 +84,7 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it,
return false; return false;
} }
cid = conf->oind->getIdByName(cname); cid = uniset_conf()->oind->getIdByName(cname);
if( cid == UniSetTypes::DefaultObjectId ) if( cid == UniSetTypes::DefaultObjectId )
{ {
ucrit << "(Restorer_XML:getConsumerInfo): НЕ НАЙДЕН ИДЕНТИФИКАТОР заказчика -->" ucrit << "(Restorer_XML:getConsumerInfo): НЕ НАЙДЕН ИДЕНТИФИКАТОР заказчика -->"
...@@ -94,9 +94,9 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it, ...@@ -94,9 +94,9 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it,
string cnodename(it.getProp("node")); string cnodename(it.getProp("node"));
if( !cnodename.empty() ) if( !cnodename.empty() )
cnode = conf->oind->getIdByName(cnodename); cnode = uniset_conf()->oind->getIdByName(cnodename);
else else
cnode = conf->getLocalNode(); cnode = uniset_conf()->getLocalNode();
if( cnode == UniSetTypes::DefaultObjectId ) if( cnode == UniSetTypes::DefaultObjectId )
{ {
......
...@@ -20,14 +20,14 @@ SMonitor::SMonitor(ObjectId id): ...@@ -20,14 +20,14 @@ SMonitor::SMonitor(ObjectId id):
UniSetObject_LT(id), UniSetObject_LT(id),
script("") script("")
{ {
string sid(conf->getArgParam("--sid")); string sid(uniset_conf()->getArgParam("--sid"));
lst = UniSetTypes::getSInfoList(sid,UniSetTypes::conf); lst = UniSetTypes::getSInfoList(sid,uniset_conf());
if( lst.empty() ) if( lst.empty() )
throw SystemError("Не задан список датчиков (--sid)"); throw SystemError("Не задан список датчиков (--sid)");
script = conf->getArgParam("--script"); script = uniset_conf()->getArgParam("--script");
} }
...@@ -49,7 +49,7 @@ void SMonitor::sysCommand( const SystemMessage *sm ) ...@@ -49,7 +49,7 @@ void SMonitor::sysCommand( const SystemMessage *sm )
for( auto &it: lst ) for( auto &it: lst )
{ {
if( it.si.node == DefaultObjectId ) if( it.si.node == DefaultObjectId )
it.si.node = conf->getLocalNode(); it.si.node = uniset_conf()->getLocalNode();
try try
{ {
...@@ -86,7 +86,7 @@ void SMonitor::sensorInfo( const SensorMessage* si ) ...@@ -86,7 +86,7 @@ void SMonitor::sensorInfo( const SensorMessage* si )
{ {
cout << "(" << setw(6) << si->id << "): " << setw(8) << timeToString(si->sm_tv_sec,":") cout << "(" << setw(6) << si->id << "): " << setw(8) << timeToString(si->sm_tv_sec,":")
<< "(" << setw(6) << si->sm_tv_usec << "): "; << "(" << setw(6) << si->sm_tv_usec << "): ";
cout << setw(45) << conf->oind->getMapName(si->id); cout << setw(45) << uniset_conf()->oind->getMapName(si->id);
cout << "\tvalue=" << si->value << "\tfvalue=" << ( (float)si->value / pow(10.0,si->ci.precision) ) << endl; cout << "\tvalue=" << si->value << "\tfvalue=" << ( (float)si->value / pow(10.0,si->ci.precision) ) << endl;
if( !script.empty() ) if( !script.empty() )
...@@ -97,7 +97,7 @@ void SMonitor::sensorInfo( const SensorMessage* si ) ...@@ -97,7 +97,7 @@ void SMonitor::sensorInfo( const SensorMessage* si )
if( script[0] == '.' || script[0] == '/' ) if( script[0] == '.' || script[0] == '/' )
cmd << script; cmd << script;
else else
cmd << conf->getBinDir() << script; cmd << uniset_conf()->getBinDir() << script;
cmd << " " << si->id << " " << si->value << " " << si->sm_tv_sec << " " << si->sm_tv_usec; cmd << " " << si->id << " " << si->value << " " << si->sm_tv_sec << " " << si->sm_tv_usec;
......
...@@ -37,9 +37,9 @@ using namespace std; ...@@ -37,9 +37,9 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
SViewer::SViewer(const string& csec, bool sn): SViewer::SViewer(const string& csec, bool sn):
csec(csec), csec(csec),
rep(UniSetTypes::conf), rep(UniSetTypes::uniset_conf()),
cache(500, 15), cache(500, 15),
ui(UniSetTypes::conf), ui(UniSetTypes::uniset_conf()),
isShort(sn) isShort(sn)
{ {
} }
...@@ -140,7 +140,7 @@ void SViewer::readSection( const string& section, const string& secRoot ) ...@@ -140,7 +140,7 @@ void SViewer::readSection( const string& section, const string& secRoot )
{ {
string ob(*li); string ob(*li);
string fname(curSection+ "/"+ ob); string fname(curSection+ "/"+ ob);
ObjectId id = conf->oind->getIdByName( fname ); ObjectId id = uniset_conf()->oind->getIdByName( fname );
if( id == DefaultObjectId ) if( id == DefaultObjectId )
cout << "(readSection): ID?! для " << fname << endl; cout << "(readSection): ID?! для " << fname << endl;
else else
...@@ -165,14 +165,14 @@ void SViewer::getInfo( ObjectId id ) ...@@ -165,14 +165,14 @@ void SViewer::getInfo( ObjectId id )
{ {
try try
{ {
oref = cache.resolve(id, conf->getLocalNode()); oref = cache.resolve(id, uniset_conf()->getLocalNode());
} }
catch( NameNotFound ){} catch( NameNotFound ){}
if( CORBA::is_nil(oref) ) if( CORBA::is_nil(oref) )
{ {
oref = ui.resolve(id); oref = ui.resolve(id);
cache.cache(id, conf->getLocalNode(), oref); cache.cache(id, uniset_conf()->getLocalNode(), oref);
} }
IONotifyController_i_var ioc = IONotifyController_i::_narrow(oref); IONotifyController_i_var ioc = IONotifyController_i::_narrow(oref);
...@@ -204,13 +204,13 @@ void SViewer::getInfo( ObjectId id ) ...@@ -204,13 +204,13 @@ void SViewer::getInfo( ObjectId id )
cout << "(getInfo): catch ..." << endl; cout << "(getInfo): catch ..." << endl;
} }
cache.erase(id, conf->getLocalNode()); cache.erase(id, uniset_conf()->getLocalNode());
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetTypes::ObjectId oid ) void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetTypes::ObjectId oid )
{ {
string owner = ORepHelpers::getShortName(conf->oind->getMapName(oid)); string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
cout << "\n======================================================\n" << owner; cout << "\n======================================================\n" << owner;
cout << "\t Датчики"; cout << "\t Датчики";
cout << "\n------------------------------------------------------"<< endl; cout << "\n------------------------------------------------------"<< endl;
...@@ -219,10 +219,10 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType ...@@ -219,10 +219,10 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType
{ {
if( amap[i].type == UniversalIO::AI || amap[i].type == UniversalIO::DI ) if( amap[i].type == UniversalIO::AI || amap[i].type == UniversalIO::DI )
{ {
string name(conf->oind->getNameById(amap[i].si.id)); string name(uniset_conf()->oind->getNameById(amap[i].si.id));
if( isShort ) if( isShort )
name = ORepHelpers::getShortName(name); name = ORepHelpers::getShortName(name);
string txtname( conf->oind->getTextName(amap[i].si.id) ); string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
printInfo( amap[i].si.id, name, amap[i].value, owner, txtname, "AI"); printInfo( amap[i].si.id, name, amap[i].value, owner, txtname, "AI");
} }
} }
...@@ -235,10 +235,10 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType ...@@ -235,10 +235,10 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType
{ {
if( amap[i].type == UniversalIO::AO || amap[i].type == UniversalIO::DO ) if( amap[i].type == UniversalIO::AO || amap[i].type == UniversalIO::DO )
{ {
string name(conf->oind->getNameById(amap[i].si.id)); string name(uniset_conf()->oind->getNameById(amap[i].si.id));
if( isShort ) if( isShort )
name = ORepHelpers::getShortName(name); name = ORepHelpers::getShortName(name);
string txtname( conf->oind->getTextName(amap[i].si.id) ); string txtname( uniset_conf()->oind->getTextName(amap[i].si.id) );
printInfo( amap[i].si.id, name, amap[i].value, owner, txtname, "AO"); printInfo( amap[i].si.id, name, amap[i].value, owner, txtname, "AO");
} }
} }
...@@ -249,7 +249,7 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType ...@@ -249,7 +249,7 @@ void SViewer::updateSensors( IOController_i::SensorInfoSeq_var& amap, UniSetType
void SViewer::updateThresholds( IONotifyController_i::ThresholdsListSeq_var& tlst, UniSetTypes::ObjectId oid ) void SViewer::updateThresholds( IONotifyController_i::ThresholdsListSeq_var& tlst, UniSetTypes::ObjectId oid )
{ {
int size = tlst->length(); int size = tlst->length();
string owner = ORepHelpers::getShortName(conf->oind->getMapName(oid)); string owner = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(oid));
cout << "\n======================================================\n" << owner; cout << "\n======================================================\n" << owner;
cout << "\t Пороговые датчики"; cout << "\t Пороговые датчики";
cout << "\n------------------------------------------------------"<< endl; cout << "\n------------------------------------------------------"<< endl;
...@@ -272,7 +272,7 @@ void SViewer::updateThresholds( IONotifyController_i::ThresholdsListSeq_var& tls ...@@ -272,7 +272,7 @@ void SViewer::updateThresholds( IONotifyController_i::ThresholdsListSeq_var& tls
break; break;
} }
string sname(conf->oind->getNameById(tlst[i].si.id)); string sname(uniset_conf()->oind->getNameById(tlst[i].si.id));
if( isShort ) if( isShort )
sname = ORepHelpers::getShortName(sname); sname = ORepHelpers::getShortName(sname);
......
...@@ -475,31 +475,31 @@ bool UniXML_iterator::find( const std::string& searchnode ) ...@@ -475,31 +475,31 @@ bool UniXML_iterator::find( const std::string& searchnode )
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator++() UniXML_iterator UniXML_iterator::operator++()
{ {
return (*this)+1; return (*this)+1;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator++(int) UniXML_iterator UniXML_iterator::operator++(int)
{ {
return (*this)+1; return (*this)+1;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator+=(int s) UniXML_iterator UniXML_iterator::operator+=(int s)
{ {
return (*this)+s; return (*this)+s;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator+(int step) UniXML_iterator UniXML_iterator::operator+(int step)
{ {
int i = 0; int i = 0;
while( i<step && curNode ) while( i<step && curNode )
{ {
curNode = curNode->next; curNode = curNode->next;
if( curNode ) if( curNode )
{ {
if( getName() == "text" || getName() == "comment" ) if( getName() == "text" || getName() == "comment" )
continue; continue;
i++; i++;
} }
} }
return *this; return *this;
...@@ -507,32 +507,32 @@ UniXML_iterator UniXML_iterator::operator+(int step) ...@@ -507,32 +507,32 @@ UniXML_iterator UniXML_iterator::operator+(int step)
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator--(int) UniXML_iterator UniXML_iterator::operator--(int)
{ {
return (*this)-1; return (*this)-1;
} }
UniXML_iterator UniXML_iterator::operator--() UniXML_iterator UniXML_iterator::operator--()
{ {
return (*this)-1; return (*this)-1;
} }
UniXML_iterator UniXML_iterator::operator-=(int s) UniXML_iterator UniXML_iterator::operator-=(int s)
{ {
return (*this)-s; return (*this)-s;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UniXML_iterator UniXML_iterator::operator-(int step) UniXML_iterator UniXML_iterator::operator-(int step)
{ {
int i=0; int i=0;
while( i<step && curNode ) while( i<step && curNode )
{ {
curNode = curNode->prev; curNode = curNode->prev;
if( curNode ) if( curNode )
{ {
if( getName() == "text" || getName() == "comment" ) if( getName() == "text" || getName() == "comment" )
continue; continue;
i++; i++;
} }
} }
return (*this); return (*this);
......
...@@ -6,74 +6,74 @@ using namespace std; ...@@ -6,74 +6,74 @@ using namespace std;
class MyTestClass class MyTestClass
{ {
public: public:
MyTestClass():num1(0),num2(0),num3(0){} MyTestClass():num1(0),num2(0),num3(0){}
~MyTestClass(){} ~MyTestClass(){}
void Time( int id ) void Time( int id )
{ {
if( id == 1 ) if( id == 1 )
num1++; num1++;
else if( id == 2 ) else if( id == 2 )
num2++; num2++;
else if( id == 3 ) else if( id == 3 )
num3++; num3++;
} }
inline int getNum1(){ return num1; } inline int getNum1(){ return num1; }
inline int getNum2(){ return num2; } inline int getNum2(){ return num2; }
inline int getNum3(){ return num3; } inline int getNum3(){ return num3; }
private: private:
int num1; int num1;
int num2; int num2;
int num3; int num3;
}; };
TEST_CASE("CallbackTimer", "[CallbackTimer]" ) TEST_CASE("CallbackTimer", "[CallbackTimer]" )
{ {
SECTION("Basic tests") SECTION("Basic tests")
{ {
MyTestClass tc; MyTestClass tc;
CallbackTimer<MyTestClass> tmr(&tc,&MyTestClass::Time); CallbackTimer<MyTestClass> tmr(&tc,&MyTestClass::Time);
tmr.add(1, 50 ); tmr.add(1, 50 );
tmr.add(2, 150 ); tmr.add(2, 150 );
tmr.add(3, 300 ); tmr.add(3, 300 );
tmr.run(); tmr.run();
msleep(60); msleep(60);
REQUIRE( tc.getNum1() == 1 ); REQUIRE( tc.getNum1() == 1 );
REQUIRE( tc.getNum2() == 0 ); REQUIRE( tc.getNum2() == 0 );
REQUIRE( tc.getNum3() == 0 ); REQUIRE( tc.getNum3() == 0 );
msleep(110); msleep(110);
REQUIRE( tc.getNum1() == 3 ); REQUIRE( tc.getNum1() == 3 );
REQUIRE( tc.getNum2() == 1 ); REQUIRE( tc.getNum2() == 1 );
REQUIRE( tc.getNum3() == 0 ); REQUIRE( tc.getNum3() == 0 );
msleep(210); msleep(210);
REQUIRE( tc.getNum1() == 7 ); REQUIRE( tc.getNum1() == 7 );
REQUIRE( tc.getNum2() == 2 ); REQUIRE( tc.getNum2() == 2 );
REQUIRE( tc.getNum3() == 1 ); REQUIRE( tc.getNum3() == 1 );
tmr.remove(1); tmr.remove(1);
msleep(60); msleep(60);
REQUIRE( tc.getNum1() == 7 ); REQUIRE( tc.getNum1() == 7 );
tmr.terminate(); tmr.terminate();
REQUIRE( tc.getNum2() == 2 ); REQUIRE( tc.getNum2() == 2 );
REQUIRE( tc.getNum3() == 1 ); REQUIRE( tc.getNum3() == 1 );
} }
SECTION("other tests") SECTION("other tests")
{ {
MyTestClass tc; MyTestClass tc;
CallbackTimer<MyTestClass> tmr(&tc,&MyTestClass::Time); CallbackTimer<MyTestClass> tmr(&tc,&MyTestClass::Time);
int i=0; int i=0;
for( ;i<tmr.MAXCallbackTimer; i++ ) for( ;i<tmr.MAXCallbackTimer; i++ )
tmr.add(i,100 ); tmr.add(i,100 );
REQUIRE_THROWS_AS( tmr.add(++i,100), UniSetTypes::LimitTimers ); REQUIRE_THROWS_AS( tmr.add(++i,100), UniSetTypes::LimitTimers );
} }
} }
...@@ -9,41 +9,43 @@ using namespace UniSetTypes; ...@@ -9,41 +9,43 @@ using namespace UniSetTypes;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
TEST_CASE( "Configuration", "[Configuration]" ) TEST_CASE( "Configuration", "[Configuration]" )
{ {
assert( conf != 0 ); auto conf = uniset_conf();
assert( conf->oind != 0 );
// смотри tests_with_conf.xml assert( conf != nullptr );
ObjectId testID = 1; assert( conf->oind != nullptr );
const std::string testSensor("Input1_S");
const std::string testObject("TestProc");
const std::string testController("SharedMemory");
const std::string testService("TimeService");
// CHECK( conf != 0 ); // смотри tests_with_conf.xml
// CHECK( conf->oind != 0 ); ObjectId testID = 1;
const std::string testSensor("Input1_S");
const std::string testObject("TestProc");
const std::string testController("SharedMemory");
const std::string testService("TimeService");
SECTION( "ObjectIndex tests.." ) // CHECK( conf != 0 );
{ // CHECK( conf->oind != 0 );
CHECK( conf->getLocalNode()!=DefaultObjectId );
CHECK( conf->oind->getTextName(testID) != "" );
string ln("/Projects/Sensors/VeryVeryLongNameSensor_ForTest_AS");
string ln_short("VeryVeryLongNameSensor_ForTest_AS");
REQUIRE( ORepHelpers::getShortName(ln) == ln_short );
CHECK( conf->oind->getNameById(testID) != "" ); SECTION( "ObjectIndex tests.." )
{
string mn(conf->oind->getMapName(testID)); CHECK( conf->getLocalNode()!=DefaultObjectId );
CHECK( mn != "" ); CHECK( conf->oind->getTextName(testID) != "" );
CHECK( conf->oind->getIdByName(mn) != DefaultObjectId );
string ln("/Projects/Sensors/VeryVeryLongNameSensor_ForTest_AS");
CHECK( conf->getIOType(testID) != UniversalIO::UnknownIOType ); string ln_short("VeryVeryLongNameSensor_ForTest_AS");
CHECK( conf->getIOType(mn) != UniversalIO::UnknownIOType ); REQUIRE( ORepHelpers::getShortName(ln) == ln_short );
CHECK( conf->getIOType(testSensor) != UniversalIO::UnknownIOType );
}
SECTION( "Arguments" ) CHECK( conf->oind->getNameById(testID) != "" );
{
string mn(conf->oind->getMapName(testID));
CHECK( mn != "" );
CHECK( conf->oind->getIdByName(mn) != DefaultObjectId );
CHECK( conf->getIOType(testID) != UniversalIO::UnknownIOType );
CHECK( conf->getIOType(mn) != UniversalIO::UnknownIOType );
CHECK( conf->getIOType(testSensor) != UniversalIO::UnknownIOType );
}
SECTION( "Arguments" )
{
xmlNode* cnode = conf->getNode("testnode"); xmlNode* cnode = conf->getNode("testnode");
CHECK( cnode != NULL ); CHECK( cnode != NULL );
...@@ -54,47 +56,47 @@ TEST_CASE( "Configuration", "[Configuration]" ) ...@@ -54,47 +56,47 @@ TEST_CASE( "Configuration", "[Configuration]" )
CHECK( conf->getArgPInt("--prop-id2",it.getProp("id2"),0) != 0 ); CHECK( conf->getArgPInt("--prop-id2",it.getProp("id2"),0) != 0 );
CHECK( conf->getArgPInt("--prop-dummy",it.getProp("dummy"),20) == 20 ); CHECK( conf->getArgPInt("--prop-dummy",it.getProp("dummy"),20) == 20 );
CHECK( conf->getArgPInt("--prop-dummy",it.getProp("dummy"),0) == 0 ); CHECK( conf->getArgPInt("--prop-dummy",it.getProp("dummy"),0) == 0 );
} }
SECTION( "XML sections" ) SECTION( "XML sections" )
{ {
CHECK( conf->getXMLSensorsSection() != 0 ); CHECK( conf->getXMLSensorsSection() != 0 );
CHECK( conf->getXMLObjectsSection() != 0 ); CHECK( conf->getXMLObjectsSection() != 0 );
CHECK( conf->getXMLControllersSection() != 0 ); CHECK( conf->getXMLControllersSection() != 0 );
CHECK( conf->getXMLServicesSection() != 0 ); CHECK( conf->getXMLServicesSection() != 0 );
CHECK( conf->getXMLNodesSection() != 0 ); CHECK( conf->getXMLNodesSection() != 0 );
CHECK( conf->getSensorID(testSensor) != DefaultObjectId ); CHECK( conf->getSensorID(testSensor) != DefaultObjectId );
CHECK( conf->getObjectID(testObject) != DefaultObjectId ); CHECK( conf->getObjectID(testObject) != DefaultObjectId );
CHECK( conf->getControllerID(testController) != DefaultObjectId ); CHECK( conf->getControllerID(testController) != DefaultObjectId );
CHECK( conf->getServiceID(testService) != DefaultObjectId ); CHECK( conf->getServiceID(testService) != DefaultObjectId );
} }
SECTION( "Empty Constructor" ) SECTION( "Empty Constructor" )
{ {
int t_argc = 0; int t_argc = 0;
char t_argv[]={""}; char t_argv[]={""};
REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),""), UniSetTypes::SystemError ); REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),""), UniSetTypes::SystemError );
} }
// SECTION( "ObjectIndex Constructor" ) // SECTION( "ObjectIndex Constructor" )
// SECTION( "ObjectsMap Constructor" ) // SECTION( "ObjectsMap Constructor" )
SECTION( "Bad conf: no <ObjectsMap>" ) SECTION( "Bad conf: no <ObjectsMap>" )
{ {
int t_argc = 0; int t_argc = 0;
char t_argv[]={""}; char t_argv[]={""};
ulog.level(Debug::NONE); ulog.level(Debug::NONE);
REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),"tests_no_objectsmap.xml"), UniSetTypes::SystemError ); REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),"tests_no_objectsmap.xml"), UniSetTypes::SystemError );
} }
SECTION( "Bad conf: no <UniSet>" ) SECTION( "Bad conf: no <UniSet>" )
{ {
int t_argc = 0; int t_argc = 0;
char t_argv[]={""}; char t_argv[]={""};
ulog.level(Debug::NONE); ulog.level(Debug::NONE);
REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),"tests_no_uniset_section.xml"), UniSetTypes::SystemError ); REQUIRE_THROWS_AS( Configuration(t_argc,(const char* const*)(t_argv),"tests_no_uniset_section.xml"), UniSetTypes::SystemError );
} }
} }
...@@ -8,102 +8,102 @@ TEST_CASE("DelayTimer", "[DelayTimer]" ) ...@@ -8,102 +8,102 @@ TEST_CASE("DelayTimer", "[DelayTimer]" )
{ {
SECTION( "Default constructor" ) SECTION( "Default constructor" )
{ {
// Работа без задержки..(нулевые задержки) // Работа без задержки..(нулевые задержки)
DelayTimer dt; DelayTimer dt;
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
CHECK( dt.check(true) ); CHECK( dt.check(true) );
msleep(15); msleep(15);
CHECK( dt.get() ); CHECK( dt.get() );
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
CHECK( dt.check(true) ); CHECK( dt.check(true) );
CHECK( dt.get() ); CHECK( dt.get() );
} }
SECTION( "Init constructor" ) SECTION( "Init constructor" )
{ {
DelayTimer dt(100,50); DelayTimer dt(100,50);
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
} }
SECTION( "Working" ) SECTION( "Working" )
{ {
DelayTimer dt(100,60); DelayTimer dt(100,60);
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
// проверяем срабатывание.. // проверяем срабатывание..
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
msleep(50); msleep(50);
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
msleep(60); msleep(60);
CHECK( dt.check(true) ); CHECK( dt.check(true) );
CHECK( dt.get() ); CHECK( dt.get() );
// проверяем отпускание // проверяем отпускание
// несмотря на вызов check(false).. должно ещё 60 мсек возвращать true // несмотря на вызов check(false).. должно ещё 60 мсек возвращать true
CHECK( dt.check(false) ); CHECK( dt.check(false) );
CHECK( dt.get() ); CHECK( dt.get() );
msleep(20); msleep(20);
CHECK( dt.check(false) ); CHECK( dt.check(false) );
CHECK( dt.get() ); CHECK( dt.get() );
msleep(50); // в сумме уже 20+50=70 > 60, значит должно "отпустить" msleep(50); // в сумме уже 20+50=70 > 60, значит должно "отпустить"
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
} }
SECTION( "Debounce" ) SECTION( "Debounce" )
{ {
DelayTimer dt(150,100); DelayTimer dt(150,100);
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
// проверяем срабатывание.. (при скакании сигнала) // проверяем срабатывание.. (при скакании сигнала)
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
msleep(50); msleep(50);
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
msleep(60); msleep(60);
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
msleep(100); msleep(100);
CHECK_FALSE( dt.check(true) ); CHECK_FALSE( dt.check(true) );
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
msleep(60); msleep(60);
CHECK( dt.check(true) ); CHECK( dt.check(true) );
CHECK( dt.get() ); CHECK( dt.get() );
// проверяем отпускание при скакании сигнала // проверяем отпускание при скакании сигнала
CHECK( dt.check(false) ); CHECK( dt.check(false) );
CHECK( dt.get() ); CHECK( dt.get() );
msleep(60); msleep(60);
CHECK( dt.check(true) ); CHECK( dt.check(true) );
CHECK( dt.get() ); CHECK( dt.get() );
dt.check(false); dt.check(false);
msleep(80); msleep(80);
CHECK( dt.check(false) ); CHECK( dt.check(false) );
CHECK( dt.get() ); CHECK( dt.get() );
msleep(40); msleep(40);
CHECK_FALSE( dt.check(false) ); CHECK_FALSE( dt.check(false) );
CHECK_FALSE( dt.get() ); CHECK_FALSE( dt.get() );
} }
SECTION( "Copy" ) SECTION( "Copy" )
{ {
DelayTimer dt1(100,50); DelayTimer dt1(100,50);
DelayTimer dt2(200,100); DelayTimer dt2(200,100);
dt1 = dt2; dt1 = dt2;
REQUIRE( dt1.getOnDelay() == 200 ); REQUIRE( dt1.getOnDelay() == 200 );
REQUIRE( dt1.getOffDelay() == 100 ); REQUIRE( dt1.getOffDelay() == 100 );
dt1.check(true); dt1.check(true);
msleep(220); msleep(220);
CHECK( dt1.get() ); CHECK( dt1.get() );
CHECK_FALSE( dt2.get() ); CHECK_FALSE( dt2.get() );
} }
} }
...@@ -11,19 +11,19 @@ std::ostringstream ss1; ...@@ -11,19 +11,19 @@ std::ostringstream ss1;
void check_log_signal( const string& s ) void check_log_signal( const string& s )
{ {
ss << s; ss << s;
} }
void check_alog_signal( const string& s ) void check_alog_signal( const string& s )
{ {
ss1 << s; ss1 << s;
} }
int main( int argc, const char **argv ) int main( int argc, const char **argv )
{ {
DebugStream tlog; DebugStream tlog;
tlog.signal_stream_event().connect(&check_log_signal); tlog.signal_stream_event().connect(&check_log_signal);
tlog.addLevel(Debug::ANY); tlog.addLevel(Debug::ANY);
...@@ -37,15 +37,15 @@ int main( int argc, const char **argv ) ...@@ -37,15 +37,15 @@ int main( int argc, const char **argv )
if( tlog.is_level1() ) if( tlog.is_level1() )
tlog.level1() << ": is level1..." << endl; tlog.level1() << ": is level1..." << endl;
cout << "===== Test 1 =====" << endl; cout << "===== Test 1 =====" << endl;
cout << ss.str(); cout << ss.str();
cout << "==================" << endl; cout << "==================" << endl;
DebugStream log1; DebugStream log1;
log1.setLogName("log1"); log1.setLogName("log1");
DebugStream log2; DebugStream log2;
log2.setLogName("log2"); log2.setLogName("log2");
LogAgregator la; LogAgregator la;
la.signal_stream_event().connect(&check_alog_signal); la.signal_stream_event().connect(&check_alog_signal);
la.add(log1); la.add(log1);
...@@ -55,17 +55,17 @@ int main( int argc, const char **argv ) ...@@ -55,17 +55,17 @@ int main( int argc, const char **argv )
log2 << "log2: test message..." << endl; log2 << "log2: test message..." << endl;
la << "la: test message.." << endl; la << "la: test message.." << endl;
cout << "===== Test 2 =====" << endl; cout << "===== Test 2 =====" << endl;
cout << ss1.str(); cout << ss1.str();
cout << "==================" << endl; cout << "==================" << endl;
DebugStream* l = la.getLog("log1"); DebugStream* l = la.getLog("log1");
if( l != &log1 ) if( l != &log1 )
cout << "**** TEST FAILED: LogAgregator::getLog() " << endl; cout << "**** TEST FAILED: LogAgregator::getLog() " << endl;
cout << "===== Test 3 =====" << endl; cout << "===== Test 3 =====" << endl;
tlog.level(Debug::ANY); tlog.level(Debug::ANY);
tlog.logFile("tlog.log"); tlog.logFile("tlog.log");
tlog << "TEST TEXT" << endl; tlog << "TEST TEXT" << endl;
......
...@@ -10,90 +10,90 @@ using namespace std; ...@@ -10,90 +10,90 @@ using namespace std;
TEST_CASE("HourGlass", "[HourGlass]" ) TEST_CASE("HourGlass", "[HourGlass]" )
{ {
SECTION( "Constructor" ) SECTION( "Constructor" )
{ {
HourGlass hg; HourGlass hg;
REQUIRE( hg.duration() == 0 ); REQUIRE( hg.duration() == 0 );
msleep(60); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50 msleep(60); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
REQUIRE( std::abs(hg.current()-60) <= 10 ); REQUIRE( std::abs(hg.current()-60) <= 10 );
REQUIRE( hg.interval() == 0 ); REQUIRE( hg.interval() == 0 );
REQUIRE( hg.amount() == 0 ); REQUIRE( hg.amount() == 0 );
REQUIRE( hg.remain() == 0 ); REQUIRE( hg.remain() == 0 );
CHECK_FALSE( hg.state() ); CHECK_FALSE( hg.state() );
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
} }
SECTION( "Working" ) SECTION( "Working" )
{ {
HourGlass hg; HourGlass hg;
hg.run(100); hg.run(100);
CHECK( hg.state() ); // часы начали тикать.. (в нормальном положении) CHECK( hg.state() ); // часы начали тикать.. (в нормальном положении)
REQUIRE( hg.duration() == 100 ); REQUIRE( hg.duration() == 100 );
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(110); msleep(110);
CHECK( hg.check() ); CHECK( hg.check() );
// Переворачиваем обратно.. // Переворачиваем обратно..
// "песок высыпается назад" в течении 50 мсек, // "песок высыпается назад" в течении 50 мсек,
// потом опять ставим "на ноги", ждём 60 мсек.. должно сработать // потом опять ставим "на ноги", ждём 60 мсек.. должно сработать
hg.rotate(false); hg.rotate(false);
CHECK_FALSE( hg.state() ); CHECK_FALSE( hg.state() );
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(50); msleep(50);
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
hg.rotate(true); hg.rotate(true);
msleep(60); msleep(60);
CHECK( hg.check() ); CHECK( hg.check() );
} }
SECTION( "Reset" ) SECTION( "Reset" )
{ {
HourGlass hg; HourGlass hg;
hg.run(100); hg.run(100);
msleep(110); msleep(110);
CHECK( hg.check() ); CHECK( hg.check() );
hg.reset(); hg.reset();
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(110); msleep(110);
CHECK( hg.check() ); CHECK( hg.check() );
} }
SECTION( "Debounce" ) SECTION( "Debounce" )
{ {
HourGlass hg; HourGlass hg;
hg.run(100); // [ 100 / 0 ] hg.run(100); // [ 100 / 0 ]
REQUIRE( hg.remain() == 100 ); REQUIRE( hg.remain() == 100 );
REQUIRE( hg.amount() == 0 ); REQUIRE( hg.amount() == 0 );
msleep(110); // [ 0 / 110 ] "110" --> "100" msleep(110); // [ 0 / 110 ] "110" --> "100"
CHECK( hg.check() ); CHECK( hg.check() );
REQUIRE( hg.remain() == 0 ); REQUIRE( hg.remain() == 0 );
REQUIRE( hg.amount() == 100 ); REQUIRE( hg.amount() == 100 );
hg.rotate(false); // начинает сыпаться "обратно".. hg.rotate(false); // начинает сыпаться "обратно"..
REQUIRE( hg.amount() == 100 ); REQUIRE( hg.amount() == 100 );
msleep(55); msleep(55);
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
REQUIRE( hg.amount() <= 50 ); // +-10 мсек.. REQUIRE( hg.amount() <= 50 ); // +-10 мсек..
hg.rotate(true); // опять начал сыпаться.. hg.rotate(true); // опять начал сыпаться..
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(25); msleep(25);
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
REQUIRE( hg.amount() >= 60 ); REQUIRE( hg.amount() >= 60 );
hg.rotate(false); // опять назад.. hg.rotate(false); // опять назад..
msleep(80); // по сути сигнал сбросился..(т.к. оставалось 70.. а прошло 80) msleep(80); // по сути сигнал сбросился..(т.к. оставалось 70.. а прошло 80)
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
REQUIRE( hg.amount() == 0 ); REQUIRE( hg.amount() == 0 );
REQUIRE( hg.remain() == 100 ); REQUIRE( hg.remain() == 100 );
hg.rotate(true); // вновь запустили hg.rotate(true); // вновь запустили
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(55); msleep(55);
REQUIRE( hg.amount() >= 50 ); REQUIRE( hg.amount() >= 50 );
CHECK_FALSE( hg.check() ); CHECK_FALSE( hg.check() );
msleep(60); msleep(60);
REQUIRE( hg.remain() == 0 ); REQUIRE( hg.remain() == 0 );
REQUIRE( hg.amount() == 100 ); REQUIRE( hg.amount() == 100 );
CHECK( hg.check() ); CHECK( hg.check() );
} }
} }
...@@ -5,16 +5,16 @@ using namespace std; ...@@ -5,16 +5,16 @@ using namespace std;
TEST_CASE("Modbus Types", "[modbus][modbus types]" ) TEST_CASE("Modbus Types", "[modbus][modbus types]" )
{ {
SECTION("WriteOutputMessage: limit the amount of data verification") SECTION("WriteOutputMessage: limit the amount of data verification")
{ {
ModbusRTU::WriteOutputMessage msg(0x01,1); ModbusRTU::WriteOutputMessage msg(0x01,1);
for( int i=0; i<(ModbusRTU::MAXDATALEN-1); i++ ) for( int i=0; i<(ModbusRTU::MAXDATALEN-1); i++ )
msg.addData(10+i); msg.addData(10+i);
CHECK_FALSE( msg.isFull() ); CHECK_FALSE( msg.isFull() );
msg.addData(1); msg.addData(1);
CHECK( msg.isFull() ); CHECK( msg.isFull() );
} }
WARN("Tests for 'Modbus types' incomplete.."); WARN("Tests for 'Modbus types' incomplete..");
} }
...@@ -8,69 +8,69 @@ TEST_CASE("PassiveTimer", "[PassiveTimer]" ) ...@@ -8,69 +8,69 @@ TEST_CASE("PassiveTimer", "[PassiveTimer]" )
{ {
SECTION( "Default constructor" ) SECTION( "Default constructor" )
{ {
PassiveTimer pt; PassiveTimer pt;
REQUIRE_FALSE( pt.checkTime() ); REQUIRE_FALSE( pt.checkTime() );
msleep(15); msleep(15);
REQUIRE( pt.getCurrent() >= 10 ); REQUIRE( pt.getCurrent() >= 10 );
REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF ); REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF );
REQUIRE( pt.getLeft( pt.getCurrent() + 10 ) == 10 ); REQUIRE( pt.getLeft( pt.getCurrent() + 10 ) == 10 );
} }
SECTION( "Init constructor" ) SECTION( "Init constructor" )
{ {
PassiveTimer pt(100); PassiveTimer pt(100);
msleep(15); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50 msleep(15); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
REQUIRE( pt.getCurrent() >= 10 ); REQUIRE( pt.getCurrent() >= 10 );
REQUIRE( pt.getInterval() == 100 ); REQUIRE( pt.getInterval() == 100 );
REQUIRE( pt.getLeft(50) > 0 ); REQUIRE( pt.getLeft(50) > 0 );
} }
SECTION( "Init zero" ) SECTION( "Init zero" )
{ {
PassiveTimer pt(0); PassiveTimer pt(0);
REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF ); REQUIRE( pt.getInterval() == 0 ); // TIMEOUT_INF );
REQUIRE( pt.getLeft(100) == 100 ); REQUIRE( pt.getLeft(100) == 100 );
} }
SECTION( "Init < 0 " ) SECTION( "Init < 0 " )
{ {
PassiveTimer pt(-10); PassiveTimer pt(-10);
REQUIRE( pt.getInterval() >= (timeout_t)(-10) ); // '>=' т.к. переданное время может быть округлено в большую сторону. REQUIRE( pt.getInterval() >= (timeout_t)(-10) ); // '>=' т.к. переданное время может быть округлено в большую сторону.
REQUIRE( pt.getLeft(10) == 10 ); REQUIRE( pt.getLeft(10) == 10 );
} }
SECTION( "Check working" ) SECTION( "Check working" )
{ {
PassiveTimer pt(100); PassiveTimer pt(100);
msleep(120); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50 msleep(120); // т.к. точность +-10 мсек.. делаем паузу 60.. а проверяем 50
REQUIRE( pt.getCurrent() >= 110 ); REQUIRE( pt.getCurrent() >= 110 );
CHECK( pt.checkTime() ); CHECK( pt.checkTime() );
INFO("Check reset"); INFO("Check reset");
pt.reset(); pt.reset();
REQUIRE_FALSE( pt.checkTime() ); REQUIRE_FALSE( pt.checkTime() );
INFO("Check setTiming"); INFO("Check setTiming");
REQUIRE_FALSE( pt.checkTime() ); REQUIRE_FALSE( pt.checkTime() );
pt.setTiming(50); pt.setTiming(50);
msleep(55); // т.к. точность +-10 мсек.. делаем паузу 55.. msleep(55); // т.к. точность +-10 мсек.. делаем паузу 55..
CHECK( pt.checkTime() ); CHECK( pt.checkTime() );
} }
SECTION( "Copy" ) SECTION( "Copy" )
{ {
PassiveTimer pt1(100); PassiveTimer pt1(100);
PassiveTimer pt2(200); PassiveTimer pt2(200);
REQUIRE( pt1.getInterval() == 100 ); REQUIRE( pt1.getInterval() == 100 );
REQUIRE( pt2.getInterval() == 200 ); REQUIRE( pt2.getInterval() == 200 );
pt2 = pt1; pt2 = pt1;
REQUIRE( pt1.getInterval() == 100 ); REQUIRE( pt1.getInterval() == 100 );
REQUIRE( pt2.getInterval() == 100 ); REQUIRE( pt2.getInterval() == 100 );
msleep(110); msleep(110);
CHECK( pt1.checkTime() ); CHECK( pt1.checkTime() );
CHECK( pt2.checkTime() ); CHECK( pt2.checkTime() );
} }
} }
...@@ -8,48 +8,48 @@ TEST_CASE("Pulse", "[Test for class 'Pulse' - impulse generator]" ) ...@@ -8,48 +8,48 @@ TEST_CASE("Pulse", "[Test for class 'Pulse' - impulse generator]" )
{ {
SECTION( "Default constructor" ) SECTION( "Default constructor" )
{ {
// Работа без задержки..(нулевые задержки) // Работа без задержки..(нулевые задержки)
Pulse p; Pulse p;
CHECK_FALSE( p.out() ); CHECK_FALSE( p.out() );
p.step(); p.step();
p.step(); p.step();
CHECK_FALSE( p.out() ); CHECK_FALSE( p.out() );
} }
SECTION( "Working" ) SECTION( "Working" )
{ {
Pulse p; Pulse p;
p.run(100,60); // 100 msec ON..60 msec OFF p.run(100,60); // 100 msec ON..60 msec OFF
CHECK( p.step() ); CHECK( p.step() );
msleep(80); msleep(80);
CHECK( p.step() ); CHECK( p.step() );
msleep(30); msleep(30);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
msleep(70); msleep(70);
CHECK( p.step() ); CHECK( p.step() );
msleep(100); msleep(100);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
p.set(false); p.set(false);
msleep(100); msleep(100);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
msleep(60); msleep(60);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
p.set(true); p.set(true);
msleep(70); msleep(70);
CHECK( p.step() ); CHECK( p.step() );
msleep(30); msleep(30);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
p.reset(); p.reset();
CHECK( p.step() ); CHECK( p.step() );
msleep(110); msleep(110);
CHECK_FALSE( p.step() ); CHECK_FALSE( p.step() );
} }
} }
...@@ -6,16 +6,16 @@ int check( const char *t ) ...@@ -6,16 +6,16 @@ int check( const char *t )
{ {
int r = 0; int r = 0;
sscanf(t, "%i", &r); sscanf(t, "%i", &r);
return r; return r;
} }
TEST_CASE("sscanf hex","[sscanf hex]") TEST_CASE("sscanf hex","[sscanf hex]")
{ {
REQUIRE( check("100") == 100 ); REQUIRE( check("100") == 100 );
REQUIRE( check("0x100") == 0x100 ); REQUIRE( check("0x100") == 0x100 );
REQUIRE( check("0xFF") == 0xff ); REQUIRE( check("0xFF") == 0xff );
REQUIRE( check("010") == 010 ); REQUIRE( check("010") == 010 );
REQUIRE( check("-10") == -10 ); REQUIRE( check("-10") == -10 );
REQUIRE( check("-1000") == -1000 ); REQUIRE( check("-1000") == -1000 );
REQUIRE( check("") == 0 ); REQUIRE( check("") == 0 );
} }
...@@ -6,21 +6,21 @@ ...@@ -6,21 +6,21 @@
int main( int argc, char* argv[] ) int main( int argc, char* argv[] )
{ {
Catch::Session session; Catch::Session session;
try try
{ {
UniSetTypes::uniset_init(argc,argv); UniSetTypes::uniset_init(argc,argv);
int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore ); int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore );
if( returnCode != 0 ) // Indicates a command line error if( returnCode != 0 ) // Indicates a command line error
return returnCode; return returnCode;
return session.run(); return session.run();
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
{ {
std::cerr << ex << std::endl; std::cerr << ex << std::endl;
} }
return 1; return 1;
} }
...@@ -6,28 +6,28 @@ using namespace std; ...@@ -6,28 +6,28 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
TEST_CASE( "Trigger", "[Trigger]" ) TEST_CASE( "Trigger", "[Trigger]" )
{ {
SECTION("Constructor") SECTION("Constructor")
{ {
Trigger tr; Trigger tr;
CHECK_FALSE( tr.hi(false) ); CHECK_FALSE( tr.hi(false) );
CHECK( tr.hi(true) ); CHECK( tr.hi(true) );
Trigger trHi; Trigger trHi;
CHECK( tr.low(false) ); CHECK( tr.low(false) );
CHECK( tr.hi(true) ); CHECK( tr.hi(true) );
} }
SECTION("Working") SECTION("Working")
{ {
Trigger tr; Trigger tr;
CHECK_FALSE( tr.low(false) ); CHECK_FALSE( tr.low(false) );
CHECK_FALSE( tr.change(false) ); CHECK_FALSE( tr.change(false) );
CHECK( tr.hi(true) ); CHECK( tr.hi(true) );
CHECK_FALSE( tr.change(true) ); CHECK_FALSE( tr.change(true) );
CHECK( tr.low(false) ); CHECK( tr.low(false) );
CHECK( tr.change(true) ); CHECK( tr.change(true) );
CHECK( tr.low(false) ); CHECK( tr.low(false) );
CHECK( tr.hi(true) ); CHECK( tr.hi(true) );
CHECK_FALSE( tr.hi(false) ); CHECK_FALSE( tr.hi(false) );
} }
} }
...@@ -6,115 +6,115 @@ using namespace std; ...@@ -6,115 +6,115 @@ using namespace std;
class MyTestClass class MyTestClass
{ {
public: public:
MyTestClass():num(0){} MyTestClass():num(0){}
~MyTestClass(){} ~MyTestClass(){}
void setOut( bool newstate ) void setOut( bool newstate )
{ {
num++; num++;
} }
inline int getNum(){ return num; } inline int getNum(){ return num; }
private: private:
int num; int num;
}; };
TEST_CASE("TriggerAND", "[TriggerAND]" ) TEST_CASE("TriggerAND", "[TriggerAND]" )
{ {
SECTION("Constructor") SECTION("Constructor")
{ {
MyTestClass tc; MyTestClass tc;
TriggerAND<MyTestClass> tr(&tc, &MyTestClass::setOut); TriggerAND<MyTestClass> tr(&tc, &MyTestClass::setOut);
tr.add(1, true); // в этот момент вход всего один и он TRUE поэтому тут out=TRUE tr.add(1, true); // в этот момент вход всего один и он TRUE поэтому тут out=TRUE
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
CHECK( tr.state() ); CHECK( tr.state() );
tr.add(2, false); tr.add(2, false);
REQUIRE( tc.getNum() == 2 ); REQUIRE( tc.getNum() == 2 );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
tr.add(3, false); tr.add(3, false);
REQUIRE( tc.getNum() == 2 ); REQUIRE( tc.getNum() == 2 );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
} }
SECTION("Working") SECTION("Working")
{ {
MyTestClass tc; MyTestClass tc;
TriggerAND<MyTestClass> tr(&tc, &MyTestClass::setOut); TriggerAND<MyTestClass> tr(&tc, &MyTestClass::setOut);
tr.add(1, false); tr.add(1, false);
tr.add(2, false); tr.add(2, false);
tr.add(3, false); tr.add(3, false);
REQUIRE( tc.getNum() == 0 ); REQUIRE( tc.getNum() == 0 );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.commit(1, true); tr.commit(1, true);
tr.commit(2, true); tr.commit(2, true);
REQUIRE( tc.getNum() == 0 ); REQUIRE( tc.getNum() == 0 );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK( tr.getState(2) ); CHECK( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.commit(3, true); tr.commit(3, true);
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
CHECK( tr.state() ); CHECK( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK( tr.getState(2) ); CHECK( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
tr.commit(2,false); tr.commit(2,false);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
REQUIRE( tc.getNum() == 2 ); REQUIRE( tc.getNum() == 2 );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
tr.commit(1,false); tr.commit(1,false);
tr.commit(3,false); tr.commit(3,false);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
REQUIRE( tc.getNum() == 2 ); REQUIRE( tc.getNum() == 2 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.commit(1,true); tr.commit(1,true);
tr.commit(3,true); tr.commit(3,true);
tr.commit(2,true); tr.commit(2,true);
CHECK( tr.state() ); CHECK( tr.state() );
REQUIRE( tc.getNum() == 3 ); REQUIRE( tc.getNum() == 3 );
tr.commit(2,false); tr.commit(2,false);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
REQUIRE( tc.getNum() == 4 ); REQUIRE( tc.getNum() == 4 );
tr.remove(2); tr.remove(2);
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
CHECK( tr.state() ); CHECK( tr.state() );
REQUIRE( tc.getNum() == 5 ); REQUIRE( tc.getNum() == 5 );
// обращение к несуществующему входу // обращение к несуществующему входу
CHECK_FALSE( tr.getState(10) ); CHECK_FALSE( tr.getState(10) );
CHECK_FALSE( tr.getState(-10) ); CHECK_FALSE( tr.getState(-10) );
CHECK_FALSE( tr.getState(0) ); CHECK_FALSE( tr.getState(0) );
tr.commit(10,false); tr.commit(10,false);
CHECK( tr.state() ); CHECK( tr.state() );
tr.commit(-10,false); tr.commit(-10,false);
CHECK( tr.state() ); CHECK( tr.state() );
tr.commit(0,false); tr.commit(0,false);
CHECK( tr.state() ); CHECK( tr.state() );
} }
} }
...@@ -6,89 +6,89 @@ using namespace std; ...@@ -6,89 +6,89 @@ using namespace std;
class MyTestClass class MyTestClass
{ {
public: public:
MyTestClass():num(0){} MyTestClass():num(0){}
~MyTestClass(){} ~MyTestClass(){}
void setOut( bool newstate ) void setOut( bool newstate )
{ {
num++; num++;
} }
inline int getNum(){ return num; } inline int getNum(){ return num; }
private: private:
int num; int num;
}; };
TEST_CASE("TriggerOR", "[TriggerOR]" ) TEST_CASE("TriggerOR", "[TriggerOR]" )
{ {
SECTION("Constructor") SECTION("Constructor")
{ {
MyTestClass tc; MyTestClass tc;
TriggerOR<MyTestClass, int> tr(&tc, &MyTestClass::setOut); TriggerOR<MyTestClass, int> tr(&tc, &MyTestClass::setOut);
REQUIRE( tc.getNum() == 0 ); REQUIRE( tc.getNum() == 0 );
tr.add(1, true); tr.add(1, true);
tr.add(2, false); tr.add(2, false);
tr.add(3, false); tr.add(3, false);
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
CHECK( tr.state() ); CHECK( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
} }
SECTION("Working") SECTION("Working")
{ {
MyTestClass tc; MyTestClass tc;
TriggerOR<MyTestClass> tr(&tc, &MyTestClass::setOut); TriggerOR<MyTestClass> tr(&tc, &MyTestClass::setOut);
REQUIRE( tc.getNum() == 0 ); REQUIRE( tc.getNum() == 0 );
tr.add(1, true); tr.add(1, true);
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
CHECK( tr.state() ); CHECK( tr.state() );
tr.add(2, false); tr.add(2, false);
CHECK( tr.state() ); CHECK( tr.state() );
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
tr.add(3, false); tr.add(3, false);
REQUIRE( tc.getNum() == 1 ); REQUIRE( tc.getNum() == 1 );
CHECK( tr.state() ); CHECK( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.reset(); tr.reset();
REQUIRE( tc.getNum() == 2 ); REQUIRE( tc.getNum() == 2 );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.commit(1,false); tr.commit(1,false);
tr.commit(2,true); tr.commit(2,true);
CHECK( tr.state() ); CHECK( tr.state() );
REQUIRE( tc.getNum() == 3 ); REQUIRE( tc.getNum() == 3 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK( tr.getState(2) ); CHECK( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.remove(2); tr.remove(2);
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
REQUIRE( tc.getNum() == 4 ); REQUIRE( tc.getNum() == 4 );
// обращение к несуществующему входу // обращение к несуществующему входу
CHECK_FALSE( tr.getState(10) ); CHECK_FALSE( tr.getState(10) );
CHECK_FALSE( tr.getState(-10) ); CHECK_FALSE( tr.getState(-10) );
CHECK_FALSE( tr.getState(0) ); CHECK_FALSE( tr.getState(0) );
tr.commit(10,true); tr.commit(10,true);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
tr.commit(-10,true); tr.commit(-10,true);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
tr.commit(0,true); tr.commit(0,true);
CHECK_FALSE( tr.state() ); CHECK_FALSE( tr.state() );
} }
} }
...@@ -6,123 +6,123 @@ using namespace std; ...@@ -6,123 +6,123 @@ using namespace std;
class MyTestClass class MyTestClass
{ {
public: public:
MyTestClass():out1(0),out2(0),out3(0){} MyTestClass():out1(0),out2(0),out3(0){}
~MyTestClass(){} ~MyTestClass(){}
void setOut( int outID, bool state ) void setOut( int outID, bool state )
{ {
if( outID == 1 ) if( outID == 1 )
out1++; out1++;
else if( outID == 2 ) else if( outID == 2 )
out2++; out2++;
else if( outID == 3 ) else if( outID == 3 )
out3++; out3++;
} }
inline int getOut1Counter(){ return out1; } inline int getOut1Counter(){ return out1; }
inline int getOut2Counter(){ return out2; } inline int getOut2Counter(){ return out2; }
inline int getOut3Counter(){ return out3; } inline int getOut3Counter(){ return out3; }
private: private:
int out1; int out1;
int out2; int out2;
int out3; int out3;
}; };
TEST_CASE("TriggerOUT", "[TriggerOUT]" ) TEST_CASE("TriggerOUT", "[TriggerOUT]" )
{ {
SECTION("Constructor") SECTION("Constructor")
{ {
MyTestClass tc; MyTestClass tc;
TriggerOUT<MyTestClass> tr(&tc, &MyTestClass::setOut); TriggerOUT<MyTestClass> tr(&tc, &MyTestClass::setOut);
tr.add(1, true); tr.add(1, true);
REQUIRE( tc.getOut1Counter() == 1 ); REQUIRE( tc.getOut1Counter() == 1 );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
tr.add(2, false); tr.add(2, false);
REQUIRE( tc.getOut1Counter() == 2 ); REQUIRE( tc.getOut1Counter() == 2 );
REQUIRE( tc.getOut2Counter() == 1 ); REQUIRE( tc.getOut2Counter() == 1 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
tr.add(3, true); tr.add(3, true);
REQUIRE( tc.getOut2Counter() == 1 ); REQUIRE( tc.getOut2Counter() == 1 );
REQUIRE( tc.getOut3Counter() == 1 ); REQUIRE( tc.getOut3Counter() == 1 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
} }
SECTION("Working") SECTION("Working")
{ {
MyTestClass tc; MyTestClass tc;
TriggerOUT<MyTestClass> tr(&tc, &MyTestClass::setOut); TriggerOUT<MyTestClass> tr(&tc, &MyTestClass::setOut);
tr.add(1, false); tr.add(1, false);
tr.add(2, false); tr.add(2, false);
tr.add(3, false); tr.add(3, false);
REQUIRE( tc.getOut1Counter() == 1 ); REQUIRE( tc.getOut1Counter() == 1 );
REQUIRE( tc.getOut2Counter() == 1 ); REQUIRE( tc.getOut2Counter() == 1 );
REQUIRE( tc.getOut3Counter() == 1 ); REQUIRE( tc.getOut3Counter() == 1 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.set(1, true); tr.set(1, true);
REQUIRE( tc.getOut1Counter() == 2 ); REQUIRE( tc.getOut1Counter() == 2 );
REQUIRE( tc.getOut2Counter() == 1 ); REQUIRE( tc.getOut2Counter() == 1 );
REQUIRE( tc.getOut3Counter() == 1 ); REQUIRE( tc.getOut3Counter() == 1 );
CHECK( tr.getState(1) ); CHECK( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.set(2, true); tr.set(2, true);
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 2 ); REQUIRE( tc.getOut2Counter() == 2 );
REQUIRE( tc.getOut3Counter() == 1 ); REQUIRE( tc.getOut3Counter() == 1 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK( tr.getState(2) ); CHECK( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
tr.set(3, false); tr.set(3, false);
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK_FALSE( tr.getState(3) ); CHECK_FALSE( tr.getState(3) );
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 3 ); REQUIRE( tc.getOut2Counter() == 3 );
REQUIRE( tc.getOut3Counter() == 1 ); REQUIRE( tc.getOut3Counter() == 1 );
tr.set(3,true); tr.set(3,true);
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 3 ); REQUIRE( tc.getOut2Counter() == 3 );
REQUIRE( tc.getOut3Counter() == 2 ); REQUIRE( tc.getOut3Counter() == 2 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
// обращение к несуществующему выходу // обращение к несуществующему выходу
tr.set(10,true); tr.set(10,true);
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 3 ); REQUIRE( tc.getOut2Counter() == 3 );
REQUIRE( tc.getOut3Counter() == 2 ); REQUIRE( tc.getOut3Counter() == 2 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
tr.set(-10,true); tr.set(-10,true);
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 3 ); REQUIRE( tc.getOut2Counter() == 3 );
REQUIRE( tc.getOut3Counter() == 2 ); REQUIRE( tc.getOut3Counter() == 2 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
tr.set(0,true); tr.set(0,true);
REQUIRE( tc.getOut1Counter() == 3 ); REQUIRE( tc.getOut1Counter() == 3 );
REQUIRE( tc.getOut2Counter() == 3 ); REQUIRE( tc.getOut2Counter() == 3 );
REQUIRE( tc.getOut3Counter() == 2 ); REQUIRE( tc.getOut3Counter() == 2 );
CHECK_FALSE( tr.getState(1) ); CHECK_FALSE( tr.getState(1) );
CHECK_FALSE( tr.getState(2) ); CHECK_FALSE( tr.getState(2) );
CHECK( tr.getState(3) ); CHECK( tr.getState(3) );
} }
} }
...@@ -9,61 +9,62 @@ using namespace UniSetTypes; ...@@ -9,61 +9,62 @@ using namespace UniSetTypes;
TEST_CASE("UInterface","[UInterface]") TEST_CASE("UInterface","[UInterface]")
{ {
CHECK( conf!=0 ); auto conf = uniset_conf();
CHECK( conf!=nullptr );
std::string sidName("Input1_S");
std::string sidName("Input1_S");
ObjectId testOID = conf->getObjectID("TestProc");
CHECK( testOID != DefaultObjectId ); ObjectId testOID = conf->getObjectID("TestProc");
CHECK( testOID != DefaultObjectId );
ObjectId sid = conf->getSensorID(sidName);
CHECK( sid != DefaultObjectId ); ObjectId sid = conf->getSensorID(sidName);
CHECK( sid != DefaultObjectId );
UInterface ui;
UInterface ui;
CHECK( ui.getObjectIndex() != nullptr );
CHECK( ui.getConf() == UniSetTypes::conf ); CHECK( ui.getObjectIndex() != nullptr );
CHECK( ui.getConf() == conf );
CHECK( ui.getConfIOType(sid) != UniversalIO::UnknownIOType );
CHECK( ui.getConfIOType(sid) != UniversalIO::UnknownIOType );
REQUIRE_THROWS_AS( ui.getValue(DefaultObjectId), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.getValue(sid), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.getValue(DefaultObjectId), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.getValue(sid, DefaultObjectId), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.getValue(sid), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getValue(sid, 100), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.getValue(sid, DefaultObjectId), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getValue(sid, 100), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.resolve(sid), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.resolve(sid,10), UniSetTypes::ORepFailed ); REQUIRE_THROWS_AS( ui.resolve(sid), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.resolve(sid,DefaultObjectId), UniSetTypes::ORepFailed ); REQUIRE_THROWS_AS( ui.resolve(sid,10), UniSetTypes::ORepFailed );
REQUIRE_THROWS_AS( ui.resolve(sid,DefaultObjectId), UniSetTypes::ORepFailed );
TransportMessage tm( SensorMessage(sid,10).transport_msg() );
TransportMessage tm( SensorMessage(sid,10).transport_msg() );
REQUIRE_THROWS_AS( ui.send(testOID,tm), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.send(testOID,tm, -20), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.send(testOID,tm), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.send(testOID,tm, DefaultObjectId), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.send(testOID,tm, -20), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getChangedTime(sid,-20), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.send(testOID,tm, DefaultObjectId), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getChangedTime(sid,DefaultObjectId), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.getChangedTime(sid,-20), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getChangedTime(sid,conf->getLocalNode()), UniSetTypes::Exception ); REQUIRE_THROWS_AS( ui.getChangedTime(sid,DefaultObjectId), UniSetTypes::Exception );
REQUIRE_THROWS_AS( ui.getChangedTime(sid,conf->getLocalNode()), UniSetTypes::Exception );
CHECK_FALSE( ui.isExist(sid) );
CHECK_FALSE( ui.isExist(sid,DefaultObjectId) ); CHECK_FALSE( ui.isExist(sid) );
CHECK_FALSE( ui.isExist(sid,100) ); CHECK_FALSE( ui.isExist(sid,DefaultObjectId) );
CHECK_FALSE( ui.isExist(sid,100) );
CHECK_FALSE( ui.waitReady(sid,100,50) );
CHECK_FALSE( ui.waitReady(sid,300,50,DefaultObjectId) ); CHECK_FALSE( ui.waitReady(sid,100,50) );
CHECK_FALSE( ui.waitReady(sid,300,50,-20) ); CHECK_FALSE( ui.waitReady(sid,300,50,DefaultObjectId) );
CHECK_FALSE( ui.waitReady(sid,-1,50) ); CHECK_FALSE( ui.waitReady(sid,300,50,-20) );
CHECK_FALSE( ui.waitReady(sid,300,-1) ); CHECK_FALSE( ui.waitReady(sid,-1,50) );
CHECK_FALSE( ui.waitReady(sid,300,-1) );
CHECK_FALSE( ui.waitWorking(sid,100,50) );
CHECK_FALSE( ui.waitWorking(sid,100,50,DefaultObjectId) ); CHECK_FALSE( ui.waitWorking(sid,100,50) );
CHECK_FALSE( ui.waitWorking(sid,100,50,-20) ); CHECK_FALSE( ui.waitWorking(sid,100,50,DefaultObjectId) );
CHECK_FALSE( ui.waitWorking(sid,-1,50) ); CHECK_FALSE( ui.waitWorking(sid,100,50,-20) );
CHECK_FALSE( ui.waitWorking(sid,100,-1) ); CHECK_FALSE( ui.waitWorking(sid,-1,50) );
CHECK_FALSE( ui.waitWorking(sid,100,-1) );
std::string longName("UNISET_PLC/Sensors/" + sidName);
CHECK( ui.getIdByName(longName) == sid ); std::string longName("UNISET_PLC/Sensors/" + sidName);
CHECK( ui.getNameById(sid) == longName ); CHECK( ui.getIdByName(longName) == sid );
CHECK( ui.getTextName(sid) == "Команда 1" ); CHECK( ui.getNameById(sid) == longName );
CHECK( ui.getTextName(sid) == "Команда 1" );
CHECK( ui.getNodeId("localhost") == 1000 );
CHECK( ui.getNodeId("localhost") == 1000 );
} }
...@@ -142,38 +142,38 @@ int main( int argc, const char **argv ) ...@@ -142,38 +142,38 @@ int main( int argc, const char **argv )
try try
{ {
#if 0 #if 0
{ {
cout << "check timed_mutex..." << endl; cout << "check timed_mutex..." << endl;
std::timed_mutex m; std::timed_mutex m;
cout << " 'unlock' without 'lock'.."; cout << " 'unlock' without 'lock'..";
m.unlock(); m.unlock();
cout << " ok." << endl; cout << " ok." << endl;
cout << "try lock (lock): " << ( m.try_lock() ? "OK" : "FAIL" ) << endl; cout << "try lock (lock): " << ( m.try_lock() ? "OK" : "FAIL" ) << endl;
m.unlock(); m.unlock();
m.lock(); m.lock();
cout << "try lock (fail): " << ( m.try_lock() ? "FAIL" : "OK" ) << endl; cout << "try lock (fail): " << ( m.try_lock() ? "FAIL" : "OK" ) << endl;
m.unlock(); m.unlock();
} }
{ {
uniset_mutex m("testmutex"); uniset_mutex m("testmutex");
{ {
uniset_mutex_lock l(m); uniset_mutex_lock l(m);
msleep(20); msleep(20);
} }
{ {
uniset_mutex_lock l(m,100); uniset_mutex_lock l(m,100);
msleep(50); msleep(50);
} }
} }
#endif #endif
#if 0 #if 0
{ {
...@@ -303,8 +303,8 @@ int main( int argc, const char **argv ) ...@@ -303,8 +303,8 @@ int main( int argc, const char **argv )
int c = (*it)->lock_count(); int c = (*it)->lock_count();
(*it)->terminate(); (*it)->terminate();
if( (*it)->get()->isRunning() ) if( (*it)->get()->isRunning() )
(*it)->get()->join(); (*it)->get()->join();
//(*it)->get()->stop(); //(*it)->get()->stop();
cout << (*it)->name() << ": locked counter: " << (c/10) << " " << ( c!=0 ? "OK":"FAIL" ) << endl; cout << (*it)->name() << ": locked counter: " << (c/10) << " " << ( c!=0 ? "OK":"FAIL" ) << endl;
} }
#endif #endif
...@@ -318,14 +318,14 @@ int main( int argc, const char **argv ) ...@@ -318,14 +318,14 @@ int main( int argc, const char **argv )
ostringstream s; ostringstream s;
bool r=false; bool r=false;
#if 1 #if 1
if( i>=half ) if( i>=half )
{ {
r = true; r = true;
s << "(R)"; s << "(R)";
} }
else else
#endif #endif
s << "(W)"; s << "(W)";
s << "t" << i; s << "t" << i;
...@@ -345,7 +345,7 @@ int main( int argc, const char **argv ) ...@@ -345,7 +345,7 @@ int main( int argc, const char **argv )
int c = (*it)->lock_count(); int c = (*it)->lock_count();
(*it)->terminate(); (*it)->terminate();
if( (*it)->get()->isRunning() ) if( (*it)->get()->isRunning() )
(*it)->get()->join(); (*it)->get()->join();
cout << (*it)->name() << ": locked counter: " << (c/10) << " " << ( c!=0 ? "OK":"FAIL" ) << endl; cout << (*it)->name() << ": locked counter: " << (c/10) << " " << ( c!=0 ? "OK":"FAIL" ) << endl;
} }
...@@ -366,8 +366,8 @@ int main( int argc, const char **argv ) ...@@ -366,8 +366,8 @@ int main( int argc, const char **argv )
msleep(50); msleep(50);
} }
std::atomic_int cnt(0); std::atomic_int cnt(0);
std::atomic_int num(10); std::atomic_int num(10);
while( --num ) while( --num )
{ {
...@@ -378,7 +378,7 @@ int main( int argc, const char **argv ) ...@@ -378,7 +378,7 @@ int main( int argc, const char **argv )
// cerr << "(writeLock): ************* lock OK.." << endl; // cerr << "(writeLock): ************* lock OK.." << endl;
} }
msleep(10); msleep(10);
} }
cout << "WRITE LOCK: " << cnt << endl; cout << "WRITE LOCK: " << cnt << endl;
...@@ -388,7 +388,7 @@ int main( int argc, const char **argv ) ...@@ -388,7 +388,7 @@ int main( int argc, const char **argv )
int c = it->lock_count(); int c = it->lock_count();
it->terminate(); it->terminate();
if( it->get()->isRunning() ) if( it->get()->isRunning() )
it->get()->join(); it->get()->join();
// cout << it->name() << ": locked counter: " << c << " " << ( c!=0 ? "OK":"FAIL" ) << endl; // cout << it->name() << ": locked counter: " << c << " " << ( c!=0 ? "OK":"FAIL" ) << endl;
} }
......
...@@ -12,105 +12,105 @@ TEST_CASE("UniXML", "[UniXML]" ) ...@@ -12,105 +12,105 @@ TEST_CASE("UniXML", "[UniXML]" )
{ {
SECTION( "Default constructor" ) SECTION( "Default constructor" )
{ {
UniXML xml; UniXML xml;
CHECK_FALSE( xml.isOpen() ); CHECK_FALSE( xml.isOpen() );
} }
SECTION( "Bad file" ) SECTION( "Bad file" )
{ {
REQUIRE_THROWS_AS( UniXML("unknown.xml"), UniSetTypes::NameNotFound ); REQUIRE_THROWS_AS( UniXML("unknown.xml"), UniSetTypes::NameNotFound );
REQUIRE_THROWS_AS( UniXML("tests_unixml_badfile.xml"), UniSetTypes::Exception ); REQUIRE_THROWS_AS( UniXML("tests_unixml_badfile.xml"), UniSetTypes::Exception );
} }
UniXML uxml("tests_unixml.xml"); UniXML uxml("tests_unixml.xml");
CHECK( uxml.isOpen() ); CHECK( uxml.isOpen() );
xmlNode* cnode = uxml.findNode(uxml.getFirstNode(),"UniSet"); xmlNode* cnode = uxml.findNode(uxml.getFirstNode(),"UniSet");
CHECK( cnode != NULL ); CHECK( cnode != NULL );
// проверка поиска "вглубь" // проверка поиска "вглубь"
CHECK( uxml.findNode(uxml.getFirstNode(),"Services") != NULL ); CHECK( uxml.findNode(uxml.getFirstNode(),"Services") != NULL );
xmlNode* tnode = uxml.findNode(uxml.getFirstNode(),"TestData"); xmlNode* tnode = uxml.findNode(uxml.getFirstNode(),"TestData");
CHECK( tnode != NULL ); CHECK( tnode != NULL );
CHECK( uxml.getProp(tnode,"text") == "text" ); CHECK( uxml.getProp(tnode,"text") == "text" );
CHECK( uxml.getIntProp(tnode,"x") == 10 ); CHECK( uxml.getIntProp(tnode,"x") == 10 );
CHECK( uxml.getPIntProp(tnode,"y",-20) == 100 ); CHECK( uxml.getPIntProp(tnode,"y",-20) == 100 );
CHECK( uxml.getPIntProp(tnode,"zero",20) == 0 ); CHECK( uxml.getPIntProp(tnode,"zero",20) == 0 );
CHECK( uxml.getPIntProp(tnode,"negative",20) == -10 ); CHECK( uxml.getPIntProp(tnode,"negative",20) == -10 );
CHECK( uxml.getPIntProp(tnode,"unknown",20) == 20 ); CHECK( uxml.getPIntProp(tnode,"unknown",20) == 20 );
// nextNode // nextNode
// create // create
// remove // remove
// copy // copy
// nextNode // nextNode
SECTION( "Iterator" ); SECTION( "Iterator" );
{ {
UniXML::iterator it(cnode); UniXML::iterator it(cnode);
CHECK( it.getCurrent() != 0 ); CHECK( it.getCurrent() != 0 );
it = uxml.begin(); it = uxml.begin();
CHECK( it.find("UniSet") != 0 ); CHECK( it.find("UniSet") != 0 );
// поиск в глубину.. // поиск в глубину..
it = uxml.begin(); it = uxml.begin();
CHECK( it.find("TestProc") != 0 ); CHECK( it.find("TestProc") != 0 );
it = uxml.begin(); it = uxml.begin();
CHECK( it.getName() == "UNISETPLC" ); CHECK( it.getName() == "UNISETPLC" );
it.goChildren(); it.goChildren();
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it += 4; it += 4;
CHECK( it.getName() == "settings" ); CHECK( it.getName() == "settings" );
it -= 4; it -= 4;
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it = it + 4; it = it + 4;
CHECK( it.getName() == "settings" ); CHECK( it.getName() == "settings" );
it = it - 4; it = it - 4;
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it++; it++;
CHECK( it.getName() == "UniSet" ); CHECK( it.getName() == "UniSet" );
it--; it--;
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
++it; ++it;
CHECK( it.getName() == "UniSet" ); CHECK( it.getName() == "UniSet" );
--it; --it;
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it = uxml.begin(); it = uxml.begin();
CHECK( it.findName("TestNode","TestNode1") != 0 ); CHECK( it.findName("TestNode","TestNode1") != 0 );
it = uxml.begin(); it = uxml.begin();
CHECK( it.findName("TestNode","TestNode2") != 0 ); CHECK( it.findName("TestNode","TestNode2") != 0 );
it = uxml.begin(); it = uxml.begin();
it.goChildren(); it.goChildren();
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it.goParent(); it.goParent();
CHECK( it.getName() == "UNISETPLC" ); CHECK( it.getName() == "UNISETPLC" );
it = uxml.begin(); it = uxml.begin();
it.goChildren(); it.goChildren();
it.goEnd(); it.goEnd();
CHECK( it.getName() == "EndSection" ); CHECK( it.getName() == "EndSection" );
it.goBegin(); it.goBegin();
CHECK( it.getName() == "UserData" ); CHECK( it.getName() == "UserData" );
it = uxml.begin(); it = uxml.begin();
CHECK( it.find("TestData") != 0 ); CHECK( it.find("TestData") != 0 );
CHECK( it.getProp("text") == "text" ); CHECK( it.getProp("text") == "text" );
CHECK( it.getIntProp("x") == 10 ); CHECK( it.getIntProp("x") == 10 );
CHECK( it.getPIntProp("y",-20) == 100 ); CHECK( it.getPIntProp("y",-20) == 100 );
CHECK( it.getPIntProp("zero",20) == 0 ); CHECK( it.getPIntProp("zero",20) == 0 );
CHECK( it.getPIntProp("negative",20) == -10 ); CHECK( it.getPIntProp("negative",20) == -10 );
CHECK( it.getPIntProp("unknown",20) == 20 ); CHECK( it.getPIntProp("unknown",20) == 20 );
} }
} }
...@@ -8,48 +8,48 @@ using namespace UniSetTypes; ...@@ -8,48 +8,48 @@ using namespace UniSetTypes;
TEST_CASE("UniSetTypes: uni_atoi", "[utypes][uni_atoi]" ) TEST_CASE("UniSetTypes: uni_atoi", "[utypes][uni_atoi]" )
{ {
SECTION("int") SECTION("int")
{ {
REQUIRE( uni_atoi("100") == 100 ); REQUIRE( uni_atoi("100") == 100 );
REQUIRE( uni_atoi("-100") == -100 ); REQUIRE( uni_atoi("-100") == -100 );
REQUIRE( uni_atoi("0") == 0 ); REQUIRE( uni_atoi("0") == 0 );
REQUIRE( uni_atoi("-0") == 0 ); REQUIRE( uni_atoi("-0") == 0 );
ostringstream imax; ostringstream imax;
imax << std::numeric_limits<int>::max(); imax << std::numeric_limits<int>::max();
REQUIRE( uni_atoi(imax.str()) == std::numeric_limits<int>::max() ); REQUIRE( uni_atoi(imax.str()) == std::numeric_limits<int>::max() );
ostringstream imin; ostringstream imin;
imin << std::numeric_limits<int>::min(); imin << std::numeric_limits<int>::min();
REQUIRE( uni_atoi(imin.str()) == std::numeric_limits<int>::min() ); REQUIRE( uni_atoi(imin.str()) == std::numeric_limits<int>::min() );
} }
SECTION("unsigned int") SECTION("unsigned int")
{ {
ostringstream imax; ostringstream imax;
imax << std::numeric_limits<unsigned int>::max(); imax << std::numeric_limits<unsigned int>::max();
unsigned int uint_max_val = (unsigned int)uni_atoi(imax.str()); unsigned int uint_max_val = (unsigned int)uni_atoi(imax.str());
REQUIRE( uint_max_val == std::numeric_limits<unsigned int>::max() ); REQUIRE( uint_max_val == std::numeric_limits<unsigned int>::max() );
ostringstream imin; ostringstream imin;
imax << std::numeric_limits<int>::min(); imax << std::numeric_limits<int>::min();
unsigned int uint_min_val = (unsigned int)uni_atoi(imin.str()); // "0"? unsigned int uint_min_val = (unsigned int)uni_atoi(imin.str()); // "0"?
REQUIRE( uint_min_val == std::numeric_limits<unsigned int>::min() ); REQUIRE( uint_min_val == std::numeric_limits<unsigned int>::min() );
} }
SECTION("hex") SECTION("hex")
{ {
REQUIRE( uni_atoi("0xff") == 0xff ); REQUIRE( uni_atoi("0xff") == 0xff );
REQUIRE( uni_atoi("0xffff") == 0xffff ); REQUIRE( uni_atoi("0xffff") == 0xffff );
REQUIRE( uni_atoi("0x0") == 0 ); REQUIRE( uni_atoi("0x0") == 0 );
REQUIRE( (unsigned int)uni_atoi("0xffffffff") == 0xffffffff ); REQUIRE( (unsigned int)uni_atoi("0xffffffff") == 0xffffffff );
REQUIRE( uni_atoi("0xfffffff8") == 0xfffffff8 ); REQUIRE( uni_atoi("0xfffffff8") == 0xfffffff8 );
} }
WARN("Tests for 'UniSetTypes' incomplete..."); WARN("Tests for 'UniSetTypes' incomplete...");
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment