Commit 12cca635 authored by Pavel Vainerman's avatar Pavel Vainerman

backported to p8 as 2.5-alt18.M80P.19 (with rpmbph script)

parents 9f6a6de2 d2ae7b28
...@@ -41,8 +41,8 @@ static struct option longopts[] = ...@@ -41,8 +41,8 @@ static struct option longopts[] =
{ "start", no_argument, 0, 's' }, { "start", no_argument, 0, 's' },
{ "finish", no_argument, 0, 'f' }, { "finish", no_argument, 0, 'f' },
{ "foldUp", no_argument, 0, 'u' }, { "foldUp", no_argument, 0, 'u' },
{ "configure", required_argument, 0, 'r' }, { "configure", optional_argument, 0, 'r' },
{ "logrotate", required_argument, 0, 'l' }, { "logrotate", optional_argument, 0, 'l' },
{ "info", required_argument, 0, 'i' }, { "info", required_argument, 0, 'i' },
{ "setValue", required_argument, 0, 'x' }, { "setValue", required_argument, 0, 'x' },
{ "getValue", required_argument, 0, 'g' }, { "getValue", required_argument, 0, 'g' },
...@@ -60,6 +60,7 @@ string conffile("configure.xml"); ...@@ -60,6 +60,7 @@ string conffile("configure.xml");
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static bool commandToAll( const string& section, std::shared_ptr<ObjectRepository>& rep, Command cmd ); static bool commandToAll( const string& section, std::shared_ptr<ObjectRepository>& rep, Command cmd );
static void createSections(const std::shared_ptr<Configuration>& c ); static void createSections(const std::shared_ptr<Configuration>& c );
static void errDoNotReolve( const std::string& oname );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int omap(); int omap();
int configure( const string& args, UInterface& ui ); int configure( const string& args, UInterface& ui );
...@@ -183,7 +184,8 @@ int main(int argc, char** argv) ...@@ -183,7 +184,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return setValue(optarg, ui); string name = ( optarg ) ? optarg : "";
return setValue(name, ui);
} }
break; break;
...@@ -193,7 +195,8 @@ int main(int argc, char** argv) ...@@ -193,7 +195,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return getValue(optarg, ui); string name = ( optarg ) ? optarg : "";
return getValue(name, ui);
} }
break; break;
...@@ -203,7 +206,8 @@ int main(int argc, char** argv) ...@@ -203,7 +206,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return getRawValue(optarg, ui); string name = ( optarg ) ? optarg : "";
return getRawValue(name, ui);
} }
break; break;
...@@ -212,7 +216,8 @@ int main(int argc, char** argv) ...@@ -212,7 +216,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return getChangedTime(optarg, ui); string name = ( optarg ) ? optarg : "";
return getChangedTime(name, ui);
} }
break; break;
...@@ -270,7 +275,8 @@ int main(int argc, char** argv) ...@@ -270,7 +275,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return configure(optarg, ui); string name = ( optarg ) ? optarg : "";
return configure(name, ui);
} }
break; break;
...@@ -298,7 +304,8 @@ int main(int argc, char** argv) ...@@ -298,7 +304,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return logRotate(optarg, ui); string name = ( optarg ) ? optarg : "";
return logRotate(name, ui);
} }
break; break;
...@@ -308,7 +315,8 @@ int main(int argc, char** argv) ...@@ -308,7 +315,8 @@ int main(int argc, char** argv)
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
ui.initBackId(UniSetTypes::AdminID); ui.initBackId(UniSetTypes::AdminID);
return getCalibrate(optarg, ui); string name = ( optarg ) ? optarg : "";
return getCalibrate(name, ui);
} }
break; break;
...@@ -365,6 +373,11 @@ int main(int argc, char** argv) ...@@ -365,6 +373,11 @@ int main(int argc, char** argv)
cerr << " mesg: " << fe.errmsg() << endl; cerr << " mesg: " << fe.errmsg() << endl;
} }
} }
catch( std::exception& ex )
{
if( !quiet )
cerr << "exception: " << ex.what() << endl;
}
catch(...) catch(...)
{ {
if( !quiet ) if( !quiet )
...@@ -418,7 +431,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -418,7 +431,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
{ {
case StartUp: case StartUp:
{ {
if(CORBA::is_nil(obj)) break; if( CORBA::is_nil(obj) )
{
errDoNotReolve(ob);
break;
}
SystemMessage msg(SystemMessage::StartUp); SystemMessage msg(SystemMessage::StartUp);
obj->push( Message::transport(msg) ); obj->push( Message::transport(msg) );
...@@ -430,7 +447,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -430,7 +447,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
case FoldUp: case FoldUp:
{ {
if(CORBA::is_nil(obj)) break; if(CORBA::is_nil(obj))
{
errDoNotReolve(ob);
break;
}
SystemMessage msg(SystemMessage::FoldUp); SystemMessage msg(SystemMessage::FoldUp);
obj->push( Message::transport(msg) ); obj->push( Message::transport(msg) );
...@@ -442,7 +463,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -442,7 +463,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
case Finish: case Finish:
{ {
if(CORBA::is_nil(obj)) break; if(CORBA::is_nil(obj))
{
errDoNotReolve(ob);
break;
}
SystemMessage msg(SystemMessage::Finish); SystemMessage msg(SystemMessage::Finish);
obj->push( Message::transport(msg) ); obj->push( Message::transport(msg) );
...@@ -511,6 +536,9 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -511,6 +536,9 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
} }
catch( ORepFailed ) catch( ORepFailed )
{ {
if( !quiet )
cerr << "..ORepFailed.." << endl;
cout.setf(old_flags); cout.setf(old_flags);
return false; return false;
} }
...@@ -875,7 +903,7 @@ int logRotate( const string& arg, UInterface& ui ) ...@@ -875,7 +903,7 @@ int logRotate( const string& arg, UInterface& ui )
auto conf = ui.getConf(); auto conf = ui.getConf();
// посылка всем // посылка всем
if( arg.empty() || (arg.c_str())[0] != '-' ) if( arg.empty() || arg[0] == '-' )
{ {
auto rep = make_shared<ObjectRepository>(conf); auto rep = make_shared<ObjectRepository>(conf);
commandToAll(conf->getServicesSection(), rep, (Command)LogRotate); commandToAll(conf->getServicesSection(), rep, (Command)LogRotate);
...@@ -884,12 +912,16 @@ int logRotate( const string& arg, UInterface& ui ) ...@@ -884,12 +912,16 @@ int logRotate( const string& arg, UInterface& ui )
} }
else // посылка определённому объекту else // посылка определённому объекту
{ {
UniSetTypes::ObjectId id = conf->oind->getIdByName(arg); UniSetTypes::ObjectId id = conf->getObjectID(arg);
if( id == DefaultObjectId )
id = conf->getControllerID(arg);
else if( id == DefaultObjectId )
id = conf->getServiceID(arg);
if( id == DefaultObjectId ) if( id == DefaultObjectId )
{ {
if( !quiet ) if( !quiet )
cout << "(logrotate): name='" << arg << "' не найдено!!!\n"; cout << "(logrotate): not found ID for name='" << arg << "'" << endl;
return 1; return 1;
} }
...@@ -911,7 +943,7 @@ int configure( const string& arg, UInterface& ui ) ...@@ -911,7 +943,7 @@ int configure( const string& arg, UInterface& ui )
auto conf = ui.getConf(); auto conf = ui.getConf();
// посылка всем // посылка всем
if( arg.empty() || (arg.c_str())[0] != '-' ) if( arg.empty() || arg[0] == '-' )
{ {
auto rep = make_shared<ObjectRepository>(conf); auto rep = make_shared<ObjectRepository>(conf);
commandToAll(conf->getServicesSection(), rep, (Command)Configure); commandToAll(conf->getServicesSection(), rep, (Command)Configure);
...@@ -920,7 +952,12 @@ int configure( const string& arg, UInterface& ui ) ...@@ -920,7 +952,12 @@ int configure( const string& arg, UInterface& ui )
} }
else // посылка определённому объекту else // посылка определённому объекту
{ {
UniSetTypes::ObjectId id = conf->oind->getIdByName(arg); UniSetTypes::ObjectId id = conf->getObjectID(arg);
if( id == DefaultObjectId )
id = conf->getControllerID(arg);
if( id == DefaultObjectId )
id = conf->getServiceID(arg);
if( id == DefaultObjectId ) if( id == DefaultObjectId )
{ {
...@@ -1010,3 +1047,9 @@ int oinfo( const string& args, UInterface& ui, int userparam ) ...@@ -1010,3 +1047,9 @@ int oinfo( const string& args, UInterface& ui, int userparam )
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
void errDoNotReolve( const std::string& oname )
{
if( verb )
cerr << oname << ": resolve failed.." << endl;
}
// --------------------------------------------------------------------------------------
...@@ -87,7 +87,7 @@ int main( int argc, char** argv ) ...@@ -87,7 +87,7 @@ int main( int argc, char** argv )
LogServerTypes::Command cmd = LogServerTypes::cmdNOP; LogServerTypes::Command cmd = LogServerTypes::cmdNOP;
int cmdonly = 0; int cmdonly = 0;
timeout_t tout = UniSetTimer::WaitUpTime; timeout_t tout = UniSetTimer::WaitUpTime;
timeout_t rdelay = 5000; timeout_t rdelay = 8000;
string logfile(""); string logfile("");
bool logtruncate = false; bool logtruncate = false;
......
...@@ -167,7 +167,6 @@ int main( int argc, char** argv ) ...@@ -167,7 +167,6 @@ int main( int argc, char** argv )
la->printLogList(cout); la->printLogList(cout);
return 0; return 0;
#endif #endif
LogServer ls(la); LogServer ls(la);
ls.setMaxSessionCount(msess); ls.setMaxSessionCount(msess);
...@@ -214,9 +213,9 @@ int main( int argc, char** argv ) ...@@ -214,9 +213,9 @@ int main( int argc, char** argv )
{ {
cerr << "(logserver): " << ex << endl; cerr << "(logserver): " << ex << endl;
} }
catch(...) catch( std::exception& ex)
{ {
cerr << "(logserver): catch(...)" << endl; cerr << "(logserver): " << ex.what() << endl;
} }
return 0; return 0;
......
...@@ -474,6 +474,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage* ...@@ -474,6 +474,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage*
mylog->logFile(fname.c_str(),true); mylog->logFile(fname.c_str(),true);
mylogany &lt;&lt; myname &lt;&lt; "(preSysCommand): ***************** mylog LOG ROTATE *****************" &lt;&lt; endl; mylogany &lt;&lt; myname &lt;&lt; "(preSysCommand): ***************** mylog LOG ROTATE *****************" &lt;&lt; endl;
} }
if( logserv &amp;&amp; !logserv_host.empty() &amp;&amp; logserv_port != 0 )
logserv-&gt;check(true);
} }
break; break;
...@@ -493,7 +496,16 @@ UniSetTypes::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA: ...@@ -493,7 +496,16 @@ UniSetTypes::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA:
ostringstream inf; ostringstream inf;
inf &lt;&lt; i->info &lt;&lt; endl; inf &lt;&lt; i->info &lt;&lt; endl;
inf &lt;&lt; "LogServer: " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port &lt;&lt; endl; if( logserv /* &amp;&amp; userparam &lt; 0 */ )
{
inf &lt;&lt; "LogServer: " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port
&lt;&lt; ( logserv->isRunning() ? " [RUNNIG]" : " [FAILED]" ) &lt;&lt; endl;
inf &lt;&lt; " " &lt;&lt; logserv->getShortInfo() &lt;&lt; endl;
}
else
inf &lt;&lt; "LogServer: NONE" &lt;&lt; endl;
inf &lt;&lt; dumpIO() &lt;&lt; endl; inf &lt;&lt; dumpIO() &lt;&lt; endl;
inf &lt;&lt; endl; inf &lt;&lt; endl;
auto timers = getTimersList(); auto timers = getTimersList();
...@@ -658,8 +670,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -658,8 +670,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
// terminate(); // terminate();
// abort(); // abort();
raise(SIGTERM); // raise(SIGTERM);
terminate(); std::terminate();
// throw SystemError(err.str()); // throw SystemError(err.str());
} }
...@@ -673,7 +685,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -673,7 +685,8 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
// terminate(); // terminate();
// abort(); // abort();
raise(SIGTERM); //raise(SIGTERM);
std::terminate();
// throw SystemError(err.str()); // throw SystemError(err.str());
} }
} }
...@@ -1121,6 +1134,7 @@ end_private(false) ...@@ -1121,6 +1134,7 @@ end_private(false)
vmonit(maxHeartBeat); vmonit(maxHeartBeat);
vmonit(activateTimeout); vmonit(activateTimeout);
vmonit(smReadyTimeout); vmonit(smReadyTimeout);
vmonit(smTestID);
// help надо выводить в конце, когда уже все переменные инициализированы по умолчанию // help надо выводить в конце, когда уже все переменные инициализированы по умолчанию
...@@ -1510,6 +1524,9 @@ askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)) ...@@ -1510,6 +1524,9 @@ askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000))
if( smTestID == DefaultObjectId ) if( smTestID == DefaultObjectId )
smTestID = getSMTestID(); smTestID = getSMTestID();
vmonit(smTestID);
vmonit(smReadyTimeout);
activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000); activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000);
int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 10000); int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 10000);
......
...@@ -42,6 +42,7 @@ TestGen::TestGen() ...@@ -42,6 +42,7 @@ TestGen::TestGen()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::step() void TestGen::step()
{ {
#if 0
cout << "strval: " << strval(input2_s) << endl; cout << "strval: " << strval(input2_s) << endl;
cout << "str: " << str(input2_s) << endl; cout << "str: " << str(input2_s) << endl;
cout << "===========" << endl; cout << "===========" << endl;
...@@ -53,7 +54,7 @@ void TestGen::step() ...@@ -53,7 +54,7 @@ void TestGen::step()
int_var++; int_var++;
bool_var ^= true; bool_var ^= true;
cout << vmon << endl; cout << vmon << endl;
#endif
// cout << vmon.pretty_str() << endl; // cout << vmon.pretty_str() << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -2,8 +2,9 @@ ...@@ -2,8 +2,9 @@
ulimit -Sc 1000000 ulimit -Sc 1000000
uniset2-start.sh -f ./test --name TestProc --confile test.xml --ulog-add-levels warn,crit \ uniset2-start.sh -f ./test --name TestProc --confile test.xml --ulog-add-levels system,warn,crit \
--test-sm-ready-timeout 15000 --test-run-logserver --test-log-add-levels any $* --test-sm-ready-timeout 15000 --test-run-logserver --test-logserver-host 192.192.192.192
#--test-log-add-levels any $*
#info,warn,crit,system,level9 > 1.log #info,warn,crit,system,level9 > 1.log
#--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1 #--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
Name: libuniset2 Name: libuniset2
Version: 2.5 Version: 2.5
Release: alt13.M80P.14 Release: alt18.M80P.19
Summary: UniSet - library for building distributed industrial control systems Summary: UniSet - library for building distributed industrial control systems
License: LGPL License: LGPL
...@@ -488,9 +488,40 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -488,9 +488,40 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
# .. # ..
%changelog %changelog
* Tue Sep 13 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt13.M80P.14 * Tue Oct 11 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt18.M80P.19
- backport to ALTLinux p8 (by rpmbph script) - backport to ALTLinux p8 (by rpmbph script)
* Tue Oct 11 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt19
- Calibration: fixed bug in getValue(), refactoring
- correction after verification static analyzer
- LogServer: fixed bug "connection refuse"
* Sat Oct 08 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt18
- LogServer: fixed bug "do not close connection"
* Fri Sep 30 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt17
- ModbusMultiMaster: add new check connection strategy
- LogServer: minor fixes
* Tue Sep 27 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt16
- LogSession: add more logs
- codegen: add logserver information in getInfo()
* Tue Sep 20 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt15
- up build
* Tue Sep 20 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14.4
- UTCPStream: check POCO_INVALID_SOCKET
* Mon Sep 19 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14.3
- UTCPStream: shudown and close (for disconnect)
* Mon Sep 19 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14.2
- (ModbusTCPMaster): added disconnect() function
* Mon Sep 19 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14.1
- (ModbusTCPMaster): added catch exceptions
* Mon Sep 12 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14 * Mon Sep 12 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14
- up build - up build
......
...@@ -50,4 +50,3 @@ ...@@ -50,4 +50,3 @@
\note Описание составлено на основе описания мьютексов из книги А.Цимбала "Технология CORBA для профессионалов". \note Описание составлено на основе описания мьютексов из книги А.Цимбала "Технология CORBA для профессионалов".
*/ */
...@@ -34,4 +34,10 @@ d_DATA = html/* ...@@ -34,4 +34,10 @@ d_DATA = html/*
# exampledir = $(docdir)/examples # exampledir = $(docdir)/examples
# example_DATA = examples/* # example_DATA = examples/*
pdf:
doxygen UniSetDox.cfg
subst 's|OT1|T2A|g' latex/doxygen.sty
subst 's|Times-Roman|Liberation Sans|g' latex/*
cd latex; make; cd -;
endif endif
...@@ -247,12 +247,12 @@ EXTENSION_MAPPING = ...@@ -247,12 +247,12 @@ EXTENSION_MAPPING =
# func(std::string) {}). This also makes the inheritance and collaboration # func(std::string) {}). This also makes the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate. # diagrams that involve STL classes more complete and accurate.
BUILTIN_STL_SUPPORT = NO BUILTIN_STL_SUPPORT = YES
# If you use Microsoft's C++/CLI language, you should set this option to YES to # If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support. # enable parsing support.
CPP_CLI_SUPPORT = NO CPP_CLI_SUPPORT = YES
# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
# Doxygen will parse them like normal C++ but will assume all classes use public # Doxygen will parse them like normal C++ but will assume all classes use public
...@@ -377,7 +377,7 @@ EXTRACT_LOCAL_METHODS = NO ...@@ -377,7 +377,7 @@ EXTRACT_LOCAL_METHODS = NO
# name of the file that contains the anonymous namespace. By default # name of the file that contains the anonymous namespace. By default
# anonymous namespaces are hidden. # anonymous namespaces are hidden.
EXTRACT_ANON_NSPACES = NO EXTRACT_ANON_NSPACES = YES
# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
# undocumented members of documented classes, files or namespaces. # undocumented members of documented classes, files or namespaces.
...@@ -421,7 +421,7 @@ INTERNAL_DOCS = NO ...@@ -421,7 +421,7 @@ INTERNAL_DOCS = NO
# in case and if your file system supports case sensitive file names. Windows # in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO. # and Mac users are advised to set this option to NO.
CASE_SENSE_NAMES = YES CASE_SENSE_NAMES = NO
# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
# will show members with their full class and namespace scopes in the # will show members with their full class and namespace scopes in the
...@@ -433,7 +433,7 @@ HIDE_SCOPE_NAMES = NO ...@@ -433,7 +433,7 @@ HIDE_SCOPE_NAMES = NO
# will put a list of the files that are included by a file in the documentation # will put a list of the files that are included by a file in the documentation
# of that file. # of that file.
SHOW_INCLUDE_FILES = YES SHOW_INCLUDE_FILES = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
# will list include files with double quotes in the documentation # will list include files with double quotes in the documentation
...@@ -499,25 +499,25 @@ STRICT_PROTO_MATCHING = NO ...@@ -499,25 +499,25 @@ STRICT_PROTO_MATCHING = NO
# disable (NO) the todo list. This list is created by putting \todo # disable (NO) the todo list. This list is created by putting \todo
# commands in the documentation. # commands in the documentation.
GENERATE_TODOLIST = YES GENERATE_TODOLIST = NO
# The GENERATE_TESTLIST tag can be used to enable (YES) or # The GENERATE_TESTLIST tag can be used to enable (YES) or
# disable (NO) the test list. This list is created by putting \test # disable (NO) the test list. This list is created by putting \test
# commands in the documentation. # commands in the documentation.
GENERATE_TESTLIST = YES GENERATE_TESTLIST = NO
# The GENERATE_BUGLIST tag can be used to enable (YES) or # The GENERATE_BUGLIST tag can be used to enable (YES) or
# disable (NO) the bug list. This list is created by putting \bug # disable (NO) the bug list. This list is created by putting \bug
# commands in the documentation. # commands in the documentation.
GENERATE_BUGLIST = YES GENERATE_BUGLIST = NO
# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
# disable (NO) the deprecated list. This list is created by putting # disable (NO) the deprecated list. This list is created by putting
# \deprecated commands in the documentation. # \deprecated commands in the documentation.
GENERATE_DEPRECATEDLIST= YES GENERATE_DEPRECATEDLIST= NO
# The ENABLED_SECTIONS tag can be used to enable conditional # The ENABLED_SECTIONS tag can be used to enable conditional
# documentation sections, marked by \if sectionname ... \endif. # documentation sections, marked by \if sectionname ... \endif.
...@@ -532,25 +532,25 @@ ENABLED_SECTIONS = ...@@ -532,25 +532,25 @@ ENABLED_SECTIONS =
# documentation can be controlled using \showinitializer or \hideinitializer # documentation can be controlled using \showinitializer or \hideinitializer
# command in the documentation regardless of this setting. # command in the documentation regardless of this setting.
MAX_INITIALIZER_LINES = 30 MAX_INITIALIZER_LINES = 25
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated # Set the SHOW_USED_FILES tag to NO to disable the list of files generated
# at the bottom of the documentation of classes and structs. If set to YES the # at the bottom of the documentation of classes and structs. If set to YES the
# list will mention the files that were used to generate the documentation. # list will mention the files that were used to generate the documentation.
SHOW_USED_FILES = YES SHOW_USED_FILES = NO
# If the sources in your project are distributed over multiple directories # If the sources in your project are distributed over multiple directories
# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
# in the documentation. The default is NO. # in the documentation. The default is NO.
SHOW_DIRECTORIES = YES SHOW_DIRECTORIES = NO
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. # Set the SHOW_FILES tag to NO to disable the generation of the Files page.
# This will remove the Files entry from the Quick Index and from the # This will remove the Files entry from the Quick Index and from the
# Folder Tree View (if specified). The default is YES. # Folder Tree View (if specified). The default is YES.
SHOW_FILES = YES SHOW_FILES = NO
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Set the SHOW_NAMESPACES tag to NO to disable the generation of the
# Namespaces page. This will remove the Namespaces entry from the Quick Index # Namespaces page. This will remove the Namespaces entry from the Quick Index
...@@ -800,13 +800,13 @@ STRIP_CODE_COMMENTS = YES ...@@ -800,13 +800,13 @@ STRIP_CODE_COMMENTS = YES
# then for each documented function all documented # then for each documented function all documented
# functions referencing it will be listed. # functions referencing it will be listed.
REFERENCED_BY_RELATION = YES REFERENCED_BY_RELATION = NO
# If the REFERENCES_RELATION tag is set to YES # If the REFERENCES_RELATION tag is set to YES
# then for each documented function all documented entities # then for each documented function all documented entities
# called/used by that function will be listed. # called/used by that function will be listed.
REFERENCES_RELATION = YES REFERENCES_RELATION = NO
# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
...@@ -837,7 +837,7 @@ VERBATIM_HEADERS = YES ...@@ -837,7 +837,7 @@ VERBATIM_HEADERS = YES
# of all compounds will be generated. Enable this if the project # of all compounds will be generated. Enable this if the project
# contains a lot of classes, structs, unions or interfaces. # contains a lot of classes, structs, unions or interfaces.
ALPHABETICAL_INDEX = NO ALPHABETICAL_INDEX = YES
# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
...@@ -1222,7 +1222,7 @@ SERVER_BASED_SEARCH = NO ...@@ -1222,7 +1222,7 @@ SERVER_BASED_SEARCH = NO
# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
# generate Latex output. # generate Latex output.
GENERATE_LATEX = NO GENERATE_LATEX = YES
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be # If a relative path is entered the value of OUTPUT_DIRECTORY will be
...@@ -1248,7 +1248,7 @@ MAKEINDEX_CMD_NAME = makeindex ...@@ -1248,7 +1248,7 @@ MAKEINDEX_CMD_NAME = makeindex
# LaTeX documents. This may be useful for small projects and may help to # LaTeX documents. This may be useful for small projects and may help to
# save some trees in general. # save some trees in general.
COMPACT_LATEX = NO COMPACT_LATEX = YES
# The PAPER_TYPE tag can be used to set the paper type that is used # The PAPER_TYPE tag can be used to set the paper type that is used
# by the printer. Possible values are: a4, letter, legal and # by the printer. Possible values are: a4, letter, legal and
...@@ -1280,13 +1280,13 @@ LATEX_FOOTER = ...@@ -1280,13 +1280,13 @@ LATEX_FOOTER =
# contain links (just like the HTML output) instead of page references # contain links (just like the HTML output) instead of page references
# This makes the output suitable for online browsing using a pdf viewer. # This makes the output suitable for online browsing using a pdf viewer.
PDF_HYPERLINKS = NO PDF_HYPERLINKS = YES
# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
# plain latex in the generated Makefile. Set this option to YES to get a # plain latex in the generated Makefile. Set this option to YES to get a
# higher quality PDF documentation. # higher quality PDF documentation.
USE_PDFLATEX = NO USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
# command to the generated LaTeX files. This will instruct LaTeX to keep # command to the generated LaTeX files. This will instruct LaTeX to keep
...@@ -1328,13 +1328,13 @@ GENERATE_RTF = NO ...@@ -1328,13 +1328,13 @@ GENERATE_RTF = NO
# If a relative path is entered the value of OUTPUT_DIRECTORY will be # If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `rtf' will be used as the default path. # put in front of it. If left blank `rtf' will be used as the default path.
RTF_OUTPUT = rtf RTF_OUTPUT = rtf2
# If the COMPACT_RTF tag is set to YES Doxygen generates more compact # If the COMPACT_RTF tag is set to YES Doxygen generates more compact
# RTF documents. This may be useful for small projects and may help to # RTF documents. This may be useful for small projects and may help to
# save some trees in general. # save some trees in general.
COMPACT_RTF = NO COMPACT_RTF = YES
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
# will contain hyperlink fields. The RTF file will # will contain hyperlink fields. The RTF file will
...@@ -1608,7 +1608,7 @@ HIDE_UNDOC_RELATIONS = YES ...@@ -1608,7 +1608,7 @@ HIDE_UNDOC_RELATIONS = YES
# toolkit from AT&T and Lucent Bell Labs. The other options in this section # toolkit from AT&T and Lucent Bell Labs. The other options in this section
# have no effect if this option is set to NO (the default) # have no effect if this option is set to NO (the default)
HAVE_DOT = NO HAVE_DOT = YES
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
# allowed to run in parallel. When set to 0 (the default) doxygen will # allowed to run in parallel. When set to 0 (the default) doxygen will
...@@ -1770,7 +1770,7 @@ MAX_DOT_GRAPH_DEPTH = 0 ...@@ -1770,7 +1770,7 @@ MAX_DOT_GRAPH_DEPTH = 0
# enabling this option may lead to badly anti-aliased labels on the edges of # enabling this option may lead to badly anti-aliased labels on the edges of
# a graph (i.e. they become hard to read). # a graph (i.e. they become hard to read).
DOT_TRANSPARENT = YES DOT_TRANSPARENT = NO
# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This # files in one run (i.e. multiple -o and -T options on the command line). This
......
...@@ -384,10 +384,12 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -384,10 +384,12 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
askTimer(DBServer_MySQL::ReconnectTimer, 0); askTimer(DBServer_MySQL::ReconnectTimer, 0);
askTimer(DBServer_MySQL::PingTimer, PingTime); askTimer(DBServer_MySQL::PingTimer, PingTime);
} }
else
{
connect_ok = false; connect_ok = false;
dbwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
}
else else
initDBServer(); initDBServer();
} }
......
...@@ -220,10 +220,9 @@ void DBServer_PostgreSQL::flushInsertBuffer() ...@@ -220,10 +220,9 @@ void DBServer_PostgreSQL::flushInsertBuffer()
} }
ibuf.erase(beg, end); ibuf.erase(beg, end);
ibufSize -= delnum;
if( ibufSize < 0 ) // ibufSize - беззнаковое, так что надо аккуратно
ibufSize = 0; ibufSize = (delnum < ibufSize) ? (ibufSize-delnum) : 0;
dbwarn << myname << "(flushInsertBuffer): overflow: clear data " << delnum << " records." << endl; dbwarn << myname << "(flushInsertBuffer): overflow: clear data " << delnum << " records." << endl;
return; return;
...@@ -438,10 +437,12 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -438,10 +437,12 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm )
askTimer(DBServer_PostgreSQL::ReconnectTimer, 0); askTimer(DBServer_PostgreSQL::ReconnectTimer, 0);
askTimer(DBServer_PostgreSQL::PingTimer, PingTime); askTimer(DBServer_PostgreSQL::PingTimer, PingTime);
} }
else
{
connect_ok = false; connect_ok = false;
dbwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
}
else else
initDBServer(); initDBServer();
} }
......
...@@ -110,7 +110,7 @@ class DBServer_PostgreSQL: ...@@ -110,7 +110,7 @@ class DBServer_PostgreSQL:
typedef std::queue<std::string> QueryBuffer; typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf; QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений. size_t qbufSize; // размер буфера сообщений.
bool lastRemove = { false }; bool lastRemove = { false };
void flushBuffer(); void flushBuffer();
......
...@@ -359,10 +359,12 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -359,10 +359,12 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
askTimer(DBServer_SQLite::ReconnectTimer, 0); askTimer(DBServer_SQLite::ReconnectTimer, 0);
askTimer(DBServer_SQLite::PingTimer, PingTime); askTimer(DBServer_SQLite::PingTimer, PingTime);
} }
else
{
connect_ok = false; connect_ok = false;
dbwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
}
else else
initDBServer(); initDBServer();
} }
......
...@@ -69,9 +69,9 @@ IOControl::IOControl(UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, ...@@ -69,9 +69,9 @@ IOControl::IOControl(UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID,
auto conf = uniset_conf(); auto conf = uniset_conf();
string cname = conf->getArgParam("--" + prefix + "-confnode", myname); string cname = conf->getArgParam("--" + prefix + "-confnode", myname);
cnode = conf->getNode(cname); confnode = conf->getNode(cname);
if( cnode == NULL ) if( confnode == NULL )
throw SystemError("Not found conf-node " + cname + " for " + myname); throw SystemError("Not found conf-node " + cname + " for " + myname);
iolog = make_shared<DebugStream>(); iolog = make_shared<DebugStream>();
...@@ -89,10 +89,10 @@ IOControl::IOControl(UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, ...@@ -89,10 +89,10 @@ IOControl::IOControl(UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID,
ioinfo << myname << "(init): numcards=" << numcards << endl; ioinfo << myname << "(init): numcards=" << numcards << endl;
UniXML::iterator it(cnode); UniXML::iterator it(confnode);
logserv = make_shared<LogServer>(loga); logserv = make_shared<LogServer>(loga);
logserv->init( prefix + "-logserver", cnode ); logserv->init( prefix + "-logserver", confnode );
if( findArgParam("--" + prefix + "-run-logserver", conf->getArgc(), conf->getArgv()) != -1 ) if( findArgParam("--" + prefix + "-run-logserver", conf->getArgc(), conf->getArgv()) != -1 )
{ {
...@@ -306,7 +306,7 @@ IOControl::~IOControl() ...@@ -306,7 +306,7 @@ IOControl::~IOControl()
void IOControl::execute() void IOControl::execute()
{ {
// set_signals(true); // set_signals(true);
UniXML::iterator it(cnode); UniXML::iterator it(confnode);
waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы
...@@ -1055,7 +1055,9 @@ void IOControl::check_testmode() ...@@ -1055,7 +1055,9 @@ void IOControl::check_testmode()
// если режим "выключено всё" // если режим "выключено всё"
// то гасим все выходы // то гасим все выходы
if( testmode == tmOffPoll ) if( testmode == tmOffPoll ||
testmode == tmConfigEnable ||
testmode == tmConfigDisable )
{ {
// выставляем безопасные состояния // выставляем безопасные состояния
for( auto& it : iomap ) for( auto& it : iomap )
...@@ -1602,17 +1604,15 @@ void IOControl::buildCardsList() ...@@ -1602,17 +1604,15 @@ void IOControl::buildCardsList()
return; return;
} }
//xmlNode* cnode = xml->findNode(mynode,"iocards",""); xmlNode* cardsnode = xml->extFindNode(mynode, 1, 1, "iocards", "");
//xmlNode* extFindNode(xmlNode* node, int depth, int width, const std::string searchnode, const std::string name = "", bool top=true );
xmlNode* cnode = xml->extFindNode(mynode, 1, 1, "iocards", "");
if( !cnode ) if( !cardsnode )
{ {
iowarn << myname << "(buildCardsList): Not found <iocards> for node=" << conf->getLocalNodeName() << "(" << conf->getLocalNode() << ")" << endl; iowarn << myname << "(buildCardsList): Not found <iocards> for node=" << conf->getLocalNodeName() << "(" << conf->getLocalNode() << ")" << endl;
return; return;
} }
UniXML::iterator it(cnode); UniXML::iterator it(cardsnode);
if( !it.goChildren() ) if( !it.goChildren() )
{ {
......
...@@ -335,7 +335,7 @@ class IOControl: ...@@ -335,7 +335,7 @@ class IOControl:
void waitSM(); void waitSM();
xmlNode* cnode = { 0 }; /*!< xml-узел в настроечном файле */ xmlNode* confnode = { 0 }; /*!< xml-узел в настроечном файле */
int polltime = { 150 }; /*!< переодичность обновления данных (опроса карт в/в), [мсек] */ int polltime = { 150 }; /*!< переодичность обновления данных (опроса карт в/в), [мсек] */
CardList cards; /*!< список карт - массив созданных ComediInterface */ CardList cards; /*!< список карт - массив созданных ComediInterface */
......
...@@ -72,7 +72,6 @@ int subdev = 0; ...@@ -72,7 +72,6 @@ int subdev = 0;
int chan = 0; int chan = 0;
int range = 0; int range = 0;
int aref = AREF_GROUND; int aref = AREF_GROUND;
bool go = true;
static struct option longopts[] = static struct option longopts[] =
{ {
......
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
- \ref sec_MBTCPM_Conf - \ref sec_MBTCPM_Conf
- \ref sec_MBTCPM_ConfList - \ref sec_MBTCPM_ConfList
- \ref sec_MBTCPM_ExchangeMode - \ref sec_MBTCPM_ExchangeMode
- \ref sec_MBTCPM_CheckConnection
\section sec_MBTCPM_Comm Общее описание ModbusTCPMultiMaster \section sec_MBTCPM_Comm Общее описание ModbusTCPMultiMaster
Класс реализует процесс обмена (опрос/запись) с RTU-устройствами, Класс реализует процесс обмена (опрос/запись) с RTU-устройствами,
...@@ -85,6 +86,9 @@ ...@@ -85,6 +86,9 @@
- \b respond_invert - инвертировать датчик связи (DI) - \b respond_invert - инвертировать датчик связи (DI)
- \b force [1,0] - "1" - обновлять значение датчика связи в SM принудительно на каждом цикле проверки ("0" - только по изменению). - \b force [1,0] - "1" - обновлять значение датчика связи в SM принудительно на каждом цикле проверки ("0" - только по изменению).
- \b timeout - таймаут на определение отсутсвия связи для данного канала. По умолчанию берётся глобальный. - \b timeout - таймаут на определение отсутсвия связи для данного канала. По умолчанию берётся глобальный.
- \b checkFunc - Номер функции для проверки соединения
- \b checkAddr - Адрес устройства для проверки соединения
- \b checkReg - Регистр для проверки соединения
\par Параметры запуска \par Параметры запуска
...@@ -143,6 +147,11 @@ ...@@ -143,6 +147,11 @@
\b --xxx-activate-timeout msec . По умолчанию 2000. - время ожидания готовности SharedMemory к работе. \b --xxx-activate-timeout msec . По умолчанию 2000. - время ожидания готовности SharedMemory к работе.
\b --xxx-check-func [1,2,3,4] - Номер функции для проверки соединения
\b --xxx-check-addr [1..255 ] - Адрес устройства для проверки соединения
\b --xxx-check-reg [1..65535] - Регистр для проверки соединения
\b --xxx-check-init-from-regmap - Взять адрес, функцию и регистр для проверки связи из списка опроса
\section sec_MBTCPM_ConfList Конфигурирование списка регистров для ModbusTCP master \section sec_MBTCPM_ConfList Конфигурирование списка регистров для ModbusTCP master
Конфигурационные параметры задаются в секции <sensors> конфигурационного файла. Конфигурационные параметры задаются в секции <sensors> конфигурационного файла.
Список обрабатываемых регистров задаётся при помощи двух параметров командной строки Список обрабатываемых регистров задаётся при помощи двух параметров командной строки
...@@ -207,8 +216,6 @@ ...@@ -207,8 +216,6 @@
регистры в устройство писатся не будут. Чтобы отключить это поведение, можно указать параметр регистры в устройство писатся не будут. Чтобы отключить это поведение, можно указать параметр
- \b tcp_sm_initOK - [0|1] Игнорировать начальную инициализацию из SM (сразу писать в устройство) - \b tcp_sm_initOK - [0|1] Игнорировать начальную инициализацию из SM (сразу писать в устройство)
При этом будет записывыться значение "default". При этом будет записывыться значение "default".
\warning Регистр должен быть уникальным. И может повторятся только если указан параметр \a nbit или \a nbyte. \warning Регистр должен быть уникальным. И может повторятся только если указан параметр \a nbit или \a nbyte.
...@@ -228,10 +235,43 @@ ...@@ -228,10 +235,43 @@
Режимы переключаются при помощи датчика, который можно задать либо аргументом командной строки Режимы переключаются при помощи датчика, который можно задать либо аргументом командной строки
\b --prefix-exchange-mode-id либо в конф. файле параметром \b exchangeModeID="". Константы определяющие режимы объявлены в MBTCPMultiMaster::ExchangeMode. \b --prefix-exchange-mode-id либо в конф. файле параметром \b exchangeModeID="". Константы определяющие режимы объявлены в MBTCPMultiMaster::ExchangeMode.
\section sec_MBTCPM_CheckConnection Проверка соединения
Для контроля состояния связи по "резервным" каналам создаётся специальный поток (check_thread), в котором
происходит периодическая проверка связи по всем "пассивным"(резервным) в данный момент каналам. Это используется
как для общей диагностики в системе, так и при выборе на какой канал переключаться в случае пропажи связи в основном канале.
Т.е. будет выбран ближайший приоритетный канал у которого выставлен признак что есть связь.
Период проверки связи по "резервным" каналам задаётся при помощи --prefix-checktime или параметром checktime="" в конфигурационном файле.
В MBTCPMultiMaster реализовано два механизма проверки связи.
- По умолчанию используется простая установка соединения и тут же его разрыв. Т.е. данные никакие не посылаются,
но проверяется что host и port доступны для подключения.
- Второй способ: это проверка соединения с посылкой modbus-запроса. Для этого имеется два способа
указать адрес устройства, регистр и функция опроса для проверки.
Либо в секции <GateList> для каждого канала можно указать:
- адрес устройства \b checkAddr=""
- функцию проверки \b checkFunc="" - функция может быть только [01,02,03,04] (т.е. функции чтения).
- регистр \b checkReg
Либо в командной строке \b задать параметры --prefix-check-addr, --prefix-check-func, --prefix-check-reg,
которые будут одинаковыми для \b ВСЕХ \b КАНАЛОВ.
Помимо этого если указать в командной строке аргумент --prefix-check-init-from-regmap, то для тестирования
соединения будет взят первый попавшийся регистр из списка обмена.
\warning Способ проверки при помощи "modbus-запроса" имеет ряд проблем: Если фактически производится
обмен с несколькими устройствами (несколько mbaddr) через TCP-шлюз, то может быть "ложное" срабатвание,
т.к. фактически состояние канала будет определяться только под связи с каким-то одним конкретным устройством.
И получается, что если обмен ведётся например с тремя устройствами, но
проверка канала происходит только по связи с первым, то если оно перестанет отвечать, это будет считаться
сбоем всего канала и этот канал будет исключён из обмена (!). Если ведётся обмен только с одним устройством,
такой проблеммы не возникает.
Но к плюсам данного способа проверки связи ("modbus-запросом") является то, что соедиенение поддерживается
постоянным, в отличие от "первого способа" при котором оно создаётся и сразу рвётся и если проверка
настроена достаточно часто ( < TIME_WAIT для сокетов), то при длительной работе могут закончится дескрипторы
на создание сокетов.
*/ */
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
/*! /*!
\par Реализация Modbus TCP Multi Master для обмена с многими ModbusRTU устройствами \par Реализация Modbus TCP MultiMaster для обмена с многими ModbusRTU устройствами
через один modbus tcp шлюз, доступный по нескольким ip-адресам. через один modbus tcp шлюз, доступный по нескольким ip-адресам.
\par Чтобы не зависеть от таймаутов TCP соединений, которые могут неопределённо зависать \par Чтобы не зависеть от таймаутов TCP соединений, которые могут неопределённо зависать
...@@ -263,6 +303,7 @@ class MBTCPMultiMaster: ...@@ -263,6 +303,7 @@ class MBTCPMultiMaster:
virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override; virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override;
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool deactivateObject() override; virtual bool deactivateObject() override;
void initCheckConnectionParameters();
void poll_thread(); void poll_thread();
void check_thread(); void check_thread();
...@@ -288,6 +329,11 @@ class MBTCPMultiMaster: ...@@ -288,6 +329,11 @@ class MBTCPMultiMaster:
std::shared_ptr<ModbusTCPMaster> mbtcp; std::shared_ptr<ModbusTCPMaster> mbtcp;
int priority; int priority;
// параметры для проверки соединения..
ModbusRTU::SlaveFunctionCode checkFunc = { ModbusRTU::fnUnknown };
ModbusRTU::ModbusAddr checkAddr = { 0x00 };
ModbusRTU::ModbusData checkReg = { 0 };
bool respond; bool respond;
UniSetTypes::ObjectId respond_id; UniSetTypes::ObjectId respond_id;
IOController::IOStateList::iterator respond_it; IOController::IOStateList::iterator respond_it;
...@@ -297,18 +343,14 @@ class MBTCPMultiMaster: ...@@ -297,18 +343,14 @@ class MBTCPMultiMaster:
DelayTimer respondDelay; DelayTimer respondDelay;
timeout_t channel_timeout = { 0 }; timeout_t channel_timeout = { 0 };
inline bool operator < ( const MBSlaveInfo& mbs ) const inline bool operator < ( const MBSlaveInfo& mbs ) const noexcept
{ {
return priority < mbs.priority; return priority < mbs.priority;
} }
bool init( std::shared_ptr<DebugStream>& mblog ); bool init( std::shared_ptr<DebugStream>& mblog );
bool check() const; bool check();
inline void setUse( bool st ) void setUse( bool st );
{
respond_init = !( st && !use );
use = st;
}
timeout_t recv_timeout; timeout_t recv_timeout;
timeout_t aftersend_pause; timeout_t aftersend_pause;
...@@ -323,9 +365,11 @@ class MBTCPMultiMaster: ...@@ -323,9 +365,11 @@ class MBTCPMultiMaster:
PassiveTimer ptIgnoreTimeout; PassiveTimer ptIgnoreTimeout;
const std::string getShortInfo() const; const std::string getShortInfo() const;
std::mutex mutInit;
}; };
typedef std::list<MBSlaveInfo> MBGateList; typedef std::list<std::shared_ptr<MBSlaveInfo>> MBGateList;
MBGateList mblist; MBGateList mblist;
MBGateList::reverse_iterator mbi; MBGateList::reverse_iterator mbi;
......
...@@ -4,7 +4,7 @@ MBPARAM= ...@@ -4,7 +4,7 @@ MBPARAM=
for N in `seq 1 100`; do for N in `seq 1 100`; do
MBPARAM="$MBPARAM --mbtcp${N}-name MBTCP${N} --mbtcp${N}-confnode MBPerfTestMaster --mbtcp${N}-filter-field mbperf MBPARAM="$MBPARAM --mbtcp${N}-name MBTCP${N} --mbtcp${N}-confnode MBPerfTestMaster --mbtcp${N}-filter-field mbperf
--mbtcp${N}-filter-value $N --mbtcp${N}-persistent-connection 1 --mbtcp${N}-log-add-levels crit,warn" --mbtcp${N}-filter-value $N --mbtcp${N}-persistent-connection 1 --mbtcp${N}-check-init-from-regmap --mbtcp${N}-log-add-levels warn,crit"
done done
#echo "$MBPARAM" #echo "$MBPARAM"
......
...@@ -14,6 +14,10 @@ ...@@ -14,6 +14,10 @@
--mbtcp-log-add-levels level4,warn,crit \ --mbtcp-log-add-levels level4,warn,crit \
--mbtcp-persistent-connection 1 \ --mbtcp-persistent-connection 1 \
--mbtcp-run-logserver \ --mbtcp-run-logserver \
--mbtcpX-check-init-from-regmap \
--mbtcpX-check-addr 1 \
--mbtcpX-check-reg 66 \
--mbtcpX-check-func 1 \
$* $*
#--dlog-add-levels info,crit,warn,level4,level3,level9 \ #--dlog-add-levels info,crit,warn,level4,level3,level9 \
......
...@@ -124,6 +124,47 @@ TEST_CASE("MBTCPMaster: reconnect", "[modbus][mbmaster][mbtcpmaster]") ...@@ -124,6 +124,47 @@ TEST_CASE("MBTCPMaster: reconnect", "[modbus][mbmaster][mbtcpmaster]")
REQUIRE_FALSE(mb.isConnection()); REQUIRE_FALSE(mb.isConnection());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("MBTCPMaster: forceDisconnect", "[modbus][mbmaster][mbtcpmaster][forceDisconnect]")
{
InitTest();
ModbusTCPMaster mb;
mb.setTimeout(500);
for( size_t i=0; i<1000; i++ )
{
// подключение к несуществующему адресу
REQUIRE_FALSE(mb.connect(iaddr, 2048));
try
{
mb.read03(slaveADDR,10,1);
}
catch(...){}
REQUIRE_FALSE(mb.isConnection());
mb.forceDisconnect();
}
}
// -----------------------------------------------------------------------------
TEST_CASE("MBTCPMaster: disconnect", "[modbus][mbmaster][mbtcpmaster][disconnect]")
{
InitTest();
ModbusTCPMaster mb;
mb.setTimeout(500);
mb.setForceDisconnect(true);
for( size_t i=0; i<1000; i++ )
{
// подключение к несуществующему адресу
REQUIRE_FALSE(mb.connect(iaddr, 2048));
try
{
mb.read03(slaveADDR,10,1);
}
catch(...){}
REQUIRE_FALSE(mb.isConnection());
mb.disconnect();
}
}
// -----------------------------------------------------------------------------
TEST_CASE("MBTCPMaster: 0x01 (read coil status)", "[modbus][0x01][mbmaster][mbtcpmaster]") TEST_CASE("MBTCPMaster: 0x01 (read coil status)", "[modbus][0x01][mbmaster][mbtcpmaster]")
{ {
InitTest(); InitTest();
......
...@@ -337,7 +337,6 @@ class MBSlave: ...@@ -337,7 +337,6 @@ class MBSlave:
VTypes::VType vtype; /*!< type of value */ VTypes::VType vtype; /*!< type of value */
size_t wnum; /*!< номер слова (для типов с размеров больше 2х байт */ size_t wnum; /*!< номер слова (для типов с размеров больше 2х байт */
size_t nbyte; /*!< номер байта, который надо "сохранить" из "пришедщего в запросе" слова. [1-2] */ size_t nbyte; /*!< номер байта, который надо "сохранить" из "пришедщего в запросе" слова. [1-2] */
bool rawdata; /*!< флаг, что в SM просто сохраняются 4-байта (актуально для типа F4)*/
std::shared_ptr<BitRegProperty> bitreg; /*!< указатель, как признак является ли данный регистр "сборным" из битовых */ std::shared_ptr<BitRegProperty> bitreg; /*!< указатель, как признак является ли данный регистр "сборным" из битовых */
ModbusRTU::RegID regID; ModbusRTU::RegID regID;
...@@ -347,7 +346,6 @@ class MBSlave: ...@@ -347,7 +346,6 @@ class MBSlave:
vtype(VTypes::vtUnknown), vtype(VTypes::vtUnknown),
wnum(0), wnum(0),
nbyte(0), nbyte(0),
rawdata(false),
regID(0) regID(0)
{} {}
......
...@@ -54,6 +54,17 @@ RRDServer::RRDServer(UniSetTypes::ObjectId objId, xmlNode* cnode, UniSetTypes::O ...@@ -54,6 +54,17 @@ RRDServer::RRDServer(UniSetTypes::ObjectId objId, xmlNode* cnode, UniSetTypes::O
for( ; it1.getCurrent(); it1++, ++tmID ) for( ; it1.getCurrent(); it1++, ++tmID )
initRRD(it1, tmID); initRRD(it1, tmID);
if( smTestID == DefaultObjectId && !rrdlist.empty() )
{
// берём первый датчик из списка
const auto& lst = rrdlist.begin()->dslist;
if( !lst.empty() )
{
const auto& dsi = *(lst.begin());
smTestID = dsi->sid;
}
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
RRDServer::~RRDServer() RRDServer::~RRDServer()
...@@ -268,6 +279,8 @@ void RRDServer::help_print( int argc, const char* const* argv ) ...@@ -268,6 +279,8 @@ void RRDServer::help_print( int argc, const char* const* argv )
cout << " set-levels ... " << endl; cout << " set-levels ... " << endl;
cout << " logfile filanme " << endl; cout << " logfile filanme " << endl;
cout << " no-debug " << endl; cout << " no-debug " << endl;
cout << " Base oprtions: " << endl;
// cout << UObject_SK::help() << endl;
cout << " LogServer: " << endl; cout << " LogServer: " << endl;
cout << "--prefix-run-logserver - run logserver. Default: localhost:id" << endl; cout << "--prefix-run-logserver - run logserver. Default: localhost:id" << endl;
cout << "--prefix-logserver-host ip - listen ip. Default: localhost" << endl; cout << "--prefix-logserver-host ip - listen ip. Default: localhost" << endl;
...@@ -315,6 +328,9 @@ void RRDServer::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -315,6 +328,9 @@ void RRDServer::askSensors( UniversalIO::UIOCommand cmd )
{ {
UObject_SK::askSensors(cmd); UObject_SK::askSensors(cmd);
// прежде чем заказывать датчики, надо убедиться что SM доступна
waitSM(smReadyTimeout);
for( auto& it : rrdlist ) for( auto& it : rrdlist )
{ {
for( auto& s : it.dsmap ) for( auto& s : it.dsmap )
......
...@@ -69,8 +69,6 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std: ...@@ -69,8 +69,6 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std:
msecPulsar(0), msecPulsar(0),
confnode(0) confnode(0)
{ {
mutex_start.setName(myname + "_mutex_start");
auto conf = uniset_conf(); auto conf = uniset_conf();
string cname(confname); string cname(confname);
...@@ -155,7 +153,7 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std: ...@@ -155,7 +153,7 @@ SharedMemory::SharedMemory( ObjectId id, const std::string& datafile, const std:
evntPause = conf->getArgPInt("--e-startup-pause", 5000); evntPause = conf->getArgPInt("--e-startup-pause", 5000);
activateTimeout = conf->getArgPInt("--activate-timeout", 30000); activateTimeout = conf->getArgPInt("--activate-timeout", 60000);
sidPulsar = DefaultObjectId; sidPulsar = DefaultObjectId;
string p = conf->getArgParam("--pulsar-id", it.getProp("pulsar_id")); string p = conf->getArgParam("--pulsar-id", it.getProp("pulsar_id"));
...@@ -197,17 +195,21 @@ SharedMemory::~SharedMemory() ...@@ -197,17 +195,21 @@ SharedMemory::~SharedMemory()
void SharedMemory::timerInfo( const TimerMessage* tm ) void SharedMemory::timerInfo( const TimerMessage* tm )
{ {
if( tm->id == tmHeartBeatCheck ) if( tm->id == tmHeartBeatCheck )
{
checkHeartBeat(); checkHeartBeat();
}
else if( tm->id == tmEvent ) else if( tm->id == tmEvent )
{ {
workready = 1; workready = true;
// рассылаем уведомление, о том, чтобы стартанули // рассылаем уведомление, о том, чтобы стартанули
SystemMessage sm1(SystemMessage::WatchDog); SystemMessage sm1(SystemMessage::WatchDog);
sendEvent(sm1); sendEvent(sm1);
askTimer(tm->id, 0); askTimer(tm->id, 0);
} }
else if( tm->id == tmHistory ) else if( tm->id == tmHistory )
{
saveToHistory(); saveToHistory();
}
else if( tm->id == tmPulsar ) else if( tm->id == tmPulsar )
{ {
if( sidPulsar != DefaultObjectId ) if( sidPulsar != DefaultObjectId )
...@@ -241,11 +243,14 @@ void SharedMemory::sysCommand( const SystemMessage* sm ) ...@@ -241,11 +243,14 @@ void SharedMemory::sysCommand( const SystemMessage* sm )
} }
if( !activated ) if( !activated )
smcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl; {
smcrit << myname << "(sysCommand): Don`t activate! TERMINATE.." << endl;
std::terminate();
}
// подождать пока пройдёт инициализация // подождать пока пройдёт инициализация
// см. activateObject() // см. activateObject()
UniSetTypes::uniset_rwmutex_rlock l(mutex_start); std::unique_lock<std::mutex> lock(mutexStart);
askTimer(tmHeartBeatCheck, heartbeatCheckTime); askTimer(tmHeartBeatCheck, heartbeatCheckTime);
askTimer(tmEvent, evntPause, 1); askTimer(tmEvent, evntPause, 1);
...@@ -294,7 +299,7 @@ bool SharedMemory::activateObject() ...@@ -294,7 +299,7 @@ bool SharedMemory::activateObject()
{ {
activated = false; activated = false;
UniSetTypes::uniset_rwmutex_wrlock l(mutex_start); std::unique_lock<std::mutex> lock(mutexStart);
res = IONotifyController::activateObject(); res = IONotifyController::activateObject();
// инициализируем указатели // инициализируем указатели
...@@ -328,6 +333,7 @@ bool SharedMemory::activateObject() ...@@ -328,6 +333,7 @@ bool SharedMemory::activateObject()
} }
cout << myname << ": ********** activate: " << pt.getCurrent() << " msec " << endl; cout << myname << ": ********** activate: " << pt.getCurrent() << " msec " << endl;
sminfo << myname << ": ********** activate: " << pt.getCurrent() << " msec " << endl;
return res; return res;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
...@@ -201,7 +201,7 @@ ...@@ -201,7 +201,7 @@
<item default="1" id="104104" iotype="DI" name="_41_04_S"> <item default="1" id="104104" iotype="DI" name="_41_04_S">
<MessagesList> <MessagesList>
<msg mtype="1" text="КСЭС: отключился ввод\вывод" value="0"/> <msg mtype="1" text="КСЭС: отключился ввод/вывод" value="0"/>
</MessagesList> </MessagesList>
</item> </item>
\endcode \endcode
...@@ -417,7 +417,7 @@ class SharedMemory: ...@@ -417,7 +417,7 @@ class SharedMemory:
void buildEventList( xmlNode* cnode ); void buildEventList( xmlNode* cnode );
void readEventList( const std::string& oname ); void readEventList( const std::string& oname );
UniSetTypes::uniset_rwmutex mutex_start; std::mutex mutexStart;
class HeartBeatInfo class HeartBeatInfo
{ {
......
...@@ -99,9 +99,6 @@ int main( int argc, const char** argv ) ...@@ -99,9 +99,6 @@ int main( int argc, const char** argv )
ThreadCreator<IOControl>* io_thr = new ThreadCreator<IOControl>(ic.get(), &IOControl::execute); ThreadCreator<IOControl>* io_thr = new ThreadCreator<IOControl>(ic.get(), &IOControl::execute);
if( io_thr == NULL )
return 1;
act->add(ic); act->add(ic);
lst_iothr.push_back( io_thr ); lst_iothr.push_back( io_thr );
} }
......
...@@ -39,12 +39,12 @@ UNetSender::UNetSender(const std::string& _host, const int _port, const std::sha ...@@ -39,12 +39,12 @@ UNetSender::UNetSender(const std::string& _host, const int _port, const std::sha
sendpause(150), sendpause(150),
packsendpause(5), packsendpause(5),
activated(false), activated(false),
items(100),
packetnum(1), packetnum(1),
lastcrc(0), lastcrc(0),
maxAData(maxACount), maxAData(maxACount),
maxDData(maxDCount) maxDData(maxDCount)
{ {
items.reserve(100);
{ {
ostringstream s; ostringstream s;
......
...@@ -77,8 +77,8 @@ class Calibration ...@@ -77,8 +77,8 @@ class Calibration
{ {
public: public:
Calibration(); Calibration();
Calibration( const std::string& name, const std::string& confile = "calibration.xml" ); Calibration( const std::string& name, const std::string& confile = "calibration.xml", size_t reserv=50 );
Calibration( xmlNode* node ); Calibration( xmlNode* node, size_t reserv=50 );
~Calibration(); ~Calibration();
/*! Тип для хранения значения */ /*! Тип для хранения значения */
...@@ -96,26 +96,26 @@ class Calibration ...@@ -96,26 +96,26 @@ class Calibration
\param crop_raw - обрезать переданное значение по крайним точкам \param crop_raw - обрезать переданное значение по крайним точкам
\return Возвращает калиброванное или outOfRange \return Возвращает калиброванное или outOfRange
*/ */
long getValue( long raw, bool crop_raw = false ); long getValue( const long raw, bool crop_raw = false );
/*! Возвращает минимальное значение 'x' встретившееся в диаграмме */ /*! Возвращает минимальное значение 'x' встретившееся в диаграмме */
inline long getMinValue() inline long getMinValue() const noexcept
{ {
return minVal; return minVal;
} }
/*! Возвращает максимальное значение 'x' втретившееся в диаграмме */ /*! Возвращает максимальное значение 'x' втретившееся в диаграмме */
inline long getMaxValue() inline long getMaxValue() const noexcept
{ {
return maxVal; return maxVal;
} }
/*! Возвращает крайнее левое значение 'x' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */ /*! Возвращает крайнее левое значение 'x' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */
inline long getLeftValue() inline long getLeftValue() const noexcept
{ {
return leftVal; return leftVal;
} }
/*! Возвращает крайнее правое значение 'x' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */ /*! Возвращает крайнее правое значение 'x' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */
inline long getRightValue() inline long getRightValue() const noexcept
{ {
return rightVal; return rightVal;
} }
...@@ -127,26 +127,26 @@ class Calibration ...@@ -127,26 +127,26 @@ class Calibration
Если range=false, то может быть возвращено значение outOfRange. Если range=false, то может быть возвращено значение outOfRange.
*/ */
long getRawValue( long cal, bool range = false ); long getRawValue( const long cal, bool range = false );
/*! Возвращает минимальное значение 'y' встретившееся в диаграмме */ /*! Возвращает минимальное значение 'y' встретившееся в диаграмме */
inline long getMinRaw() inline long getMinRaw() const noexcept
{ {
return minRaw; return minRaw;
} }
/*! Возвращает максимальное значение 'y' встретившееся в диаграмме */ /*! Возвращает максимальное значение 'y' встретившееся в диаграмме */
inline long getMaxRaw() inline long getMaxRaw() const noexcept
{ {
return maxRaw; return maxRaw;
} }
/*! Возвращает крайнее левое значение 'y' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */ /*! Возвращает крайнее левое значение 'y' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */
inline long getLeftRaw() inline long getLeftRaw() const noexcept
{ {
return leftRaw; return leftRaw;
} }
/*! Возвращает крайнее правое значение 'y' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */ /*! Возвращает крайнее правое значение 'y' встретившееся в диаграмме (ПОСЛЕ СОРТИРОВКИ ПО ВОЗРАСТАНИЮ 'x'!) */
inline long getRightRaw() inline long getRightRaw() const noexcept
{ {
return rightRaw; return rightRaw;
} }
...@@ -166,14 +166,15 @@ class Calibration ...@@ -166,14 +166,15 @@ class Calibration
return lround(val); return lround(val);
} }
void setCacheSize( unsigned int sz ); void setCacheSize( size_t sz );
inline unsigned int getCacheSize()
inline size_t getCacheSize() const
{ {
return cache.size(); return cache.size();
} }
void setCacheResortCycle( unsigned int n ); void setCacheResortCycle( size_t n );
inline unsigned int getCacheResotrCycle() inline size_t getCacheResotrCycle() const noexcept
{ {
return numCacheResort; return numCacheResort;
} }
...@@ -204,56 +205,56 @@ class Calibration ...@@ -204,56 +205,56 @@ class Calibration
class Part class Part
{ {
public: public:
Part(); Part() noexcept;
Part( const Point& pleft, const Point& pright ); Part( const Point& pleft, const Point& pright ) noexcept;
~Part() {}; ~Part() {};
/*! находится ли точка на данном участке */ /*! находится ли точка на данном участке */
bool check( const Point& p ) const; bool check( const Point& p ) const noexcept;
/*! находится ли точка на данном участке по X */ /*! находится ли точка на данном участке по X */
bool checkX( const TypeOfValue& x ) const; bool checkX( const TypeOfValue& x ) const noexcept;
/*! находится ли точка на данном участке по Y */ /*! находится ли точка на данном участке по Y */
bool checkY( const TypeOfValue& y ) const; bool checkY( const TypeOfValue& y ) const noexcept;
// функции могут вернуть OutOfRange // функции могут вернуть OutOfRange
TypeOfValue getY( const TypeOfValue& x ) const; /*!< получить значение Y */ TypeOfValue getY( const TypeOfValue& x ) const noexcept; /*!< получить значение Y */
TypeOfValue getX( const TypeOfValue& y ) const; /*!< получить значение X */ TypeOfValue getX( const TypeOfValue& y ) const noexcept; /*!< получить значение X */
TypeOfValue calcY( const TypeOfValue& x ) const; /*!< расчитать значение для x */ TypeOfValue calcY( const TypeOfValue& x ) const noexcept; /*!< расчитать значение для x */
TypeOfValue calcX( const TypeOfValue& y ) const; /*!< расчитать значение для y */ TypeOfValue calcX( const TypeOfValue& y ) const noexcept; /*!< расчитать значение для y */
inline bool operator < ( const Part& p ) const inline bool operator < ( const Part& p ) const noexcept
{ {
return (p_right < p.p_right); return (p_right < p.p_right);
} }
inline Point leftPoint() const inline Point leftPoint() const noexcept
{ {
return p_left; return p_left;
} }
inline Point rightPoint() const inline Point rightPoint() const noexcept
{ {
return p_right; return p_right;
} }
inline TypeOfValue getK() const inline TypeOfValue getK() const noexcept
{ {
return k; /*!< получить коэффициент наклона */ return k; /*!< получить коэффициент наклона */
} }
inline TypeOfValue left_x() const inline TypeOfValue left_x() const noexcept
{ {
return p_left.x; return p_left.x;
} }
inline TypeOfValue left_y() const inline TypeOfValue left_y() const noexcept
{ {
return p_left.y; return p_left.y;
} }
inline TypeOfValue right_x() const inline TypeOfValue right_x() const noexcept
{ {
return p_right.x; return p_right.x;
} }
inline TypeOfValue right_y() const inline TypeOfValue right_y() const noexcept
{ {
return p_right.y; return p_right.y;
} }
...@@ -283,19 +284,19 @@ class Calibration ...@@ -283,19 +284,19 @@ class Calibration
std::string myname; std::string myname;
// Cache // Cache
unsigned int szCache; size_t szCache;
struct CacheInfo struct CacheInfo
{ {
CacheInfo(): val(0), raw(outOfRange), cnt(0) {} CacheInfo() noexcept: val(0), raw(outOfRange), cnt(0) {}
CacheInfo( const long r, const long v ): val(v), raw(r), cnt(0) {} CacheInfo( const long r, const long v ) noexcept: val(v), raw(r), cnt(0) {}
long val; long val;
long raw; long raw;
unsigned long cnt; // счётчик обращений size_t cnt; // счётчик обращений
// сортируем в порядке убывания(!) обращений // сортируем в порядке убывания(!) обращений
// т.е. наиболее часто используемые (впереди) // т.е. наиболее часто используемые (впереди)
inline bool operator<( const CacheInfo& r ) const inline bool operator<( const CacheInfo& r ) const noexcept
{ {
if( r.raw == outOfRange ) if( r.raw == outOfRange )
return true; return true;
...@@ -310,8 +311,8 @@ class Calibration ...@@ -310,8 +311,8 @@ class Calibration
typedef std::deque<CacheInfo> ValueCache; typedef std::deque<CacheInfo> ValueCache;
ValueCache cache; ValueCache cache;
unsigned long numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша.. size_t numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша..
unsigned long numCallToCache; // текущий счётчик обращений к кэшу size_t numCallToCache; // текущий счётчик обращений к кэшу
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // Calibration_H_ #endif // Calibration_H_
......
...@@ -717,8 +717,8 @@ namespace MTR ...@@ -717,8 +717,8 @@ namespace MTR
return val; return val;
} }
unsigned short val; unsigned short val = { 0 };
float fval; float fval = { 0.0 };
}; };
std::ostream& operator<<(std::ostream& os, T16& t ); std::ostream& operator<<(std::ostream& os, T16& t );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -765,8 +765,8 @@ namespace MTR ...@@ -765,8 +765,8 @@ namespace MTR
return val; return val;
} }
signed short val; signed short val = { 0 };
float fval; float fval = { 0 };
}; };
std::ostream& operator<<(std::ostream& os, T17& t ); std::ostream& operator<<(std::ostream& os, T17& t );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2016-08-25+03:00 // generate timestamp: 2016-09-30+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef UObject_SK_H_ #ifndef UObject_SK_H_
#define UObject_SK_H_ #define UObject_SK_H_
...@@ -29,7 +29,7 @@ class UObject_SK: ...@@ -29,7 +29,7 @@ class UObject_SK:
public UniSetObject public UniSetObject
{ {
public: public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node = UniSetTypes::uniset_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();
...@@ -41,62 +41,56 @@ class UObject_SK: ...@@ -41,62 +41,56 @@ class UObject_SK:
virtual UniSetTypes::SimpleInfo* getInfo( CORBA::Long userparam = 0 ) override; virtual UniSetTypes::SimpleInfo* getInfo( CORBA::Long userparam = 0 ) override;
virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ); virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ) noexcept;
inline std::shared_ptr<DebugStream> log() inline std::shared_ptr<DebugStream> log() noexcept { return mylog; }
{ inline std::shared_ptr<LogAgregator> logAgregator() noexcept { return loga; }
return mylog;
}
inline std::shared_ptr<LogAgregator> logAgregator()
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ); void init_dlog( std::shared_ptr<DebugStream> d ) noexcept;
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
#ifndef myinfo #ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info() #define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif #endif
#ifndef mywarn #ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn() #define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif #endif
#ifndef mycrit #ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit() #define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif #endif
#ifndef mylog1 #ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1() #define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif #endif
#ifndef mylog2 #ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2() #define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif #endif
#ifndef mylog3 #ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3() #define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif #endif
#ifndef mylog4 #ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4() #define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif #endif
#ifndef mylog5 #ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5() #define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif #endif
#ifndef mylog6 #ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6() #define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif #endif
#ifndef mylog7 #ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7() #define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif #endif
#ifndef mylog8 #ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8() #define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif #endif
#ifndef mylog9 #ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9() #define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif #endif
#ifndef mylogany #ifndef mylogany
#define mylogany log()->any() #define mylogany log()->any()
#endif #endif
#ifndef vmonit #ifndef vmonit
#define vmonit( var ) vmon.add( #var, var ) #define vmonit( var ) vmon.add( #var, var )
#endif #endif
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
...@@ -113,21 +107,18 @@ class UObject_SK: ...@@ -113,21 +107,18 @@ class UObject_SK:
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string str( UniSetTypes::ObjectId id, bool showLinkName = true ) const; std::string str( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val /*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string strval( UniSetTypes::ObjectId id, bool showLinkName = true ) const; std::string strval( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод состояния внутренних переменных */ /*! Вывод состояния внутренних переменных */
inline std::string dumpVars() inline std::string dumpVars(){ return std::move(vmon.pretty_str()); }
{
return std::move(vmon.pretty_str());
}
// ------------------------------------------------------------ // ------------------------------------------------------------
std::string help(); std::string help() noexcept;
...@@ -152,21 +143,21 @@ class UObject_SK: ...@@ -152,21 +143,21 @@ class UObject_SK:
// ---- end of protected variables ---- // ---- end of protected variables ----
virtual void callback() override; virtual void callback() noexcept override;
virtual void processingMessage( const UniSetTypes::VoidMessage* msg ) override; virtual void processingMessage( const UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) {}; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ){};
virtual void askSensors( UniversalIO::UIOCommand cmd ) {} virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override {} virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override {} virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool activateObject() override; virtual bool activateObject() override;
virtual std::string getMonitInfo() virtual std::string getMonitInfo(){ return ""; } /*!< пользовательская информация выводимая в getInfo() */
{
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step() {} virtual void step(){}
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const UniSetTypes::SystemMessage* sm );
virtual void testMode( bool state ); virtual void testMode( bool state );
void updateOutputs( bool force ); void updateOutputs( bool force );
...@@ -192,15 +183,9 @@ class UObject_SK: ...@@ -192,15 +183,9 @@ class UObject_SK:
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
{
return UniSetTypes::uniset_conf()->getIntProp(confnode, name);
}
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
{
return UniSetTypes::uniset_conf()->getProp(confnode, name);
}
timeout_t smReadyTimeout; /*!< время ожидания готовности SM */ timeout_t smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
...@@ -235,11 +220,9 @@ class UObject_SK: ...@@ -235,11 +220,9 @@ class UObject_SK:
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// ------------ private функции --------------- // ------------ private функции ---------------
void updatePreviousValues(); void updatePreviousValues() noexcept;
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSensorInfo( const UniSetTypes::SensorMessage* sm ); void preSensorInfo( const UniSetTypes::SensorMessage* sm );
void preTimerInfo( const UniSetTypes::TimerMessage* tm ); void preTimerInfo( const UniSetTypes::TimerMessage* tm );
void preSysCommand( const UniSetTypes::SystemMessage* sm );
void initFromSM(); void initFromSM();
void checkSensors(); void checkSensors();
// -------------------------------------------- // --------------------------------------------
......
...@@ -114,7 +114,7 @@ namespace VTypes ...@@ -114,7 +114,7 @@ namespace VTypes
// ------------------------------------------ // ------------------------------------------
// конструкторы на разные случаи... // конструкторы на разные случаи...
F2r() noexcept {} F2r() noexcept { raw_backorder.val = 0; }
F2r( const float& f ) noexcept: F2(f) F2r( const float& f ) noexcept: F2(f)
{ {
...@@ -383,7 +383,7 @@ namespace VTypes ...@@ -383,7 +383,7 @@ namespace VTypes
public I2 public I2
{ {
public: public:
I2r() noexcept {} I2r() noexcept { raw_backorder.val = 0; }
I2r( const int v ) noexcept: I2(v) I2r( const int v ) noexcept: I2(v)
{ {
...@@ -457,7 +457,7 @@ namespace VTypes ...@@ -457,7 +457,7 @@ namespace VTypes
public U2 public U2
{ {
public: public:
U2r() noexcept {} U2r() noexcept { raw_backorder.val = 0; }
U2r( int v ) noexcept: U2(v) U2r( int v ) noexcept: U2(v)
{ {
......
...@@ -29,23 +29,19 @@ using namespace UniSetTypes; ...@@ -29,23 +29,19 @@ using namespace UniSetTypes;
const Calibration::TypeOfValue Calibration::ValueOutOfRange = std::numeric_limits<Calibration::TypeOfValue>::max(); const Calibration::TypeOfValue Calibration::ValueOutOfRange = std::numeric_limits<Calibration::TypeOfValue>::max();
const long Calibration::outOfRange = std::numeric_limits<long>::max(); const long Calibration::outOfRange = std::numeric_limits<long>::max();
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::Part::Part(): Calibration::Part::Part() noexcept:
k(0) k(0)
{ {
} }
Calibration::Part::Part( const Point& pleft, const Point& pright ): Calibration::Part::Part( const Point& pleft, const Point& pright ) noexcept:
p_left(pleft), p_left(pleft),
p_right(pright), p_right(pright),
k(0) k(0)
{ {
if( p_right.x < p_left.x ) if( p_right.x < p_left.x )
{ std::swap(p_right,p_left);
Point t(p_right);
p_right = p_left;
p_left = t;
}
// вычисление коэффициента наклона (один раз в конструкторе) // вычисление коэффициента наклона (один раз в конструкторе)
// k = (y2-y1)/(x2-x1) // k = (y2-y1)/(x2-x1)
...@@ -55,29 +51,28 @@ Calibration::Part::Part( const Point& pleft, const Point& pright ): ...@@ -55,29 +51,28 @@ Calibration::Part::Part( const Point& pleft, const Point& pright ):
k = ( p_right.y - p_left.y ) / ( p_right.x - p_left.x ); k = ( p_right.y - p_left.y ) / ( p_right.x - p_left.x );
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool Calibration::Part::check( const Point& p ) const bool Calibration::Part::check( const Point& p ) const noexcept
{ {
return ( checkX(p.x) && checkY(p.y) ); return ( checkX(p.x) && checkY(p.y) );
} }
// ----------------------------------------------------------------------------
bool Calibration::Part::checkX( const TypeOfValue& x ) const bool Calibration::Part::checkX( const TypeOfValue& x ) const noexcept
{ {
if( x < p_left.x || x > p_right.x ) if( x < p_left.x || x > p_right.x )
return false; return false;
return true; return true;
} }
// ----------------------------------------------------------------------------
bool Calibration::Part::checkY( const TypeOfValue& y ) const bool Calibration::Part::checkY( const TypeOfValue& y ) const noexcept
{ {
if( y < p_left.y || y > p_right.y ) if( y < p_left.y || y > p_right.y )
return false; return false;
return true; return true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::TypeOfValue Calibration::Part::getY( const TypeOfValue& x ) const Calibration::TypeOfValue Calibration::Part::getY( const TypeOfValue& x ) const noexcept
{ {
if( !checkX(x) ) if( !checkX(x) )
return Calibration::ValueOutOfRange; return Calibration::ValueOutOfRange;
...@@ -91,7 +86,7 @@ Calibration::TypeOfValue Calibration::Part::getY( const TypeOfValue& x ) const ...@@ -91,7 +86,7 @@ Calibration::TypeOfValue Calibration::Part::getY( const TypeOfValue& x ) const
return calcY(x); return calcY(x);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::TypeOfValue Calibration::Part::getX( const TypeOfValue& y ) const Calibration::TypeOfValue Calibration::Part::getX( const TypeOfValue& y ) const noexcept
{ {
if( !checkY(y) ) if( !checkY(y) )
return Calibration::ValueOutOfRange; return Calibration::ValueOutOfRange;
...@@ -105,13 +100,13 @@ Calibration::TypeOfValue Calibration::Part::getX( const TypeOfValue& y ) const ...@@ -105,13 +100,13 @@ Calibration::TypeOfValue Calibration::Part::getX( const TypeOfValue& y ) const
return calcX(y); return calcX(y);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::TypeOfValue Calibration::Part::calcY( const TypeOfValue& x ) const Calibration::TypeOfValue Calibration::Part::calcY( const TypeOfValue& x ) const noexcept
{ {
// y = y0 + kx // y = y0 + kx
return k * (x - p_left.x) + p_left.y; return k * (x - p_left.x) + p_left.y;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::TypeOfValue Calibration::Part::calcX( const TypeOfValue& y ) const Calibration::TypeOfValue Calibration::Part::calcX( const TypeOfValue& y ) const noexcept
{ {
// x = (y - y0) / k // x = (y - y0) / k
if( k == 0 ) if( k == 0 )
...@@ -123,7 +118,6 @@ Calibration::TypeOfValue Calibration::Part::calcX( const TypeOfValue& y ) const ...@@ -123,7 +118,6 @@ Calibration::TypeOfValue Calibration::Part::calcX( const TypeOfValue& y ) const
Calibration::Calibration(): Calibration::Calibration():
minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0), minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0),
pvec(50),
myname(""), myname(""),
szCache(5), szCache(5),
numCacheResort(20), numCacheResort(20),
...@@ -134,25 +128,26 @@ Calibration::Calibration(): ...@@ -134,25 +128,26 @@ Calibration::Calibration():
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::Calibration( const string& name, const string& confile ): Calibration::Calibration( const string& name, const string& confile, size_t reserv ):
minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0), minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0),
pvec(50),
myname(name), myname(name),
szCache(5), szCache(5),
numCacheResort(20), numCacheResort(20),
numCallToCache(5) numCallToCache(5)
{ {
pvec.reserve(reserv);
cache.assign(szCache, CacheInfo()); cache.assign(szCache, CacheInfo());
build(name, confile, 0); build(name, confile, 0);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
Calibration::Calibration( xmlNode* node ): Calibration::Calibration(xmlNode* node , size_t reserv ):
minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0), pvec(100), minRaw(0), maxRaw(0), minVal(0), maxVal(0), rightVal(0), leftVal(0), rightRaw(0), leftRaw(0),
szCache(5), szCache(5),
numCacheResort(20), numCacheResort(20),
numCallToCache(5) numCallToCache(5)
{ {
pvec.reserve(reserv);
cache.assign(szCache, CacheInfo()); cache.assign(szCache, CacheInfo());
UniXML::iterator it(node); UniXML::iterator it(node);
myname = it.getProp("name"); myname = it.getProp("name");
...@@ -199,14 +194,13 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo ...@@ -199,14 +194,13 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo
} }
bool prev = false; bool prev = false;
Point prev_point(0, 0); Point prev_point;
unsigned int i = 0;
for(; it; it.goNext()) for(; it; it++ )
{ {
Point p(prev_point); Point p(prev_point);
p.x = atof(it.getProp("x").c_str()); p.x = std::atof(it.getProp("x").c_str());
p.y = atof(it.getProp("y").c_str()); p.y = std::atof(it.getProp("y").c_str());
if( p.x == 0 || p.y == 0 ) if( p.x == 0 || p.y == 0 )
{ {
...@@ -225,36 +219,28 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo ...@@ -225,36 +219,28 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo
minVal = p.y; minVal = p.y;
if( prev ) if( prev )
{ pvec.emplace_back(prev_point, p);
Part pt(prev_point, p);
pvec[i++] = pt;
if( i >= pvec.size() )
pvec.resize(pvec.size() + 20);
}
else else
prev = true; prev = true;
prev_point = p; prev_point = p;
} }
pvec.resize(i); // приводим размер к фактическому.. pvec.shrink_to_fit();
std::sort(pvec.begin(), pvec.end()); std::sort(pvec.begin(), pvec.end());
if( !pvec.empty() )
{
auto beg = pvec.begin(); auto beg = pvec.begin();
auto end = pvec.end(); auto end = --pvec.end();
if( pvec.size() > 0 )
{
leftRaw = beg->left_x(); leftRaw = beg->left_x();
leftVal = beg->left_y(); leftVal = beg->left_y();
--end;
rightRaw = end->right_x(); rightRaw = end->right_x();
rightVal = end->right_y(); rightVal = end->right_y();
} }
} }
catch( const Exception& ex ) catch( const UniSetTypes::Exception& ex )
{ {
dcrit << myname << "(Calibration::build): Failed open " << confile << endl; dcrit << myname << "(Calibration::build): Failed open " << confile << endl;
throw; throw;
...@@ -262,7 +248,7 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo ...@@ -262,7 +248,7 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// рекурсивная функция поиска методом "половинного деления" // рекурсивная функция поиска методом "половинного деления"
static Calibration::PartsVec::iterator find_range( long raw, Calibration::PartsVec::iterator beg, static Calibration::PartsVec::iterator find_range( const long raw, Calibration::PartsVec::iterator beg,
Calibration::PartsVec::iterator end ) Calibration::PartsVec::iterator end )
{ {
if( beg->checkX(raw) ) if( beg->checkX(raw) )
...@@ -282,7 +268,7 @@ static Calibration::PartsVec::iterator find_range( long raw, Calibration::PartsV ...@@ -282,7 +268,7 @@ static Calibration::PartsVec::iterator find_range( long raw, Calibration::PartsV
return it; return it;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
long Calibration::getValue( long raw, bool crop_raw ) long Calibration::getValue( const long raw, bool crop_raw )
{ {
// если x левее первого отрезка то берём первую точку... // если x левее первого отрезка то берём первую точку...
if( raw < leftRaw ) if( raw < leftRaw )
...@@ -312,7 +298,7 @@ long Calibration::getValue( long raw, bool crop_raw ) ...@@ -312,7 +298,7 @@ long Calibration::getValue( long raw, bool crop_raw )
} }
} }
auto fit = find_range(raw, pvec.begin(), pvec.end()); auto fit = find_range(raw, pvec.begin(), --pvec.end() );
if( fit == pvec.end() ) if( fit == pvec.end() )
{ {
...@@ -338,13 +324,13 @@ long Calibration::getValue( long raw, bool crop_raw ) ...@@ -338,13 +324,13 @@ long Calibration::getValue( long raw, bool crop_raw )
return outOfRange; return outOfRange;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void Calibration::setCacheResortCycle( unsigned int n ) void Calibration::setCacheResortCycle( size_t n )
{ {
numCacheResort = n; numCacheResort = n;
numCallToCache = n; numCallToCache = n;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void Calibration::setCacheSize( unsigned int sz ) void Calibration::setCacheSize( size_t sz )
{ {
sort(cache.begin(), cache.end()); // в порядке уменьшения обращений (см. CacheInfo::operator< ) sort(cache.begin(), cache.end()); // в порядке уменьшения обращений (см. CacheInfo::operator< )
cache.resize(sz); cache.resize(sz);
...@@ -358,7 +344,7 @@ void Calibration::insertToCache( const long raw, const long val ) ...@@ -358,7 +344,7 @@ void Calibration::insertToCache( const long raw, const long val )
sort(cache.begin(), cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< ) sort(cache.begin(), cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
long Calibration::getRawValue( long cal, bool range ) long Calibration::getRawValue( const long cal, bool range )
{ {
for( auto& it : pvec ) for( auto& it : pvec )
{ {
......
...@@ -33,7 +33,6 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq, ...@@ -33,7 +33,6 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
S(0), S(0),
tmr(UniSetTimer::WaitUpTime), tmr(UniSetTimer::WaitUpTime),
maxsize(bufsize), maxsize(bufsize),
mvec(bufsize),
mvec_sorted(false), mvec_sorted(false),
w(bufsize), w(bufsize),
lsparam(lsq), lsparam(lsq),
......
...@@ -192,7 +192,9 @@ bool IOBase::check_front( bool val ) ...@@ -192,7 +192,9 @@ bool IOBase::check_front( bool val )
void IOBase::processingAsAI( IOBase* it, long val, const std::shared_ptr<SMInterface>& shm, bool force ) void IOBase::processingAsAI( IOBase* it, long val, const std::shared_ptr<SMInterface>& shm, bool force )
{ {
if( it->stype == UniversalIO::DI || it->stype == UniversalIO::DO ) if( it->stype == UniversalIO::DI || it->stype == UniversalIO::DO )
val = (val ? 1.0 : 0.0); {
val = (val ? 1 : 0);
}
else else
{ {
// проверка на обрыв // проверка на обрыв
...@@ -270,7 +272,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, const std::shared_ptr<SMIn ...@@ -270,7 +272,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, const std::shared_ptr<SMIn
long val = lroundf(fval); long val = lroundf(fval);
if( it->stype == UniversalIO::DI || it->stype == UniversalIO::DO ) if( it->stype == UniversalIO::DI || it->stype == UniversalIO::DO )
val = (fval != 0 ? 1.0 : 0.0); val = (fval != 0 ? 1 : 0);
else else
{ {
if( it->rawdata ) if( it->rawdata )
......
...@@ -74,7 +74,7 @@ using namespace UniSetTypes; ...@@ -74,7 +74,7 @@ using namespace UniSetTypes;
{ \ { \
uwarn << "(" << __STRING(fname) << "): " << ex.err << endl; \ uwarn << "(" << __STRING(fname) << "): " << ex.err << endl; \
} \ } \
catch( const Exception& ex ) \ catch( const UniSetTypes::Exception& ex ) \
{ \ { \
uwarn << "(" << __STRING(fname) << "): " << ex << endl; \ uwarn << "(" << __STRING(fname) << "): " << ex << endl; \
} \ } \
......
...@@ -53,8 +53,8 @@ void TestProc::sysCommand( const UniSetTypes::SystemMessage* sm ) ...@@ -53,8 +53,8 @@ void TestProc::sysCommand( const UniSetTypes::SystemMessage* sm )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
string TestProc::getMonitInfo() string TestProc::getMonitInfo()
{ {
int* p = 0; // int* p = 0;
(*p) = 10; // (*p) = 10;
return ""; return "";
} }
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
#ifndef LogServer_H_ #ifndef LogServer_H_
#define LogServer_H_ #define LogServer_H_
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#include <list> #include <vector>
#include <string> #include <string>
#include <memory> #include <memory>
#include <unordered_map> #include <unordered_map>
...@@ -87,8 +87,8 @@ class LogServer: ...@@ -87,8 +87,8 @@ class LogServer:
{ {
public: public:
LogServer( std::shared_ptr<DebugStream> log ) noexcept; LogServer( std::shared_ptr<DebugStream> log );
LogServer( std::shared_ptr<LogAgregator> log ) noexcept; LogServer( std::shared_ptr<LogAgregator> log );
virtual ~LogServer() noexcept; virtual ~LogServer() noexcept;
inline void setCmdTimeout( timeout_t msec ) noexcept inline void setCmdTimeout( timeout_t msec ) noexcept
...@@ -113,6 +113,8 @@ class LogServer: ...@@ -113,6 +113,8 @@ class LogServer:
return isrunning; return isrunning;
} }
bool check( bool restart_if_fail = true );
void init( const std::string& prefix, xmlNode* cnode = 0 ); void init( const std::string& prefix, xmlNode* cnode = 0 );
static std::string help_print( const std::string& prefix ); static std::string help_print( const std::string& prefix );
...@@ -120,7 +122,7 @@ class LogServer: ...@@ -120,7 +122,7 @@ class LogServer:
std::string getShortInfo(); std::string getShortInfo();
protected: protected:
LogServer() noexcept; LogServer();
virtual void evprepare( const ev::loop_ref& loop ) override; virtual void evprepare( const ev::loop_ref& loop ) override;
virtual void evfinish( const ev::loop_ref& loop ) override; virtual void evfinish( const ev::loop_ref& loop ) override;
...@@ -136,16 +138,16 @@ class LogServer: ...@@ -136,16 +138,16 @@ class LogServer:
std::string onCommand( LogSession* s, LogServerTypes::Command cmd, const std::string& logname ); std::string onCommand( LogSession* s, LogServerTypes::Command cmd, const std::string& logname );
private: private:
typedef std::list< std::shared_ptr<LogSession> > SessionList;
SessionList slist;
size_t scount = { 0 };
UniSetTypes::uniset_rwmutex mutSList;
timeout_t timeout = { UniSetTimer::WaitUpTime }; timeout_t timeout = { UniSetTimer::WaitUpTime };
timeout_t cmdTimeout = { 2000 }; timeout_t cmdTimeout = { 2000 };
Debug::type sessLogLevel = { Debug::NONE }; Debug::type sessLogLevel = { Debug::NONE };
size_t sessMaxCount = { 10 }; size_t sessMaxCount = { 10 };
typedef std::vector< std::shared_ptr<LogSession> > SessionList;
SessionList slist;
UniSetTypes::uniset_rwmutex mutSList;
DebugStream mylog; DebugStream mylog;
ev::io io; ev::io io;
......
...@@ -77,6 +77,8 @@ class LogSession ...@@ -77,6 +77,8 @@ class LogSession
std::string getShortInfo() noexcept; std::string getShortInfo() noexcept;
std::string name() const noexcept;
protected: protected:
// LogSession( ost::TCPSocket& server ); // LogSession( ost::TCPSocket& server );
......
...@@ -180,8 +180,6 @@ class NCRestorer_XML: ...@@ -180,8 +180,6 @@ class NCRestorer_XML:
std::string s_filterField; std::string s_filterField;
std::string s_filterValue; std::string s_filterValue;
std::string c_filterField;
std::string c_filterValue;
std::string t_filterField; std::string t_filterField;
std::string t_filterValue; std::string t_filterValue;
......
...@@ -93,7 +93,7 @@ class ThreadCreator: ...@@ -93,7 +93,7 @@ class ThreadCreator:
typedef void(ThreadMaster::* Action)(void); typedef void(ThreadMaster::* Action)(void);
ThreadCreator( ThreadMaster* m, Action a ); ThreadCreator( ThreadMaster* m, Action a );
~ThreadCreator(); virtual ~ThreadCreator();
inline Poco::Thread::TID getTID() const inline Poco::Thread::TID getTID() const
{ {
......
...@@ -44,6 +44,7 @@ class UTCPStream: ...@@ -44,6 +44,7 @@ class UTCPStream:
bool isSetLinger() const; bool isSetLinger() const;
void forceDisconnect(); // disconnect() без ожидания (с отключением SO_LINGER) void forceDisconnect(); // disconnect() без ожидания (с отключением SO_LINGER)
void disconnect();
// -------------------------------------------------------------------- // --------------------------------------------------------------------
int getSocket() const; int getSocket() const;
......
...@@ -178,7 +178,7 @@ class ModbusClient ...@@ -178,7 +178,7 @@ class ModbusClient
/*! функция запрос-ответ */ /*! функция запрос-ответ */
virtual ModbusRTU::mbErrCode query( ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusMessage& msg, virtual ModbusRTU::mbErrCode query( ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusMessage& msg,
ModbusRTU::ModbusMessage& reply, timeout_t timeout ) = 0; ModbusRTU::ModbusMessage& qreply, timeout_t timeout ) = 0;
// ------------------------------------- // -------------------------------------
/*! посылка запроса */ /*! посылка запроса */
...@@ -191,11 +191,6 @@ class ModbusClient ...@@ -191,11 +191,6 @@ class ModbusClient
virtual ModbusRTU::mbErrCode recv_pdu( ModbusRTU::ModbusByte qfunc, virtual ModbusRTU::mbErrCode recv_pdu( ModbusRTU::ModbusByte qfunc,
ModbusRTU::ModbusMessage& rbuf, timeout_t timeout ); ModbusRTU::ModbusMessage& rbuf, timeout_t timeout );
ModbusRTU::ModbusMessage reply; /*!< буфер для приёма сообщений */
ModbusRTU::ModbusMessage qbuf; /*!< буфер для посылки сообщений */
timeout_t replyTimeOut_ms; /*!< таймаут на ожидание ответа */ timeout_t replyTimeOut_ms; /*!< таймаут на ожидание ответа */
timeout_t aftersend_msec; /*!< пауза после посылки запроса */ timeout_t aftersend_msec; /*!< пауза после посылки запроса */
timeout_t sleepPause_usec; /*!< пауза между попытками чтения символа из канала */ timeout_t sleepPause_usec; /*!< пауза между попытками чтения символа из канала */
...@@ -209,6 +204,9 @@ class ModbusClient ...@@ -209,6 +204,9 @@ class ModbusClient
PassiveTimer tmProcessing; PassiveTimer tmProcessing;
private: private:
ModbusRTU::ModbusMessage qreply; /*!< буфер для приёма сообщений */
ModbusRTU::ModbusMessage qbuf; /*!< буфер для посылки сообщений */
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // ModbusClient_H_ #endif // ModbusClient_H_
......
...@@ -150,6 +150,7 @@ namespace ModbusRTU ...@@ -150,6 +150,7 @@ namespace ModbusRTU
float dat2f( const ModbusData dat1, const ModbusData dat2 ); float dat2f( const ModbusData dat1, const ModbusData dat2 );
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool isWriteFunction( SlaveFunctionCode c ); bool isWriteFunction( SlaveFunctionCode c );
bool isReadFunction( SlaveFunctionCode c );
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! Заголовок сообщений */ /*! Заголовок сообщений */
struct ModbusHeader struct ModbusHeader
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
using namespace std; using namespace std;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
static UInterface* ui = 0; static UInterface* uInterface = 0;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void pyUInterface::uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException) void pyUInterface::uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException)
{ {
...@@ -37,7 +37,7 @@ void pyUInterface::uniset_init( int argc, char* argv[], const std::string& xmlfi ...@@ -37,7 +37,7 @@ void pyUInterface::uniset_init( int argc, char* argv[], const std::string& xmlfi
try try
{ {
UniSetTypes::uniset_init(argc, argv, xmlfile); UniSetTypes::uniset_init(argc, argv, xmlfile);
ui = new UInterface(); uInterface = new UInterface();
return; return;
} }
catch( UniSetTypes::Exception& ex ) catch( UniSetTypes::Exception& ex )
...@@ -54,7 +54,7 @@ long pyUInterface::getValue( long id )throw(UException) ...@@ -54,7 +54,7 @@ long pyUInterface::getValue( long id )throw(UException)
{ {
auto conf = UniSetTypes::uniset_conf(); auto conf = UniSetTypes::uniset_conf();
if( !conf || !ui ) if( !conf || !uInterface )
throw USysError(); throw USysError();
UniversalIO::IOType t = conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
...@@ -67,7 +67,7 @@ long pyUInterface::getValue( long id )throw(UException) ...@@ -67,7 +67,7 @@ long pyUInterface::getValue( long id )throw(UException)
case UniversalIO::DO: case UniversalIO::DO:
case UniversalIO::AI: case UniversalIO::AI:
case UniversalIO::AO: case UniversalIO::AO:
return ui->getValue(id); return uInterface->getValue(id);
break; break;
default: default:
...@@ -96,7 +96,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException) ...@@ -96,7 +96,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
{ {
auto conf = UniSetTypes::uniset_conf(); auto conf = UniSetTypes::uniset_conf();
if( !conf || !ui ) if( !conf || !uInterface )
throw USysError(); throw USysError();
UniversalIO::IOType t = conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
...@@ -109,7 +109,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException) ...@@ -109,7 +109,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
case UniversalIO::DO: case UniversalIO::DO:
case UniversalIO::AI: case UniversalIO::AI:
case UniversalIO::AO: case UniversalIO::AO:
ui->setValue(id, val, supplier); uInterface->setValue(id, val, supplier);
break; break;
default: default:
......
...@@ -60,10 +60,10 @@ throw(ModbusRTU::mbException) ...@@ -60,10 +60,10 @@ throw(ModbusRTU::mbException)
{ {
ReadCoilMessage msg(addr, start, count); ReadCoilMessage msg(addr, start, count);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ReadCoilRetMessage(reply); return ReadCoilRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -74,10 +74,10 @@ throw(ModbusRTU::mbException) ...@@ -74,10 +74,10 @@ throw(ModbusRTU::mbException)
{ {
ReadInputStatusMessage msg(addr, start, count); ReadInputStatusMessage msg(addr, start, count);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ReadInputStatusRetMessage(reply); return ReadInputStatusRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -90,10 +90,10 @@ throw(ModbusRTU::mbException) ...@@ -90,10 +90,10 @@ throw(ModbusRTU::mbException)
ReadOutputMessage msg(addr, start, count); ReadOutputMessage msg(addr, start, count);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ReadOutputRetMessage(reply); return ReadOutputRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -104,10 +104,10 @@ throw(ModbusRTU::mbException) ...@@ -104,10 +104,10 @@ throw(ModbusRTU::mbException)
{ {
ReadInputMessage msg(addr, start, count); ReadInputMessage msg(addr, start, count);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ReadInputRetMessage(reply); return ReadInputRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -119,10 +119,10 @@ throw(ModbusRTU::mbException) ...@@ -119,10 +119,10 @@ throw(ModbusRTU::mbException)
ForceSingleCoilMessage msg(addr, start, cmd); ForceSingleCoilMessage msg(addr, start, cmd);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ForceSingleCoilRetMessage(reply); return ForceSingleCoilRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -135,10 +135,10 @@ throw(ModbusRTU::mbException) ...@@ -135,10 +135,10 @@ throw(ModbusRTU::mbException)
WriteSingleOutputMessage msg(addr, start, data); WriteSingleOutputMessage msg(addr, start, data);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return WriteSingleOutputRetMessage(reply); return WriteSingleOutputRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -147,10 +147,10 @@ ForceCoilsRetMessage ModbusClient::write0F( ForceCoilsMessage& msg ) ...@@ -147,10 +147,10 @@ ForceCoilsRetMessage ModbusClient::write0F( ForceCoilsMessage& msg )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(msg.addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(msg.addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return ForceCoilsRetMessage(reply); return ForceCoilsRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -160,10 +160,10 @@ WriteOutputRetMessage ModbusClient::write10( WriteOutputMessage& msg ) ...@@ -160,10 +160,10 @@ WriteOutputRetMessage ModbusClient::write10( WriteOutputMessage& msg )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(msg.addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(msg.addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return WriteOutputRetMessage(reply); return WriteOutputRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -175,10 +175,10 @@ throw(ModbusRTU::mbException) ...@@ -175,10 +175,10 @@ throw(ModbusRTU::mbException)
{ {
DiagnosticMessage msg(addr, subfunc, dat); DiagnosticMessage msg(addr, subfunc, dat);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(msg.addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(msg.addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return DiagnosticRetMessage(reply); return DiagnosticRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -190,10 +190,10 @@ throw(ModbusRTU::mbException) ...@@ -190,10 +190,10 @@ throw(ModbusRTU::mbException)
{ {
MEIMessageRDI msg(addr, devID, objID); MEIMessageRDI msg(addr, devID, objID);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(msg.addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(msg.addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return MEIMessageRetRDI(reply); return MEIMessageRetRDI(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -213,10 +213,10 @@ throw(ModbusRTU::mbException) ...@@ -213,10 +213,10 @@ throw(ModbusRTU::mbException)
msg.century = century; msg.century = century;
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, replyTimeOut_ms); mbErrCode res = query(addr, qbuf, qreply, replyTimeOut_ms);
if( res == erNoError ) if( res == erNoError )
return SetDateTimeRetMessage(reply); return SetDateTimeRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
...@@ -320,10 +320,10 @@ throw(ModbusRTU::mbException) ...@@ -320,10 +320,10 @@ throw(ModbusRTU::mbException)
FileTransferMessage msg(addr, idFile, numpack); FileTransferMessage msg(addr, idFile, numpack);
qbuf = msg.transport_msg(); qbuf = msg.transport_msg();
mbErrCode res = query(addr, qbuf, reply, part_timeout_msec); mbErrCode res = query(addr, qbuf, qreply, part_timeout_msec);
if( res == erNoError ) if( res == erNoError )
return FileTransferRetMessage(reply); return FileTransferRetMessage(qreply);
throw mbException(res); throw mbException(res);
} }
......
...@@ -39,9 +39,6 @@ size_t ModbusTCPCore::readNextData(UTCPStream* tcp, ...@@ -39,9 +39,6 @@ size_t ModbusTCPCore::readNextData(UTCPStream* tcp,
char* buf = new char[max]; char* buf = new char[max];
if( buf == 0 )
return 0;
try try
{ {
ssize_t l = tcp->receiveBytes(buf, max); ssize_t l = tcp->receiveBytes(buf, max);
...@@ -114,11 +111,19 @@ size_t ModbusTCPCore::getNextData(UTCPStream* tcp, ...@@ -114,11 +111,19 @@ size_t ModbusTCPCore::getNextData(UTCPStream* tcp,
if( len <= 0 ) if( len <= 0 )
len = 7; len = 7;
try
{
size_t ret = ModbusTCPCore::readNextData(tcp, qrecv, len); size_t ret = ModbusTCPCore::readNextData(tcp, qrecv, len);
if( ret == 0 ) if( ret == 0 )
return 0; return 0;
} }
catch( UniSetTypes::CommFailed& ex )
{
if( qrecv.empty() )
return 0;
}
}
size_t i = 0; size_t i = 0;
...@@ -141,9 +146,6 @@ size_t ModbusTCPCore::readDataFD( int fd, std::queue<unsigned char>& qrecv, size ...@@ -141,9 +146,6 @@ size_t ModbusTCPCore::readDataFD( int fd, std::queue<unsigned char>& qrecv, size
char* buf = new char[max]; char* buf = new char[max];
if( buf == 0 )
return 0;
ssize_t l = 0; ssize_t l = 0;
size_t cnt = 0; size_t cnt = 0;
...@@ -209,11 +211,19 @@ size_t ModbusTCPCore::getDataFD( int fd, std::queue<unsigned char>& qrecv, ...@@ -209,11 +211,19 @@ size_t ModbusTCPCore::getDataFD( int fd, std::queue<unsigned char>& qrecv,
if( len == 0 ) if( len == 0 )
len = 7; len = 7;
try
{
size_t ret = ModbusTCPCore::readDataFD(fd, qrecv, len, attempts); size_t ret = ModbusTCPCore::readDataFD(fd, qrecv, len, attempts);
if( ret == 0 && qrecv.empty() ) if( ret == 0 && qrecv.empty() )
return 0; return 0;
} }
catch( UniSetTypes::CommFailed& ex )
{
if( qrecv.empty() )
return 0;
}
}
size_t i = 0; size_t i = 0;
......
...@@ -59,7 +59,7 @@ void ModbusTCPMaster::setChannelTimeout( timeout_t msec ) ...@@ -59,7 +59,7 @@ void ModbusTCPMaster::setChannelTimeout( timeout_t msec )
Poco::Timespan tm = UniSetTimer::millisecToPoco(msec); Poco::Timespan tm = UniSetTimer::millisecToPoco(msec);
Poco::Timespan old = tcp->getReceiveTimeout();; Poco::Timespan old = tcp->getReceiveTimeout();;
if( old.microseconds() == tm.microseconds() ) if( old.totalMicroseconds() == tm.totalMicroseconds() )
return; return;
tcp->setReceiveTimeout(tm); tcp->setReceiveTimeout(tm);
...@@ -201,6 +201,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ...@@ -201,6 +201,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
} }
cleanInputStream(); cleanInputStream();
if( tcp )
tcp->forceDisconnect(); tcp->forceDisconnect();
return erTimeOut; // return erHardwareError; return erTimeOut; // return erHardwareError;
} }
...@@ -247,12 +248,13 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ...@@ -247,12 +248,13 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
if( force_disconnect ) if( force_disconnect )
{ {
if( dlog->is_info() ) if( dlog->is_info() )
dlog->info() << "(query): force disconnect.." << endl; dlog->info() << "(query): disconnect.." << endl;
// при штатном обмене..лучше дождаться конца "посылки".. // при штатном обмене..лучше дождаться конца "посылки"..
// поэтому применяем disconnect(), а не forceDisconnect() // поэтому применяем disconnect(), а не forceDisconnect()
// (с учётом выставленной опции setLinger(true)) // (с учётом выставленной опции setLinger(true))
tcp->close(); if( tcp )
tcp->disconnect();
} }
return res; return res;
...@@ -267,6 +269,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ...@@ -267,6 +269,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
dlog->info() << "(query): force disconnect.." << endl; dlog->info() << "(query): force disconnect.." << endl;
// cleanInputStream(); // cleanInputStream();
if( tcp )
tcp->forceDisconnect(); tcp->forceDisconnect();
} }
...@@ -303,7 +306,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ...@@ -303,7 +306,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
catch( const std::exception& e ) catch( const std::exception& e )
{ {
if( dlog->is_warn() ) if( dlog->is_warn() )
dlog->crit() << "(query): " << e.what() << std::endl; dlog->warn() << "(query): " << e.what() << std::endl;
} }
return erTimeOut; // erHardwareError return erTimeOut; // erHardwareError
...@@ -385,7 +388,7 @@ bool ModbusTCPMaster::connect( const std::string& addr, int _port, bool closeOld ...@@ -385,7 +388,7 @@ bool ModbusTCPMaster::connect( const std::string& addr, int _port, bool closeOld
{ {
ostringstream s; ostringstream s;
s << "(ModbusTCPMaster): connect " << iaddr << ":" << port << " error: " << e.what(); s << "(ModbusTCPMaster): connect " << iaddr << ":" << port << " error: " << e.what();
dlog->crit() << iaddr << std::endl; dlog->crit() << s.str() << std::endl;
} }
} }
...@@ -426,13 +429,22 @@ bool ModbusTCPMaster::connect( const Poco::Net::SocketAddress& addr, int _port, ...@@ -426,13 +429,22 @@ bool ModbusTCPMaster::connect( const Poco::Net::SocketAddress& addr, int _port,
tcp->setNoDelay(true); tcp->setNoDelay(true);
return true; return true;
} }
catch( Poco::TimeoutException& ex)
{
if( dlog->debugging(Debug::CRIT) )
{
ostringstream s;
s << "(ModbusTCPMaster): create connection " << iaddr << ":" << port << " timeout exception";
dlog->crit() << s.str() << std::endl;
}
}
catch( Poco::Net::NetException& ex) catch( Poco::Net::NetException& ex)
{ {
if( dlog->debugging(Debug::CRIT) ) if( dlog->debugging(Debug::CRIT) )
{ {
ostringstream s; ostringstream s;
s << "(ModbusTCPMaster): create connection " << iaddr << ":" << port << " error: " << ex.displayText(); s << "(ModbusTCPMaster): create connection " << iaddr << ":" << port << " error: " << ex.displayText();
dlog->crit() << iaddr << std::endl; dlog->crit() << s.str() << std::endl;
} }
} }
catch( const std::exception& e ) catch( const std::exception& e )
...@@ -441,7 +453,7 @@ bool ModbusTCPMaster::connect( const Poco::Net::SocketAddress& addr, int _port, ...@@ -441,7 +453,7 @@ bool ModbusTCPMaster::connect( const Poco::Net::SocketAddress& addr, int _port,
{ {
ostringstream s; ostringstream s;
s << "(ModbusTCPMaster): connection " << iaddr << ":" << port << " error: " << e.what(); s << "(ModbusTCPMaster): connection " << iaddr << ":" << port << " error: " << e.what();
dlog->crit() << iaddr << std::endl; dlog->crit() << s.str() << std::endl;
} }
} }
catch( ... ) catch( ... )
...@@ -466,7 +478,7 @@ void ModbusTCPMaster::disconnect() ...@@ -466,7 +478,7 @@ void ModbusTCPMaster::disconnect()
if( !tcp ) if( !tcp )
return; return;
tcp->close(); tcp->disconnect(); // close();
tcp = nullptr; tcp = nullptr;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -194,6 +194,18 @@ bool ModbusRTU::isWriteFunction( SlaveFunctionCode c ) ...@@ -194,6 +194,18 @@ bool ModbusRTU::isWriteFunction( SlaveFunctionCode c )
return false; return false;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool ModbusRTU::isReadFunction( SlaveFunctionCode c )
{
if( c == fnReadCoilStatus ||
c == fnReadInputStatus ||
c == fnReadOutputRegisters ||
c == fnReadInputRegisters )
return true;
return false;
}
// -------------------------------------------------------------------------
std::ostream& ModbusRTU::mbPrintMessage( std::ostream& os, ModbusByte* m, size_t len ) std::ostream& ModbusRTU::mbPrintMessage( std::ostream& os, ModbusByte* m, size_t len )
{ {
// Чтобы не менять настройки 'os' // Чтобы не менять настройки 'os'
......
...@@ -14,10 +14,12 @@ ...@@ -14,10 +14,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <functional>
#include <sstream> #include <sstream>
#include <cstdlib> #include <cstdlib>
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "PassiveTimer.h" #include "PassiveTimer.h"
#include "ThreadCreator.h"
#include "TCPCheck.h" #include "TCPCheck.h"
#include "UTCPStream.h" #include "UTCPStream.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -76,11 +78,38 @@ void TCPCheck::check_thread() ...@@ -76,11 +78,38 @@ void TCPCheck::check_thread()
t.create(ip, port, tout_msec); t.create(ip, port, tout_msec);
t.setKeepAliveParams( (tout_msec > 1000 ? tout_msec / 1000 : 1) ); t.setKeepAliveParams( (tout_msec > 1000 ? tout_msec / 1000 : 1) );
setResult(true); setResult(true);
t.close(); t.disconnect();
} }
catch( ... ) {} catch( ... ) {}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
template<typename T>
class TGuard
{
public:
TGuard( T* m, typename ThreadCreator<T>::Action a ):
t(m,a)
{
t.start();
}
~TGuard()
{
if( t.isRunning() )
t.stop();
}
inline bool isRunning()
{
return t.isRunning();
}
protected:
ThreadCreator<T> t;
};
// -----------------------------------------------------------------------------
bool TCPCheck::ping( const std::string& _ip, timeout_t tout, timeout_t sleep_msec, const std::string& _ping_args ) bool TCPCheck::ping( const std::string& _ip, timeout_t tout, timeout_t sleep_msec, const std::string& _ping_args )
{ {
ip = _ip; ip = _ip;
...@@ -89,17 +118,13 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, timeout_t sleep_mse ...@@ -89,17 +118,13 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, timeout_t sleep_mse
setResult(false); setResult(false);
ThreadCreator<TCPCheck> t(this, &TCPCheck::ping_thread); TGuard<TCPCheck> t(this, &TCPCheck::ping_thread);
t.start();
PassiveTimer pt(tout); PassiveTimer pt(tout);
while( !pt.checkTime() && t.isRunning() ) while( !pt.checkTime() && t.isRunning() )
msleep(sleep_msec); msleep(sleep_msec);
if( t.isRunning() ) // !getResult() )
t.stop();
return result; return result;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -5,7 +5,11 @@ using namespace std; ...@@ -5,7 +5,11 @@ using namespace std;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
USocket::~USocket() USocket::~USocket()
{ {
try
{
close(); close();
}
catch(...){}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
USocket::USocket( int sock ) USocket::USocket( int sock )
......
...@@ -12,7 +12,11 @@ using namespace std; ...@@ -12,7 +12,11 @@ using namespace std;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UTCPSocket::~UTCPSocket() UTCPSocket::~UTCPSocket()
{ {
try
{
Poco::Net::ServerSocket::close(); Poco::Net::ServerSocket::close();
}
catch(...){}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UTCPSocket::UTCPSocket() UTCPSocket::UTCPSocket()
......
...@@ -57,20 +57,40 @@ bool UTCPStream::isSetLinger() const ...@@ -57,20 +57,40 @@ bool UTCPStream::isSetLinger() const
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UTCPStream::forceDisconnect() void UTCPStream::forceDisconnect()
{ {
if( !isConnected() )
return;
try try
{ {
bool on;
int sec;
Poco::Net::StreamSocket::getLinger(on, sec);
setLinger(false, 0); setLinger(false, 0);
}
// catch( Poco::Net::NetException& ex ){}
catch( std::exception& ex ){}
try
{
close(); close();
//shutdown(); //shutdown();
Poco::Net::StreamSocket::setLinger(on, sec);
} }
catch( Poco::Net::NetException& ) // catch( Poco::Net::NetException& ex ){}
catch( std::exception& ex ){}
}
// -------------------------------------------------------------------------
void UTCPStream::disconnect()
{
try
{ {
shutdown();
}
// catch( Poco::Net::NetException& ex ){}
catch( std::exception& ex ){}
try
{
close();
} }
// catch( Poco::Net::NetException& ex ){}
catch( std::exception& ex ){}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
int UTCPStream::getSocket() const int UTCPStream::getSocket() const
...@@ -81,13 +101,13 @@ int UTCPStream::getSocket() const ...@@ -81,13 +101,13 @@ int UTCPStream::getSocket() const
timeout_t UTCPStream::getTimeout() const timeout_t UTCPStream::getTimeout() const
{ {
auto tm = Poco::Net::StreamSocket::getReceiveTimeout(); auto tm = Poco::Net::StreamSocket::getReceiveTimeout();
return tm.microseconds(); return tm.totalMicroseconds();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UTCPStream::create(const std::string& hname, int port, timeout_t tout_msec ) void UTCPStream::create( const std::string& hname, int port, timeout_t tout_msec )
{ {
Poco::Net::SocketAddress sa(hname, port); Poco::Net::SocketAddress saddr(hname, port);
connect(sa, tout_msec * 1000); connect(saddr, UniSetTimer::millisecToPoco(tout_msec));
setKeepAlive(true); setKeepAlive(true);
Poco::Net::StreamSocket::setLinger(true, 1); Poco::Net::StreamSocket::setLinger(true, 1);
setKeepAliveParams(); setKeepAliveParams();
...@@ -95,7 +115,7 @@ void UTCPStream::create(const std::string& hname, int port, timeout_t tout_msec ...@@ -95,7 +115,7 @@ void UTCPStream::create(const std::string& hname, int port, timeout_t tout_msec
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool UTCPStream::isConnected() noexcept bool UTCPStream::isConnected() noexcept
{ {
return ( Poco::Net::StreamSocket::sockfd() > 0 ); return ( Poco::Net::StreamSocket::sockfd() != POCO_INVALID_SOCKET );
/* /*
try try
{ {
......
...@@ -920,8 +920,8 @@ throw(ResolveNameError, UniSetTypes::TimeOut ) ...@@ -920,8 +920,8 @@ throw(ResolveNameError, UniSetTypes::TimeOut )
catch(const CosNaming::NamingContext::NotFound& nf) {} catch(const CosNaming::NamingContext::NotFound& nf) {}
catch(const CosNaming::NamingContext::InvalidName& nf) {} catch(const CosNaming::NamingContext::InvalidName& nf) {}
catch(const CosNaming::NamingContext::CannotProceed& cp) {} catch(const CosNaming::NamingContext::CannotProceed& cp) {}
catch( const Exception ) {} catch( const UniSetTypes::Exception& ex ) {}
catch( const CORBA::OBJECT_NOT_EXIST ) catch( const CORBA::OBJECT_NOT_EXIST& ex )
{ {
throw UniSetTypes::ResolveNameError("ObjectNOTExist"); throw UniSetTypes::ResolveNameError("ObjectNOTExist");
} }
......
...@@ -59,8 +59,8 @@ static const int numErrorTags = sizeof(errorTags) / sizeof(error_item); ...@@ -59,8 +59,8 @@ static const int numErrorTags = sizeof(errorTags) / sizeof(error_item);
Debug::type const Debug::ANY = Debug::type( Debug::type const Debug::ANY = Debug::type(
Debug::INFO | Debug::INIT | Debug::WARN | Debug::CRIT | Debug::INFO | Debug::INIT | Debug::WARN | Debug::CRIT |
Debug::LEVEL1 | Debug::LEVEL2 | Debug::LEVEL3 | Debug::LEVEL4 | Debug::LEVEL1 | Debug::LEVEL2 | Debug::LEVEL3 | Debug::LEVEL4 |
Debug::LEVEL5 | Debug::LEVEL5 | Debug::LEVEL6 | Debug::LEVEL7 | Debug::LEVEL5 | Debug::LEVEL6 | Debug::LEVEL7 | Debug::LEVEL8 |
Debug::LEVEL8 | Debug::LEVEL9 | Debug::REPOSITORY | Debug::SYSTEM | Debug::LEVEL9 | Debug::REPOSITORY | Debug::SYSTEM |
Debug::EXCEPTION ); Debug::EXCEPTION );
...@@ -124,7 +124,11 @@ void Debug::showTags(ostream& os) noexcept ...@@ -124,7 +124,11 @@ void Debug::showTags(ostream& os) noexcept
<< setw(10) << errorTags[i].name << setw(10) << errorTags[i].name
<< " " << errorTags[i].desc << '\n'; << " " << errorTags[i].desc << '\n';
try
{
os.flush(); os.flush();
}
catch(...){}
} }
std::ostream& operator<<(std::ostream& os, Debug::type level ) noexcept std::ostream& operator<<(std::ostream& os, Debug::type level ) noexcept
...@@ -166,7 +170,13 @@ std::string Debug::str( Debug::type level ) noexcept ...@@ -166,7 +170,13 @@ std::string Debug::str( Debug::type level ) noexcept
} }
} }
try
{
return s.str(); return s.str();
}
catch(...){}
return "";
} }
......
...@@ -132,8 +132,7 @@ void LogReader::disconnect() ...@@ -132,8 +132,7 @@ void LogReader::disconnect()
try try
{ {
//tcp->shutdown(); tcp->disconnect();
tcp->close();
} }
catch( const Poco::Net::NetException& e ) catch( const Poco::Net::NetException& e )
{ {
...@@ -181,7 +180,7 @@ void LogReader::sendCommand(const std::string& _addr, int _port, std::vector<Com ...@@ -181,7 +180,7 @@ void LogReader::sendCommand(const std::string& _addr, int _port, std::vector<Com
msg.data = c.data; msg.data = c.data;
msg.setLogName(c.logfilter); msg.setLogName(c.logfilter);
unsigned int n = 2; // две попытки на посылку size_t n = 2; // две попытки на посылку
while( n > 0 ) while( n > 0 )
{ {
...@@ -245,7 +244,7 @@ void LogReader::sendCommand(const std::string& _addr, int _port, std::vector<Com ...@@ -245,7 +244,7 @@ void LogReader::sendCommand(const std::string& _addr, int _port, std::vector<Com
// теперь ждём ответ.. // теперь ждём ответ..
try try
{ {
int a = 2; size_t a = 2;
while( a > 0 && tcp->poll(UniSetTimer::millisecToPoco(reply_timeout), Poco::Net::Socket::SELECT_READ) ) while( a > 0 && tcp->poll(UniSetTimer::millisecToPoco(reply_timeout), Poco::Net::Socket::SELECT_READ) )
{ {
......
...@@ -39,28 +39,41 @@ LogServer::~LogServer() noexcept ...@@ -39,28 +39,41 @@ LogServer::~LogServer() noexcept
catch(...){} catch(...){}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<LogAgregator> log ) noexcept: LogServer::LogServer( std::shared_ptr<LogAgregator> log ):
LogServer(static_pointer_cast<DebugStream>(log)) LogServer()
{ {
elog = dynamic_pointer_cast<DebugStream>(log);
if( !elog )
{
ostringstream err;
err << myname << "(LogServer): dynamic_pointer_cast FAILED! ";
if( mylog.is_info() )
mylog.info() << myname << "(evfinish): terminate..." << endl;
if( mylog.is_crit() )
mylog.crit() << err.str() << endl;
cerr << err.str() << endl;
throw SystemError(err.str());
}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<DebugStream> log ) noexcept: LogServer::LogServer( std::shared_ptr<DebugStream> log ):
timeout(UniSetTimer::WaitUpTime), LogServer()
cmdTimeout(2000),
sessLogLevel(Debug::NONE),
sock(0),
elog(log)
{ {
elog = log;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogServer::LogServer() noexcept: LogServer::LogServer():
timeout(UniSetTimer::WaitUpTime), timeout(UniSetTimer::WaitUpTime),
cmdTimeout(2000), cmdTimeout(2000),
sessLogLevel(Debug::NONE), sessLogLevel(Debug::NONE),
sock(0), sock(0),
elog(nullptr) elog(nullptr)
{ {
slist.reserve(sessMaxCount);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogServer::evfinish( const ev::loop_ref& loop ) void LogServer::evfinish( const ev::loop_ref& loop )
...@@ -115,6 +128,45 @@ void LogServer::terminate() ...@@ -115,6 +128,45 @@ void LogServer::terminate()
loop.evstop(this); loop.evstop(this);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool LogServer::check( bool restart_if_fail )
{
try
{
// для проверки пробуем открыть соединение..
UTCPSocket s(addr, port);
s.close();
return true;
}
catch(...){}
if( !restart_if_fail )
return false;
if( !sock )
return false;
io.stop();
io.set<LogServer, &LogServer::ioAccept>(this);
io.start(sock->getSocket(), ev::READ);
try
{
UTCPSocket s(addr, port);
s.close();
return true;
}
catch( Poco::Net::NetException& ex )
{
ostringstream err;
err << myname << "(check): socket error:" << ex.message();
if( mylog.is_crit() )
mylog.crit() << err.str() << endl;
}
return false;
}
// -------------------------------------------------------------------------
void LogServer::evprepare( const ev::loop_ref& eloop ) void LogServer::evprepare( const ev::loop_ref& eloop )
{ {
if( sock ) if( sock )
...@@ -146,8 +198,8 @@ void LogServer::evprepare( const ev::loop_ref& eloop ) ...@@ -146,8 +198,8 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
sock->setBlocking(false); sock->setBlocking(false);
io.set<LogServer, &LogServer::ioAccept>(this);
io.set( eloop ); io.set( eloop );
io.set<LogServer, &LogServer::ioAccept>(this);
io.start(sock->getSocket(), ev::READ); io.start(sock->getSocket(), ev::READ);
isrunning = true; isrunning = true;
} }
...@@ -172,9 +224,9 @@ void LogServer::ioAccept( ev::io& watcher, int revents ) ...@@ -172,9 +224,9 @@ void LogServer::ioAccept( ev::io& watcher, int revents )
} }
{ {
uniset_rwmutex_wrlock l(mutSList); uniset_rwmutex_rlock l(mutSList);
if( scount >= sessMaxCount ) if( slist.size() >= sessMaxCount )
{ {
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << myname << "(LogServer::ioAccept): session limit(" << sessMaxCount << ")" << endl; mylog.crit() << myname << "(LogServer::ioAccept): session limit(" << sessMaxCount << ")" << endl;
...@@ -194,13 +246,10 @@ void LogServer::ioAccept( ev::io& watcher, int revents ) ...@@ -194,13 +246,10 @@ void LogServer::ioAccept( ev::io& watcher, int revents )
s->signal_logsession_command().connect( sigc::mem_fun(this, &LogServer::onCommand) ); s->signal_logsession_command().connect( sigc::mem_fun(this, &LogServer::onCommand) );
{ {
uniset_rwmutex_wrlock l(mutSList); uniset_rwmutex_wrlock l(mutSList);
scount++; slist.push_back(s);
// на первой сессии запоминаем состояние логов // на первой сессии запоминаем состояние логов
if( scount == 1 ) if( slist.size() == 1 )
saveDefaultLogLevels("ALL"); saveDefaultLogLevels("ALL");
slist.push_back(s);
} }
s->run(watcher.loop); s->run(watcher.loop);
...@@ -220,14 +269,12 @@ void LogServer::sessionFinished( LogSession* s ) ...@@ -220,14 +269,12 @@ void LogServer::sessionFinished( LogSession* s )
if( i->get() == s ) if( i->get() == s )
{ {
slist.erase(i); slist.erase(i);
scount--;
break; break;
} }
} }
if( slist.empty() ) if( slist.empty() )
{ {
scount = 0;
// восстанавливаем уровни логов по умолчанию // восстанавливаем уровни логов по умолчанию
restoreDefaultLogLevels("ALL"); restoreDefaultLogLevels("ALL");
} }
...@@ -255,9 +302,14 @@ string LogServer::getShortInfo() ...@@ -255,9 +302,14 @@ string LogServer::getShortInfo()
{ {
ostringstream inf; ostringstream inf;
inf << "LogServer: " << myname << endl; inf << "LogServer: " << myname
<< " ["
<< " sessMaxCount=" << sessMaxCount
<< " ]"
<< endl;
{ {
uniset_rwmutex_wrlock l(mutSList); uniset_rwmutex_rlock l(mutSList);
for( const auto& s : slist ) for( const auto& s : slist )
inf << " " << s->getShortInfo() << endl; inf << " " << s->getShortInfo() << endl;
......
...@@ -74,7 +74,7 @@ LogSession::LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugS ...@@ -74,7 +74,7 @@ LogSession::LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugS
if( iaddr.host().toString().empty() ) if( iaddr.host().toString().empty() )
{ {
ostringstream err; ostringstream err;
err << "(ModbusTCPSession): unknonwn ip(0.0.0.0) client disconnected?!"; err << "(LogSession): unknonwn ip(0.0.0.0) client disconnected?!";
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << err.str() << endl; mylog.crit() << err.str() << endl;
...@@ -107,7 +107,7 @@ LogSession::LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugS ...@@ -107,7 +107,7 @@ LogSession::LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugS
if( log ) if( log )
conn = log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) ); conn = log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) );
else else
mylog.crit() << "LOG NULL!!" << endl; mylog.crit() << "(LogSession): LOG NULL!!" << endl;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogSession::logOnEvent( const std::string& s ) noexcept void LogSession::logOnEvent( const std::string& s ) noexcept
...@@ -137,11 +137,19 @@ void LogSession::logOnEvent( const std::string& s ) noexcept ...@@ -137,11 +137,19 @@ void LogSession::logOnEvent( const std::string& s ) noexcept
if( logbuf.size() >= maxRecordsNum ) if( logbuf.size() >= maxRecordsNum )
{ {
numLostMsg++; numLostMsg++;
if( numLostMsg > maxRecordsNum )
{
// видимо клиент отвалился или совсем не успевает читать
// разрываем сессию..
if( mylog.is_info() )
mylog.info() << peername << "(LogSession::onEvent): too many lost messages. Close session.." << endl;
cancelled = true;
}
if( !lostMsg ) if( !lostMsg )
{ {
ostringstream err; ostringstream err;
err << "The buffer is full. Message is lost...(size of buffer " << maxRecordsNum << ")" << endl; err << "(LogSession): The buffer is full. Message is lost...(size of buffer " << maxRecordsNum << ")" << endl;
logbuf.emplace(new UTCPCore::Buffer(std::move(err.str()))); logbuf.emplace(new UTCPCore::Buffer(std::move(err.str())));
lostMsg = true; lostMsg = true;
} }
...@@ -163,7 +171,7 @@ void LogSession::run( const ev::loop_ref& loop ) noexcept ...@@ -163,7 +171,7 @@ void LogSession::run( const ev::loop_ref& loop ) noexcept
setSessionLogLevel(Debug::ANY); setSessionLogLevel(Debug::ANY);
if( mylog.is_info() ) if( mylog.is_info() )
mylog.info() << peername << "(run): run session.." << endl; mylog.info() << peername << "(LogSession::run): run session.." << endl;
asyncEvent.set(loop); asyncEvent.set(loop);
cmdTimer.set(loop); cmdTimer.set(loop);
...@@ -178,7 +186,7 @@ void LogSession::run( const ev::loop_ref& loop ) noexcept ...@@ -178,7 +186,7 @@ void LogSession::run( const ev::loop_ref& loop ) noexcept
void LogSession::terminate() void LogSession::terminate()
{ {
if( mylog.is_info() ) if( mylog.is_info() )
mylog.info() << peername << "(terminate)..." << endl; mylog.info() << peername << "(LogSession::terminate)..." << endl;
cancelled = true; cancelled = true;
...@@ -196,6 +204,7 @@ void LogSession::terminate() ...@@ -196,6 +204,7 @@ void LogSession::terminate()
logbuf.pop(); logbuf.pop();
} }
sock->disconnect();
sock->close(); sock->close();
final(); final();
} }
...@@ -205,7 +214,7 @@ void LogSession::event( ev::async& watcher, int revents ) noexcept ...@@ -205,7 +214,7 @@ void LogSession::event( ev::async& watcher, int revents ) noexcept
if( EV_ERROR & revents ) if( EV_ERROR & revents )
{ {
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << peername << "(event): EVENT ERROR.." << endl; mylog.crit() << peername << "(LogSession::event): EVENT ERROR.." << endl;
return; return;
} }
...@@ -218,7 +227,7 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept ...@@ -218,7 +227,7 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept
if( EV_ERROR & revents ) if( EV_ERROR & revents )
{ {
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << peername << "(callback): EVENT ERROR.." << endl; mylog.crit() << peername << "(LogSession::callback): EVENT ERROR.." << endl;
return; return;
} }
...@@ -241,10 +250,10 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept ...@@ -241,10 +250,10 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept
catch(...){} catch(...){}
} }
if( cancelled ) if( cancelled.load() )
{ {
if( mylog.is_info() ) if( mylog.is_info() )
mylog.info() << peername << ": stop session... disconnect.." << endl; mylog.info() << peername << "LogSession: stop session... disconnect.." << endl;
io.stop(); io.stop();
cmdTimer.stop(); cmdTimer.stop();
...@@ -262,7 +271,7 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept ...@@ -262,7 +271,7 @@ void LogSession::callback( ev::io& watcher, int revents ) noexcept
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogSession::writeEvent( ev::io& watcher ) void LogSession::writeEvent( ev::io& watcher )
{ {
if( cancelled ) if( cancelled.load() )
return; return;
UTCPCore::Buffer* buffer = 0; UTCPCore::Buffer* buffer = 0;
...@@ -283,17 +292,17 @@ void LogSession::writeEvent( ev::io& watcher ) ...@@ -283,17 +292,17 @@ void LogSession::writeEvent( ev::io& watcher )
if( !buffer ) if( !buffer )
return; return;
ssize_t ret = write(watcher.fd, buffer->dpos(), buffer->nbytes()); ssize_t ret = ::write(watcher.fd, buffer->dpos(), buffer->nbytes());
if( ret < 0 ) if( ret < 0 )
{ {
if( mylog.is_warn() ) if( mylog.is_warn() )
mylog.warn() << peername << "(writeEvent): write to socket error(" << errno << "): " << strerror(errno) << endl; mylog.warn() << peername << "(LogSession::writeEvent): write to socket error(" << errno << "): " << strerror(errno) << endl;
if( errno == EPIPE ) if( errno == EPIPE || errno == EBADF )
{ {
if( mylog.is_warn() ) if( mylog.is_warn() )
mylog.warn() << peername << "(writeEvent): write error.. terminate session.." << endl; mylog.warn() << peername << "(LogSession::writeEvent): write error.. terminate session.." << endl;
cancelled = true; cancelled = true;
} }
...@@ -344,7 +353,7 @@ size_t LogSession::readData( unsigned char* buf, int len ) ...@@ -344,7 +353,7 @@ size_t LogSession::readData( unsigned char* buf, int len )
if( res < 0 ) if( res < 0 )
{ {
if( errno != EAGAIN && mylog.is_warn() ) if( errno != EAGAIN && mylog.is_warn() )
mylog.warn() << peername << "(readData): read from socket error(" << errno << "): " << strerror(errno) << endl; mylog.warn() << peername << "(LogSession::readData): read from socket error(" << errno << "): " << strerror(errno) << endl;
return 0; return 0;
} }
...@@ -362,7 +371,7 @@ size_t LogSession::readData( unsigned char* buf, int len ) ...@@ -362,7 +371,7 @@ size_t LogSession::readData( unsigned char* buf, int len )
} }
mylog.info() << peername << "(readData): client disconnected.." << endl; mylog.info() << peername << "(LogSession::readData): client disconnected.." << endl;
cancelled = true; cancelled = true;
return 0; return 0;
} }
...@@ -382,13 +391,13 @@ void LogSession::readEvent( ev::io& watcher ) noexcept ...@@ -382,13 +391,13 @@ void LogSession::readEvent( ev::io& watcher ) noexcept
if( ret != sizeof(msg) || msg.magic != LogServerTypes::MAGICNUM ) if( ret != sizeof(msg) || msg.magic != LogServerTypes::MAGICNUM )
{ {
if( mylog.is_warn() ) if( mylog.is_warn() )
mylog.warn() << peername << "(readEvent): BAD MESSAGE..." << endl; mylog.warn() << peername << "(LogSession::readEvent): BAD MESSAGE..." << endl;
return; return;
} }
if( mylog.is_info() ) if( mylog.is_info() )
mylog.info() << peername << "(readEvent): receive command: '" << msg.cmd << "'" << endl; mylog.info() << peername << "(LogSession::readEvent): receive command: '" << msg.cmd << "'" << endl;
string cmdLogName(msg.logname); string cmdLogName(msg.logname);
...@@ -399,7 +408,7 @@ void LogSession::readEvent( ev::io& watcher ) noexcept ...@@ -399,7 +408,7 @@ void LogSession::readEvent( ev::io& watcher ) noexcept
catch( std::exception& ex ) catch( std::exception& ex )
{ {
if( mylog.is_warn() ) if( mylog.is_warn() )
mylog.warn() << peername << "(readEvent): " << ex.what() << endl; mylog.warn() << peername << "(LogSession::readEvent): " << ex.what() << endl;
} }
catch(...){} catch(...){}
...@@ -550,7 +559,7 @@ void LogSession::cmdProcessing( const string& cmdLogName, const LogServerTypes:: ...@@ -550,7 +559,7 @@ void LogSession::cmdProcessing( const string& cmdLogName, const LogServerTypes::
catch( std::exception& ex ) catch( std::exception& ex )
{ {
if( mylog.is_warn() ) if( mylog.is_warn() )
mylog.warn() << peername << "(cmdProcessing): " << ex.what() << endl; mylog.warn() << peername << "(LogSession::cmdProcessing): " << ex.what() << endl;
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -559,7 +568,7 @@ void LogSession::onCmdTimeout( ev::timer& watcher, int revents ) noexcept ...@@ -559,7 +568,7 @@ void LogSession::onCmdTimeout( ev::timer& watcher, int revents ) noexcept
if( EV_ERROR & revents ) if( EV_ERROR & revents )
{ {
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << peername << "(onCmdTimeout): EVENT ERROR.." << endl; mylog.crit() << peername << "(LogSession::onCmdTimeout): EVENT ERROR.." << endl;
return; return;
} }
...@@ -573,7 +582,7 @@ void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents ) noexc ...@@ -573,7 +582,7 @@ void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents ) noexc
if( EV_ERROR & revents ) if( EV_ERROR & revents )
{ {
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << peername << "(onCheckConnectionTimer): EVENT ERROR.." << endl; mylog.crit() << peername << "(LogSession::onCheckConnectionTimer): EVENT ERROR.." << endl;
return; return;
} }
...@@ -588,10 +597,12 @@ void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents ) noexc ...@@ -588,10 +597,12 @@ void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents ) noexc
// если клиент уже отвалился.. то при попытке write.. сессия будет закрыта. // если клиент уже отвалился.. то при попытке write.. сессия будет закрыта.
// длинное сообщение ("keep alive message") забивает логи, что потом неудобно смотреть, поэтому пишем "пустоту" // длинное сообщение ("keep alive message") забивает логи, что потом неудобно смотреть
// поэтому используем "пробел и возврат на один символ"
try try
{ {
logbuf.emplace(new UTCPCore::Buffer("")); //
logbuf.emplace(new UTCPCore::Buffer(" \b"));
} }
catch(...){} catch(...){}
...@@ -649,7 +660,7 @@ string LogSession::getShortInfo() noexcept ...@@ -649,7 +660,7 @@ string LogSession::getShortInfo() noexcept
ostringstream inf; ostringstream inf;
inf << "client: " << caddr << endl inf << "client: " << caddr << " :"
<< " buffer[" << maxRecordsNum << "]: size=" << sz << " buffer[" << maxRecordsNum << "]: size=" << sz
<< " maxCount=" << maxCount << " maxCount=" << maxCount
<< " minSizeMsg=" << minSizeMsg << " minSizeMsg=" << minSizeMsg
...@@ -660,3 +671,8 @@ string LogSession::getShortInfo() noexcept ...@@ -660,3 +671,8 @@ string LogSession::getShortInfo() noexcept
return std::move(inf.str()); return std::move(inf.str());
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
string LogSession::name() const noexcept
{
return caddr;
}
// ---------------------------------------------------------------------
...@@ -24,9 +24,10 @@ ...@@ -24,9 +24,10 @@
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
ObjectIndex_XML::ObjectIndex_XML(const string& xmlfile, size_t minSize ): ObjectIndex_XML::ObjectIndex_XML(const string& xmlfile, size_t minSize )
omap(minSize)
{ {
omap.reserve(minSize);
shared_ptr<UniXML> xml = make_shared<UniXML>(); shared_ptr<UniXML> xml = make_shared<UniXML>();
// try // try
// { // {
...@@ -36,9 +37,9 @@ ObjectIndex_XML::ObjectIndex_XML(const string& xmlfile, size_t minSize ): ...@@ -36,9 +37,9 @@ ObjectIndex_XML::ObjectIndex_XML(const string& xmlfile, size_t minSize ):
// catch(...){} // catch(...){}
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
ObjectIndex_XML::ObjectIndex_XML(const std::shared_ptr<UniXML>& xml, size_t minSize ): ObjectIndex_XML::ObjectIndex_XML(const std::shared_ptr<UniXML>& xml, size_t minSize )
omap(minSize)
{ {
omap.reserve(minSize);
build(xml); build(xml);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -111,6 +112,7 @@ void ObjectIndex_XML::build( const std::shared_ptr<UniXML>& xml ) ...@@ -111,6 +112,7 @@ void ObjectIndex_XML::build( const std::shared_ptr<UniXML>& xml )
// //
omap.resize(ind); omap.resize(ind);
omap.shrink_to_fit();
// omap[ind].repName=NULL; // omap[ind].repName=NULL;
// omap[ind].textName=NULL; // omap[ind].textName=NULL;
// omap[ind].id = ind; // omap[ind].id = ind;
...@@ -199,7 +201,7 @@ size_t ObjectIndex_XML::read_section( const std::shared_ptr<UniXML>& xml, const ...@@ -199,7 +201,7 @@ size_t ObjectIndex_XML::read_section( const std::shared_ptr<UniXML>& xml, const
// cout << "read: " << "(" << ind << ") " << omap[ind].repName << "\t" << omap[ind].textName << endl; // cout << "read: " << "(" << ind << ") " << omap[ind].repName << "\t" << omap[ind].textName << endl;
ind++; ind++;
if( (unsigned)ind >= omap.size() ) if( ind >= omap.size() )
{ {
uinfo << "(ObjectIndex_XML::build): не хватило размера массива maxSize=" << omap.size() uinfo << "(ObjectIndex_XML::build): не хватило размера массива maxSize=" << omap.size()
<< "... Делаем resize + 100" << endl; << "... Делаем resize + 100" << endl;
......
...@@ -343,6 +343,8 @@ void UniSetManager::objects(OManagerCommand cmd) ...@@ -343,6 +343,8 @@ void UniSetManager::objects(OManagerCommand cmd)
{ {
ucrit << myname << "(objects): " << ex << endl; ucrit << myname << "(objects): " << ex << endl;
ucrit << myname << "(objects): не смог зарегистрировать (разрегистрировать) объект -->" << li->getName() << endl; ucrit << myname << "(objects): не смог зарегистрировать (разрегистрировать) объект -->" << li->getName() << endl;
if( cmd == activ )
std::terminate();
} }
catch( const CORBA::SystemException& ex ) catch( const CORBA::SystemException& ex )
{ {
...@@ -360,6 +362,9 @@ void UniSetManager::objects(OManagerCommand cmd) ...@@ -360,6 +362,9 @@ void UniSetManager::objects(OManagerCommand cmd)
ucrit << myname << "(objects): file: " << fe.file() ucrit << myname << "(objects): file: " << fe.file()
<< " line: " << fe.line() << " line: " << fe.line()
<< " mesg: " << fe.errmsg() << endl; << " mesg: " << fe.errmsg() << endl;
if( cmd == activ )
std::terminate();
} }
} }
} // unlock } // unlock
......
...@@ -32,8 +32,6 @@ using namespace UniSetTypes; ...@@ -32,8 +32,6 @@ using namespace UniSetTypes;
NCRestorer_XML::NCRestorer_XML( const string& fname ): NCRestorer_XML::NCRestorer_XML( const string& fname ):
s_filterField(""), s_filterField(""),
s_filterValue(""), s_filterValue(""),
c_filterField(""),
c_filterValue(""),
t_filterField(""), t_filterField(""),
t_filterValue(""), t_filterValue(""),
fname(fname), fname(fname),
...@@ -47,8 +45,6 @@ NCRestorer_XML::NCRestorer_XML(const string& fname, ...@@ -47,8 +45,6 @@ NCRestorer_XML::NCRestorer_XML(const string& fname,
const std::string& f_value): const std::string& f_value):
s_filterField(f_field), s_filterField(f_field),
s_filterValue(f_value), s_filterValue(f_value),
c_filterField(""),
c_filterValue(""),
t_filterField(""), t_filterField(""),
t_filterValue(""), t_filterValue(""),
fname(fname), fname(fname),
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <thread> #include <thread>
#include <future>
#include "Mutex.h" #include "Mutex.h"
#include "UniSetTypes.h" #include "UniSetTypes.h"
...@@ -47,8 +48,10 @@ void la_logOnEvent( const std::string& s ) ...@@ -47,8 +48,10 @@ void la_logOnEvent( const std::string& s )
la_msg << s; la_msg << s;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void readlog_thread1() bool readlog_thread1()
{ {
try
{
LogReader lr; LogReader lr;
lr.setinTimeout(readTimeout); lr.setinTimeout(readTimeout);
lr.signal_stream_event().connect( sigc::ptr_fun(rlog1OnEvent) ); lr.signal_stream_event().connect( sigc::ptr_fun(rlog1OnEvent) );
...@@ -57,10 +60,20 @@ void readlog_thread1() ...@@ -57,10 +60,20 @@ void readlog_thread1()
while( !g_read_cancel ) while( !g_read_cancel )
lr.readlogs(ip, port); // ,LogServerTypes::cmdNOP,0,"",true); lr.readlogs(ip, port); // ,LogServerTypes::cmdNOP,0,"",true);
return true;
}
catch( std::exception& ex )
{
}
return false;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void readlog_thread2() bool readlog_thread2()
{ {
try
{
LogReader lr; LogReader lr;
lr.setinTimeout(readTimeout); lr.setinTimeout(readTimeout);
lr.signal_stream_event().connect( sigc::ptr_fun(rlog2OnEvent) ); lr.signal_stream_event().connect( sigc::ptr_fun(rlog2OnEvent) );
...@@ -69,6 +82,13 @@ void readlog_thread2() ...@@ -69,6 +82,13 @@ void readlog_thread2()
while( !g_read_cancel ) while( !g_read_cancel )
lr.readlogs(ip, port); // ,LogServerTypes::cmdNOP,0,"",true); lr.readlogs(ip, port); // ,LogServerTypes::cmdNOP,0,"",true);
return true;
}
catch( std::exception& ex )
{
}
return false;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
TEST_CASE("LogAgregator", "[LogServer][LogAgregator]" ) TEST_CASE("LogAgregator", "[LogServer][LogAgregator]" )
...@@ -133,7 +153,7 @@ TEST_CASE("LogServer", "[LogServer]" ) ...@@ -133,7 +153,7 @@ TEST_CASE("LogServer", "[LogServer]" )
REQUIRE( ls.isRunning() ); REQUIRE( ls.isRunning() );
msg.str(""); msg.str("");
auto r_thr = make_shared<std::thread>(readlog_thread1); auto ret = std::async(std::launch::async, readlog_thread1); // make_shared<std::thread>(readlog_thread1);
msleep(100); // небольшая пауза на создание потока и т.п. msleep(100); // небольшая пауза на создание потока и т.п.
...@@ -168,10 +188,7 @@ TEST_CASE("LogServer", "[LogServer]" ) ...@@ -168,10 +188,7 @@ TEST_CASE("LogServer", "[LogServer]" )
} }
g_read_cancel = true; g_read_cancel = true;
msleep(readTimeout); ret.get();
if( r_thr->joinable() )
r_thr->join();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
TEST_CASE("MaxSessions", "[LogServer]" ) TEST_CASE("MaxSessions", "[LogServer]" )
...@@ -205,11 +222,11 @@ TEST_CASE("MaxSessions", "[LogServer]" ) ...@@ -205,11 +222,11 @@ TEST_CASE("MaxSessions", "[LogServer]" )
msg.str(""); msg.str("");
msg2.str(""); msg2.str("");
auto r1_thr = make_shared<std::thread>(readlog_thread1); auto ret1 = std::async(std::launch::async, readlog_thread1); // make_shared<std::thread>(readlog_thread1);
msleep(500); // пауза чтобы первый заведомо успел подключиться раньше второго.. msleep(500); // пауза чтобы первый заведомо успел подключиться раньше второго..
auto r2_thr = make_shared<std::thread>(readlog_thread2); auto ret2 = std::async(std::launch::async, readlog_thread1); // make_shared<std::thread>(readlog_thread2);
msleep(100); // небольшая пауза на создание потока и т.п. msleep(100); // небольшая пауза на создание потока и т.п.
...@@ -240,13 +257,8 @@ TEST_CASE("MaxSessions", "[LogServer]" ) ...@@ -240,13 +257,8 @@ TEST_CASE("MaxSessions", "[LogServer]" )
} }
g_read_cancel = true; g_read_cancel = true;
msleep(readTimeout); ret1.get();
ret2.get();
if( r1_thr->joinable() )
r1_thr->join();
if( r2_thr->joinable() )
r2_thr->join();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
TEST_CASE("LogAgregator regexp", "[LogAgregator]" ) TEST_CASE("LogAgregator regexp", "[LogAgregator]" )
......
...@@ -16,6 +16,8 @@ static atomic_bool cancel = {false}; ...@@ -16,6 +16,8 @@ static atomic_bool cancel = {false};
// -------------------------------------------------------- // --------------------------------------------------------
bool run_test_server() bool run_test_server()
{ {
try
{
UTCPSocket sock(host, port); UTCPSocket sock(host, port);
while( !cancel ) while( !cancel )
...@@ -27,6 +29,10 @@ bool run_test_server() ...@@ -27,6 +29,10 @@ bool run_test_server()
} }
return true; return true;
}
catch(...){}
return false;
} }
// -------------------------------------------------------- // --------------------------------------------------------
// вспомогательный класс для гарантированного завершения потока.. // вспомогательный класс для гарантированного завершения потока..
......
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