Commit e2451a5c authored by Pavel Vainerman's avatar Pavel Vainerman

Глобальное переделывание механизма завершения работы.

Текущая версия: любое завершение делается через Activator Для этого сделана специальная функция в UniSetObject::uterminate(). Исправил ошибки некорректного завершения потоков при выходе. Заодно небольшой рефакторинг.
parent e23632d7
...@@ -293,7 +293,7 @@ ...@@ -293,7 +293,7 @@
<xsl:if test="normalize-space($TESTMODE)!=''"> <xsl:if test="normalize-space($TESTMODE)!=''">
bool checkTestMode() const noexcept; bool checkTestMode() const noexcept;
</xsl:if> </xsl:if>
void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId ); bool waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId );
uniset::ObjectId getSMTestID() const; uniset::ObjectId getSMTestID() const;
void resetMsg(); void resetMsg();
...@@ -505,7 +505,13 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage* ...@@ -505,7 +505,13 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage*
} }
ostate = "StartUp: wait sm ready.."; ostate = "StartUp: wait sm ready..";
waitSM(smReadyTimeout); if( !waitSM(smReadyTimeout) )
{
if( !cancelled )
uterminate();
return;
}
ptStartUpTimeout.reset(); ptStartUpTimeout.reset();
// т.к. для io-переменных важно соблюдать последовательность! // т.к. для io-переменных важно соблюдать последовательность!
// сперва обновить входы.. // сперва обновить входы..
...@@ -826,7 +832,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preTimerInfo( const uniset::TimerMe ...@@ -826,7 +832,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preTimerInfo( const uniset::TimerMe
timerInfo(_tm); timerInfo(_tm);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _testID ) bool <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _testID )
{ {
<xsl:if test="normalize-space($TESTMODE)!=''"> <xsl:if test="normalize-space($TESTMODE)!=''">
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
...@@ -837,7 +843,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -837,7 +843,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
_testID = smTestID; _testID = smTestID;
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
return; return true;
myinfo &lt;&lt; myname &lt;&lt; "(waitSM): waiting SM ready " myinfo &lt;&lt; myname &lt;&lt; "(waitSM): waiting SM ready "
&lt;&lt; wait_msec &lt;&lt; " msec" &lt;&lt; wait_msec &lt;&lt; " msec"
...@@ -852,8 +858,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -852,8 +858,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
&lt;&lt; wait_msec &lt;&lt; " мсек"; &lt;&lt; wait_msec &lt;&lt; " мсек";
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
std::abort(); return false;
// throw uniset::SystemError(err.str());
} }
if( !ui->waitWorking(_testID,wait_msec) ) if( !ui->waitWorking(_testID,wait_msec) )
...@@ -864,9 +869,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -864,9 +869,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
&lt;&lt; wait_msec &lt;&lt; " мсек"; &lt;&lt; wait_msec &lt;&lt; " мсек";
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
std::abort(); return false;
// throw uniset::SystemError(err.str());
} }
return true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string <xsl:value-of select="$CLASSNAME"/>_SK::help() const noexcept std::string <xsl:value-of select="$CLASSNAME"/>_SK::help() const noexcept
......
...@@ -331,7 +331,13 @@ namespace uniset ...@@ -331,7 +331,13 @@ namespace uniset
// set_signals(true); // set_signals(true);
UniXML::iterator it(confnode); UniXML::iterator it(confnode);
waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы if( !waitSM() ) // необходимо дождаться, чтобы нормально инициализировать итераторы
{
if( !cancelled )
uterminate();
return;
}
PassiveTimer pt(UniSetTimer::WaitUpTime); PassiveTimer pt(UniSetTimer::WaitUpTime);
...@@ -375,7 +381,7 @@ namespace uniset ...@@ -375,7 +381,7 @@ namespace uniset
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !activated && !cancelled && !ptAct.checkTime() )
{ {
cout << myname << "(execute): wait activate..." << endl; cout << myname << "(execute): wait activate..." << endl;
msleep(300); msleep(300);
...@@ -387,6 +393,9 @@ namespace uniset ...@@ -387,6 +393,9 @@ namespace uniset
} }
} }
if( cancelled )
return;
if( !activated ) if( !activated )
iocrit << myname << "(execute): ************* don`t activate?! ************" << endl; iocrit << myname << "(execute): ************* don`t activate?! ************" << endl;
...@@ -1345,7 +1354,7 @@ namespace uniset ...@@ -1345,7 +1354,7 @@ namespace uniset
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !cancelled && !activated && !ptAct.checkTime() )
{ {
ioinfo << myname << "(sysCommand): wait activate..." << endl; ioinfo << myname << "(sysCommand): wait activate..." << endl;
msleep(300); msleep(300);
...@@ -1354,6 +1363,9 @@ namespace uniset ...@@ -1354,6 +1363,9 @@ namespace uniset
break; break;
} }
if( cancelled )
return;
if( !activated ) if( !activated )
iocrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl; iocrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
...@@ -1419,11 +1431,15 @@ namespace uniset ...@@ -1419,11 +1431,15 @@ namespace uniset
if( force_out ) if( force_out )
return; return;
waitSM(); if( !waitSM() )
{
if( !cancelled )
uterminate();
}
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !readconf_ok && !ptAct.checkTime() ) while( !cancelled && !readconf_ok && !ptAct.checkTime() )
{ {
ioinfo << myname << "(askSensors): wait read configuration..." << endl; ioinfo << myname << "(askSensors): wait read configuration..." << endl;
msleep(50); msleep(50);
...@@ -1432,6 +1448,9 @@ namespace uniset ...@@ -1432,6 +1448,9 @@ namespace uniset
break; break;
} }
if( cancelled )
return;
if( !readconf_ok ) if( !readconf_ok )
iocrit << myname << "(askSensors): ************* don`t read configuration?! ************" << endl; iocrit << myname << "(askSensors): ************* don`t read configuration?! ************" << endl;
...@@ -1621,7 +1640,7 @@ namespace uniset ...@@ -1621,7 +1640,7 @@ namespace uniset
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IOControl::waitSM() bool IOControl::waitSM()
{ {
if( !shm->waitSMreadyWithCancellation(smReadyTimeout, cancelled, 50) ) if( !shm->waitSMreadyWithCancellation(smReadyTimeout, cancelled, 50) )
{ {
...@@ -1632,9 +1651,12 @@ namespace uniset ...@@ -1632,9 +1651,12 @@ namespace uniset
<< smReadyTimeout << " msec"; << smReadyTimeout << " msec";
iocrit << err.str() << endl; iocrit << err.str() << endl;
std::terminate();
} }
return false;
} }
return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IOControl::buildCardsList() void IOControl::buildCardsList()
......
...@@ -342,7 +342,7 @@ namespace uniset ...@@ -342,7 +342,7 @@ namespace uniset
bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec ); bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec );
void buildCardsList(); void buildCardsList();
void waitSM(); bool waitSM();
xmlNode* confnode = { 0 }; /*!< xml-узел в настроечном файле */ xmlNode* confnode = { 0 }; /*!< xml-узел в настроечном файле */
......
#!/bin/sh
ulimit -Sc 1000000
uniset2-start.sh -f ./uniset2-sqlite-dbserver --confile test.xml --name DBServer1 \
--ulog-add-levels info,crit,warn,level9,system \
--dbserver-buffer-size 100
...@@ -148,10 +148,11 @@ void PassiveLProcessor::sysCommand( const uniset::SystemMessage* sm ) ...@@ -148,10 +148,11 @@ void PassiveLProcessor::sysCommand( const uniset::SystemMessage* sm )
{ {
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
if( !shm->waitSMreadyWithCancellation(smReadyTimeout,cannceled) ) if( !shm->waitSMreadyWithCancellation(smReadyTimeout, cannceled) )
{ {
dcrit << myname << "(ERR): SM not ready. Terminated... " << endl; dcrit << myname << "(ERR): SM not ready. Terminated... " << endl;
std::terminate(); // std::terminate();
uterminate();
return; return;
} }
......
...@@ -300,7 +300,7 @@ namespace uniset ...@@ -300,7 +300,7 @@ namespace uniset
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::waitSMReady() bool MBExchange::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int tout = uniset_conf()->getArgInt("--" + prefix + "-sm-ready-timeout", ""); int tout = uniset_conf()->getArgInt("--" + prefix + "-sm-ready-timeout", "");
...@@ -318,9 +318,12 @@ namespace uniset ...@@ -318,9 +318,12 @@ namespace uniset
ostringstream err; ostringstream err;
err << myname << "(waitSMReady): failed waiting SharedMemory " << ready_timeout << " msec. ==> TERMINATE!"; err << myname << "(waitSMReady): failed waiting SharedMemory " << ready_timeout << " msec. ==> TERMINATE!";
mbcrit << err.str() << endl; mbcrit << err.str() << endl;
std::terminate();
} }
return false;
} }
return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::step() void MBExchange::step()
...@@ -348,7 +351,7 @@ namespace uniset ...@@ -348,7 +351,7 @@ namespace uniset
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool MBExchange::isProcActive() const bool MBExchange::isProcActive() const
{ {
return activated; return activated && !canceled;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::setProcActive( bool st ) void MBExchange::setProcActive( bool st )
...@@ -360,6 +363,10 @@ namespace uniset ...@@ -360,6 +363,10 @@ namespace uniset
{ {
setProcActive(false); setProcActive(false);
canceled = true; canceled = true;
if( logserv && logserv->isRunning() )
logserv->terminate();
return UniSetObject::deactivateObject(); return UniSetObject::deactivateObject();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -3015,8 +3022,8 @@ namespace uniset ...@@ -3015,8 +3022,8 @@ namespace uniset
if( devices.empty() ) if( devices.empty() )
{ {
mbcrit << myname << "(sysCommand): ************* ITEM MAP EMPTY! terminated... *************" << endl; mbcrit << myname << "(sysCommand): ************* ITEM MAP EMPTY! terminated... *************" << endl;
//raise(SIGTERM); // std::terminate();
std::terminate(); uterminate();
return; return;
} }
...@@ -3025,7 +3032,13 @@ namespace uniset ...@@ -3025,7 +3032,13 @@ namespace uniset
if( !shm->isLocalwork() ) if( !shm->isLocalwork() )
initDeviceList(); initDeviceList();
waitSMReady(); if( !waitSMReady() )
{
if( !canceled )
uterminate();
return;
}
// подождать пока пройдёт инициализация датчиков // подождать пока пройдёт инициализация датчиков
// см. activateObject() // см. activateObject()
...@@ -3042,7 +3055,11 @@ namespace uniset ...@@ -3042,7 +3055,11 @@ namespace uniset
} }
if( !isProcActive() ) if( !isProcActive() )
{
mbcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl; mbcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
uterminate();
return;
}
{ {
uniset::uniset_rwmutex_rlock l(mutex_start); uniset::uniset_rwmutex_rlock l(mutex_start);
...@@ -3116,8 +3133,8 @@ namespace uniset ...@@ -3116,8 +3133,8 @@ namespace uniset
<< activateTimeout << " мсек"; << activateTimeout << " мсек";
mbcrit << err.str() << endl; mbcrit << err.str() << endl;
std::terminate(); // прерываем (перезапускаем) процесс... // std::terminate(); // прерываем (перезапускаем) процесс...
// throw SystemError(err.str()); uterminate();
return; return;
} }
......
...@@ -303,7 +303,7 @@ namespace uniset ...@@ -303,7 +303,7 @@ namespace uniset
bool isProcActive() const; bool isProcActive() const;
void setProcActive( bool st ); void setProcActive( bool st );
void waitSMReady(); bool waitSMReady();
void readConfiguration(); void readConfiguration();
bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec ); bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec );
......
...@@ -82,20 +82,13 @@ MBTCPMaster::MBTCPMaster(uniset::ObjectId objId, uniset::ObjectId shmId, ...@@ -82,20 +82,13 @@ MBTCPMaster::MBTCPMaster(uniset::ObjectId objId, uniset::ObjectId shmId,
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
MBTCPMaster::~MBTCPMaster() MBTCPMaster::~MBTCPMaster()
{ {
if( pollThread ) if( pollThread && !canceled )
{
try
{ {
pollThread->stop(); canceled = true;
if( pollThread->isRunning() ) if( pollThread->isRunning() )
pollThread->join(); pollThread->join();
} }
catch( Poco::NullPointerException& ex )
{
}
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen ) std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen )
...@@ -149,16 +142,20 @@ void MBTCPMaster::sysCommand( const uniset::SystemMessage* sm ) ...@@ -149,16 +142,20 @@ void MBTCPMaster::sysCommand( const uniset::SystemMessage* sm )
void MBTCPMaster::final_thread() void MBTCPMaster::final_thread()
{ {
setProcActive(false); setProcActive(false);
canceled = true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBTCPMaster::poll_thread() void MBTCPMaster::poll_thread()
{ {
// ждём начала работы..(см. MBExchange::activateObject) // ждём начала работы..(см. MBExchange::activateObject)
while( !isProcActive() ) while( !isProcActive() && !canceled )
{ {
uniset::uniset_rwmutex_rlock l(mutex_start); uniset::uniset_rwmutex_rlock l(mutex_start);
} }
// if( canceled )
// return;
// работаем // работаем
while( isProcActive() ) while( isProcActive() )
{ {
...@@ -187,18 +184,20 @@ void MBTCPMaster::poll_thread() ...@@ -187,18 +184,20 @@ void MBTCPMaster::poll_thread()
msleep(polltime); msleep(polltime);
} }
dinfo << myname << "(poll_thread): thread finished.." << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool MBTCPMaster::deactivateObject() bool MBTCPMaster::deactivateObject()
{ {
setProcActive(false); setProcActive(false);
canceled = true;
if( pollThread ) if( pollThread )
{ {
pollThread->stop();
if( pollThread->isRunning() ) if( pollThread->isRunning() )
pollThread->join(); pollThread->join();
} }
return MBExchange::deactivateObject(); return MBExchange::deactivateObject();
......
...@@ -206,20 +206,11 @@ MBTCPMultiMaster::MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shm ...@@ -206,20 +206,11 @@ MBTCPMultiMaster::MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shm
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
MBTCPMultiMaster::~MBTCPMultiMaster() MBTCPMultiMaster::~MBTCPMultiMaster()
{ {
if( pollThread ) if( pollThread && !canceled )
{
try
{ {
pollThread->stop();
if( pollThread->isRunning() ) if( pollThread->isRunning() )
pollThread->join(); pollThread->join();
} }
catch( Poco::NullPointerException& ex )
{
}
}
if( checkThread ) if( checkThread )
{ {
...@@ -352,6 +343,7 @@ std::shared_ptr<ModbusClient> MBTCPMultiMaster::initMB( bool reopen ) ...@@ -352,6 +343,7 @@ std::shared_ptr<ModbusClient> MBTCPMultiMaster::initMB( bool reopen )
void MBTCPMultiMaster::final_thread() void MBTCPMultiMaster::final_thread()
{ {
setProcActive(false); setProcActive(false);
canceled = true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -471,7 +463,7 @@ void MBTCPMultiMaster::sysCommand( const uniset::SystemMessage* sm ) ...@@ -471,7 +463,7 @@ void MBTCPMultiMaster::sysCommand( const uniset::SystemMessage* sm )
void MBTCPMultiMaster::poll_thread() void MBTCPMultiMaster::poll_thread()
{ {
// ждём начала работы..(см. MBExchange::activateObject) // ждём начала работы..(см. MBExchange::activateObject)
while( !isProcActive() ) while( !isProcActive() && !canceled )
{ {
uniset::uniset_rwmutex_rlock l(mutex_start); uniset::uniset_rwmutex_rlock l(mutex_start);
} }
...@@ -590,6 +582,7 @@ void MBTCPMultiMaster::initIterators() ...@@ -590,6 +582,7 @@ void MBTCPMultiMaster::initIterators()
bool MBTCPMultiMaster::deactivateObject() bool MBTCPMultiMaster::deactivateObject()
{ {
setProcActive(false); setProcActive(false);
canceled = true;
if( pollThread ) if( pollThread )
{ {
......
...@@ -63,14 +63,12 @@ int main( int argc, const char** argv ) ...@@ -63,14 +63,12 @@ int main( int argc, const char** argv )
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
dcrit << "(mbtcpmaster): " << ex << std::endl; cerr << "(mbtcpmaster): " << ex << std::endl;
} }
catch(...) catch(...)
{ {
std::exception_ptr p = std::current_exception(); std::exception_ptr p = std::current_exception();
std::clog << (p ? p.__cxa_exception_type()->name() : "null") << std::endl; cerr << "(mbtcpmaster): catch.." << (p ? p.__cxa_exception_type()->name() : "null") << std::endl;
dcrit << "(mbtcpmaster): catch ..." << std::endl;
} }
return 1; return 1;
......
...@@ -537,7 +537,7 @@ namespace uniset ...@@ -537,7 +537,7 @@ namespace uniset
cancelled = true; cancelled = true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBSlave::waitSMReady() bool MBSlave::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int tout = uniset_conf()->getArgInt("--" + prefix + "-sm-ready-timeout", ""); int tout = uniset_conf()->getArgInt("--" + prefix + "-sm-ready-timeout", "");
...@@ -555,10 +555,12 @@ namespace uniset ...@@ -555,10 +555,12 @@ namespace uniset
ostringstream err; ostringstream err;
err << myname << "(waitSMReady): Не дождались готовности SharedMemory к работе в течение " << ready_timeout << " мсек"; err << myname << "(waitSMReady): Не дождались готовности SharedMemory к работе в течение " << ready_timeout << " мсек";
mbcrit << err.str() << endl; mbcrit << err.str() << endl;
//terminate();
std::terminate();
} }
return false;
} }
return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBSlave::execute_rtu() void MBSlave::execute_rtu()
...@@ -571,15 +573,18 @@ namespace uniset ...@@ -571,15 +573,18 @@ namespace uniset
{ {
std::unique_lock<std::mutex> locker(mutexStartNotify); std::unique_lock<std::mutex> locker(mutexStartNotify);
while( !activated ) while( !activated && !cancelled )
startNotifyEvent.wait(locker); startNotifyEvent.wait(locker);
if( cancelled )
return;
} }
if( vaddr.empty() ) if( vaddr.empty() )
{ {
mbcrit << "(execute_rtu): Unknown my modbus addresses!" << endl; mbcrit << "(execute_rtu): Unknown my modbus addresses!" << endl;
//raise(SIGTERM); //std::terminate();
std::terminate(); uterminate();
return; return;
} }
...@@ -618,8 +623,8 @@ namespace uniset ...@@ -618,8 +623,8 @@ namespace uniset
if( !tcpserver ) if( !tcpserver )
{ {
mbcrit << myname << "(execute_tcp): DYNAMIC CAST ERROR (mbslot --> ModbusTCPServerSlot)" << std::endl; mbcrit << myname << "(execute_tcp): DYNAMIC CAST ERROR (mbslot --> ModbusTCPServerSlot)" << std::endl;
//raise(SIGTERM); // std::terminate();
std::terminate(); uterminate();
return; return;
} }
...@@ -641,8 +646,8 @@ namespace uniset ...@@ -641,8 +646,8 @@ namespace uniset
if( vaddr.empty() ) if( vaddr.empty() )
{ {
mbcrit << "(execute_tcp): Unknown my modbus addresses!" << endl; mbcrit << "(execute_tcp): Unknown my modbus addresses!" << endl;
//raise(SIGTERM); // std::terminate();
std::terminate(); uterminate();
return; return;
} }
...@@ -682,7 +687,8 @@ namespace uniset ...@@ -682,7 +687,8 @@ namespace uniset
mbcrit << myname << "(execute_tcp): error run tcpserver: " mbcrit << myname << "(execute_tcp): error run tcpserver: "
<< tcpserver->getInetAddress() << tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << " err: not active.." << endl; << ":" << tcpserver->getInetPort() << " err: not active.." << endl;
std::terminate(); // std::terminate();
uterminate();
return; return;
} }
} }
...@@ -942,8 +948,8 @@ namespace uniset ...@@ -942,8 +948,8 @@ namespace uniset
if( iomap.empty() ) if( iomap.empty() )
{ {
mbcrit << myname << "(sysCommand): iomap EMPTY! terminated..." << endl; mbcrit << myname << "(sysCommand): iomap EMPTY! terminated..." << endl;
// raise(SIGTERM); // std::terminate();
std::terminate(); uterminate();
return; return;
} }
...@@ -953,14 +959,20 @@ namespace uniset ...@@ -953,14 +959,20 @@ namespace uniset
logserv->async_run(logserv_host, logserv_port); logserv->async_run(logserv_host, logserv_port);
} }
waitSMReady(); if( !waitSMReady() )
{
if( !cancelled )
uterminate();
return;
}
// подождать пока пройдёт инициализация датчиков // подождать пока пройдёт инициализация датчиков
// см. activateObject() // см. activateObject()
msleep(initPause); msleep(initPause);
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !cancelled && !activated && !ptAct.checkTime() )
{ {
cout << myname << "(sysCommand): wait activate..." << endl; cout << myname << "(sysCommand): wait activate..." << endl;
msleep(300); msleep(300);
...@@ -969,6 +981,9 @@ namespace uniset ...@@ -969,6 +981,9 @@ namespace uniset
break; break;
} }
if( cancelled )
return;
if( !activated ) if( !activated )
{ {
mbcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl; mbcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
...@@ -1170,6 +1185,9 @@ namespace uniset ...@@ -1170,6 +1185,9 @@ namespace uniset
{ {
if( mbslot ) if( mbslot )
mbslot->terminate(); mbslot->terminate();
if( thr )
thr->join();
} }
catch( std::exception& ex) catch( std::exception& ex)
{ {
...@@ -1177,6 +1195,9 @@ namespace uniset ...@@ -1177,6 +1195,9 @@ namespace uniset
} }
} }
if( logserv && logserv->isRunning() )
logserv->terminate();
return UniSetObject::deactivateObject(); return UniSetObject::deactivateObject();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -1527,7 +1548,6 @@ namespace uniset ...@@ -1527,7 +1548,6 @@ namespace uniset
cout << "--prefix-filter-value val - Считывать список опрашиваемых датчиков, только у которых field=value" << endl; cout << "--prefix-filter-value val - Считывать список опрашиваемых датчиков, только у которых field=value" << endl;
cout << "--prefix-heartbeat-id - Данный процесс связан с указанным аналоговым heartbeat-дачиком." << endl; cout << "--prefix-heartbeat-id - Данный процесс связан с указанным аналоговым heartbeat-дачиком." << endl;
cout << "--prefix-heartbeat-max - Максимальное значение heartbeat-счётчика для данного процесса. По умолчанию 10." << endl; cout << "--prefix-heartbeat-max - Максимальное значение heartbeat-счётчика для данного процесса. По умолчанию 10." << endl;
cout << "--prefix-ready-timeout - Время ожидания готовности SM к работе, мсек. (-1 - ждать 'вечно')" << endl;
cout << "--prefix-initPause - Задержка перед инициализацией (время на активизация процесса)" << endl; cout << "--prefix-initPause - Задержка перед инициализацией (время на активизация процесса)" << endl;
cout << "--prefix-force 1 - Читать данные из SM каждый раз, а не по изменению." << endl; cout << "--prefix-force 1 - Читать данные из SM каждый раз, а не по изменению." << endl;
cout << "--prefix-respond-id - respond sensor id" << endl; cout << "--prefix-respond-id - respond sensor id" << endl;
......
...@@ -502,7 +502,7 @@ namespace uniset ...@@ -502,7 +502,7 @@ namespace uniset
virtual void sensorInfo( const uniset::SensorMessage* sm ) override; virtual void sensorInfo( const uniset::SensorMessage* sm ) override;
virtual void timerInfo( const uniset::TimerMessage* tm ) override; virtual void timerInfo( const uniset::TimerMessage* tm ) override;
void askSensors( UniversalIO::UIOCommand cmd ); void askSensors( UniversalIO::UIOCommand cmd );
void waitSMReady(); bool waitSMReady();
virtual void execute_rtu(); virtual void execute_rtu();
virtual void execute_tcp(); virtual void execute_tcp();
virtual void updateStatistics(); virtual void updateStatistics();
......
...@@ -80,21 +80,15 @@ int main(int argc, const char** argv) ...@@ -80,21 +80,15 @@ int main(int argc, const char** argv)
// on_sigchild(SIGTERM); // on_sigchild(SIGTERM);
return 0; return 0;
} }
catch( const SystemError& err )
{
dcrit << "(mbslave): " << err << endl;
}
catch( const uniset::Exception& ex )
{
dcrit << "(mbslave): " << ex << endl;
}
catch( const std::exception& e ) catch( const std::exception& e )
{ {
dcrit << "(mbslave): " << e.what() << endl; cerr << "(mbslave): " << e.what() << endl;
} }
catch(...) catch(...)
{ {
dcrit << "(mbslave): catch(...)" << endl; cerr << "(mbslave): catch(...)" << endl;
std::exception_ptr p = std::current_exception();
cerr << (p ? p.__cxa_exception_type()->name() : "null") << std::endl;
} }
// on_sigchild(SIGTERM); // on_sigchild(SIGTERM);
......
...@@ -330,7 +330,11 @@ void RRDServer::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -330,7 +330,11 @@ void RRDServer::askSensors( UniversalIO::UIOCommand cmd )
UObject_SK::askSensors(cmd); UObject_SK::askSensors(cmd);
// прежде чем заказывать датчики, надо убедиться что SM доступна // прежде чем заказывать датчики, надо убедиться что SM доступна
waitSM(smReadyTimeout); if( !waitSM(smReadyTimeout) )
{
uterminate();
return;
}
for( const auto& it : rrdlist ) for( const auto& it : rrdlist )
{ {
......
...@@ -261,16 +261,21 @@ namespace uniset ...@@ -261,16 +261,21 @@ namespace uniset
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !cancelled && !activated && !ptAct.checkTime() )
{ {
cout << myname << "(sysCommand): wait activate..." << endl; cout << myname << "(sysCommand): wait activate..." << endl;
msleep(100); msleep(100);
} }
if( cancelled )
return;
if( !activated ) if( !activated )
{ {
smcrit << myname << "(sysCommand): Don`t activate [timeout=" << activateTimeout << " msec]! TERMINATE.." << endl; smcrit << myname << "(sysCommand): Don`t activate [timeout=" << activateTimeout << " msec]! TERMINATE.." << endl;
std::terminate(); // std::terminate();
uterminate();
return;
} }
// подождать пока пройдёт инициализация // подождать пока пройдёт инициализация
...@@ -306,6 +311,7 @@ namespace uniset ...@@ -306,6 +311,7 @@ namespace uniset
bool SharedMemory::deactivateObject() bool SharedMemory::deactivateObject()
{ {
workready = false; workready = false;
cancelled = true;
if( logserv && logserv->isRunning() ) if( logserv && logserv->isRunning() )
logserv->terminate(); logserv->terminate();
...@@ -904,9 +910,9 @@ namespace uniset ...@@ -904,9 +910,9 @@ namespace uniset
ostringstream err; ostringstream err;
err << myname << "(initFromReserv): Not found ID for '" << smName << "'"; err << myname << "(initFromReserv): Not found ID for '" << smName << "'";
smcrit << err.str() << endl; smcrit << err.str() << endl;
// throw SystemError(err.str()); // std::terminate();
//raise(SIGTERM); uterminate();
std::terminate(); return;
} }
std::string smNode(it.getProp("node")); std::string smNode(it.getProp("node"));
...@@ -921,9 +927,9 @@ namespace uniset ...@@ -921,9 +927,9 @@ namespace uniset
ostringstream err; ostringstream err;
err << myname << "(initFromReserv): Not found NodeID for '" << smNode << "'"; err << myname << "(initFromReserv): Not found NodeID for '" << smNode << "'";
smcrit << err.str() << endl; smcrit << err.str() << endl;
// throw SystemError(err.str()); //std::terminate();
//raise(SIGTERM); uterminate();
std::terminate(); return;
} }
......
...@@ -487,8 +487,9 @@ namespace uniset ...@@ -487,8 +487,9 @@ namespace uniset
typedef std::list<HeartBeatInfo> HeartBeatList; typedef std::list<HeartBeatInfo> HeartBeatList;
HeartBeatList hblist; // список датчиков "сердцебиения" HeartBeatList hblist; // список датчиков "сердцебиения"
std::shared_ptr<WDTInterface> wdt; std::shared_ptr<WDTInterface> wdt;
std::atomic_bool activated; std::atomic_bool activated = { false };
std::atomic_bool workready; std::atomic_bool workready = { false };
std::atomic_bool cancelled = { false };
typedef std::list<uniset::ObjectId> EventList; typedef std::list<uniset::ObjectId> EventList;
EventList elst; EventList elst;
......
...@@ -475,7 +475,7 @@ void UNetExchange::startReceivers() ...@@ -475,7 +475,7 @@ void UNetExchange::startReceivers()
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetExchange::waitSMReady() bool UNetExchange::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int tout = uniset_conf()->getArgPInt("--unet-sm-ready-timeout", "", uniset_conf()->getNCReadyTimeout()); int tout = uniset_conf()->getArgPInt("--unet-sm-ready-timeout", "", uniset_conf()->getNCReadyTimeout());
...@@ -487,16 +487,19 @@ void UNetExchange::waitSMReady() ...@@ -487,16 +487,19 @@ void UNetExchange::waitSMReady()
else if( tout < 0 ) else if( tout < 0 )
ready_timeout = UniSetTimer::WaitUpTime; ready_timeout = UniSetTimer::WaitUpTime;
if( !shm->waitSMreadyWithCancellation(ready_timeout, cannceled, 50) ) if( !shm->waitSMreadyWithCancellation(ready_timeout, cancelled, 50) )
{ {
if( !cannceled ) if( !cancelled )
{ {
ostringstream err; ostringstream err;
err << myname << "(waitSMReady): Не дождались готовности SharedMemory к работе в течение " << ready_timeout << " мсек"; err << myname << "(waitSMReady): Не дождались готовности SharedMemory к работе в течение " << ready_timeout << " мсек";
unetcrit << err.str() << endl; unetcrit << err.str() << endl;
std::terminate();
} }
return false;
} }
return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetExchange::timerInfo( const TimerMessage* tm ) void UNetExchange::timerInfo( const TimerMessage* tm )
...@@ -612,14 +615,23 @@ void UNetExchange::sysCommand( const uniset::SystemMessage* sm ) ...@@ -612,14 +615,23 @@ void UNetExchange::sysCommand( const uniset::SystemMessage* sm )
} }
} }
waitSMReady(); if( !waitSMReady() )
{
if( !cancelled )
{
// std::terminate();
uterminate();
}
return;
}
// подождать пока пройдёт инициализация датчиков // подождать пока пройдёт инициализация датчиков
// см. activateObject() // см. activateObject()
msleep(initPause); msleep(initPause);
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !cancelled && !activated && !ptAct.checkTime() )
{ {
cout << myname << "(sysCommand): wait activate..." << endl; cout << myname << "(sysCommand): wait activate..." << endl;
msleep(300); msleep(300);
...@@ -628,6 +640,9 @@ void UNetExchange::sysCommand( const uniset::SystemMessage* sm ) ...@@ -628,6 +640,9 @@ void UNetExchange::sysCommand( const uniset::SystemMessage* sm )
break; break;
} }
if( cancelled )
return;
if( !activated ) if( !activated )
unetcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl; unetcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
...@@ -736,7 +751,8 @@ bool UNetExchange::activateObject() ...@@ -736,7 +751,8 @@ bool UNetExchange::activateObject()
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool UNetExchange::deactivateObject() bool UNetExchange::deactivateObject()
{ {
cannceled = true; cancelled = true;
if( activated ) if( activated )
{ {
unetinfo << myname << "(deactivateObject): disactivate.." << endl; unetinfo << myname << "(deactivateObject): disactivate.." << endl;
......
...@@ -162,7 +162,7 @@ namespace uniset ...@@ -162,7 +162,7 @@ namespace uniset
void sensorInfo( const uniset::SensorMessage* sm ) override; void sensorInfo( const uniset::SensorMessage* sm ) override;
void timerInfo( const uniset::TimerMessage* tm ) override; void timerInfo( const uniset::TimerMessage* tm ) override;
void askSensors( UniversalIO::UIOCommand cmd ); void askSensors( UniversalIO::UIOCommand cmd );
void waitSMReady(); bool waitSMReady();
void receiverEvent( const std::shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev ) noexcept; void receiverEvent( const std::shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev ) noexcept;
virtual bool activateObject() override; virtual bool activateObject() override;
...@@ -194,7 +194,7 @@ namespace uniset ...@@ -194,7 +194,7 @@ namespace uniset
timeout_t steptime = { 1000 }; /*!< периодичность вызова step, [мсек] */ timeout_t steptime = { 1000 }; /*!< периодичность вызова step, [мсек] */
std::atomic_bool activated = { false }; std::atomic_bool activated = { false };
std::atomic_bool cannceled = { false }; std::atomic_bool cancelled = { false };
timeout_t activateTimeout = { 20000 }; // msec timeout_t activateTimeout = { 20000 }; // msec
struct ReceiverInfo struct ReceiverInfo
......
...@@ -443,7 +443,6 @@ namespace uniset ...@@ -443,7 +443,6 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP DIGITAL DATA LIMIT! max=" << "(readItem): OVERFLOW! MAX UDP DIGITAL DATA LIMIT! max="
<< UniSetUDP::MaxDCount << endl; << UniSetUDP::MaxDCount << endl;
// raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
...@@ -482,7 +481,6 @@ namespace uniset ...@@ -482,7 +481,6 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP ANALOG DATA LIMIT! max=" << "(readItem): OVERFLOW! MAX UDP ANALOG DATA LIMIT! max="
<< UniSetUDP::MaxACount << endl; << UniSetUDP::MaxACount << endl;
// raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
...@@ -495,7 +493,6 @@ namespace uniset ...@@ -495,7 +493,6 @@ namespace uniset
{ {
unetcrit << myname unetcrit << myname
<< "(readItem): Sensor (" << p.id << ")" << sname << " ALREADY ADDED!! ABORT!" << endl; << "(readItem): Sensor (" << p.id << ")" << sname << " ALREADY ADDED!! ABORT!" << endl;
// raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
......
...@@ -145,7 +145,7 @@ UniExchange::~UniExchange() ...@@ -145,7 +145,7 @@ UniExchange::~UniExchange()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UniExchange::execute() void UniExchange::execute()
{ {
if( !shm->waitSMreadyWithCancellation(smReadyTimeout, canncelled, 50) ) if( !shm->waitSMreadyWithCancellation(smReadyTimeout, cancelled, 50) )
{ {
ostringstream err; ostringstream err;
err << myname << "(execute): Не дождались готовности SharedMemory к работе в течение " err << myname << "(execute): Не дождались готовности SharedMemory к работе в течение "
...@@ -153,7 +153,9 @@ void UniExchange::execute() ...@@ -153,7 +153,9 @@ void UniExchange::execute()
ucrit << err.str() << endl; ucrit << err.str() << endl;
//throw SystemError(err.str()); //throw SystemError(err.str());
std::terminate(); //std::terminate();
uterminate();
return;
} }
PassiveTimer pt(UniSetTimer::WaitUpTime); PassiveTimer pt(UniSetTimer::WaitUpTime);
...@@ -169,10 +171,13 @@ void UniExchange::execute() ...@@ -169,10 +171,13 @@ void UniExchange::execute()
initIterators(); initIterators();
init_ok = true; init_ok = true;
while(1) while( !cancelled )
{ {
for( auto& it : nlst ) for( auto& it : nlst )
{ {
if( cancelled )
break;
bool ok = false; bool ok = false;
try try
...@@ -330,7 +335,7 @@ void UniExchange::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -330,7 +335,7 @@ void UniExchange::askSensors( UniversalIO::UIOCommand cmd )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UniExchange::deactivateObject() bool UniExchange::deactivateObject()
{ {
canncelled = true; cancelled = true;
return IOController::deactivateObject(); return IOController::deactivateObject();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -144,7 +144,7 @@ namespace uniset ...@@ -144,7 +144,7 @@ namespace uniset
size_t maxIndex = { 0 }; size_t maxIndex = { 0 };
timeout_t smReadyTimeout = { 60000 }; // msec timeout_t smReadyTimeout = { 60000 }; // msec
std::atomic_bool canncelled = { false }; std::atomic_bool cancelled = { false };
private: private:
}; };
......
...@@ -130,7 +130,7 @@ namespace uniset ...@@ -130,7 +130,7 @@ namespace uniset
Если range=false, то может быть возвращено значение outOfRange. Если range=false, то может быть возвращено значение outOfRange.
*/ */
long getRawValue( const long cal, bool range = false ); long getRawValue( const long cal, bool range = false ) const;
/*! Возвращает минимальное значение 'y' встретившееся в диаграмме */ /*! Возвращает минимальное значение 'y' встретившееся в диаграмме */
inline long getMinRaw() const noexcept inline long getMinRaw() const noexcept
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2017-08-31+03:00 // generate timestamp: 2017-09-01+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 uniset::UniSetObject public uniset::UniSetObject
{ {
public: public:
UObject_SK( uniset::ObjectId id, xmlNode* node=uniset::uniset_conf()->getNode("UObject"), const std::string& argprefix="" ); UObject_SK( uniset::ObjectId id, xmlNode* node = uniset::uniset_conf()->getNode("UObject"), const std::string& argprefix = "" );
UObject_SK(); UObject_SK();
virtual ~UObject_SK(); virtual ~UObject_SK();
...@@ -43,54 +43,60 @@ class UObject_SK: ...@@ -43,54 +43,60 @@ class UObject_SK:
virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept; virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept;
inline std::shared_ptr<DebugStream> log() noexcept { return mylog; } inline std::shared_ptr<DebugStream> log() noexcept
inline std::shared_ptr<uniset::LogAgregator> logAgregator() noexcept { return loga; } {
return mylog;
}
inline std::shared_ptr<uniset::LogAgregator> logAgregator() noexcept
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ) noexcept; 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
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
...@@ -107,16 +113,19 @@ class UObject_SK: ...@@ -107,16 +113,19 @@ class UObject_SK:
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string str( uniset::ObjectId id, bool showLinkName=true ) const; std::string str( uniset::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( uniset::ObjectId id, bool showLinkName=true ) const; std::string strval( uniset::ObjectId id, bool showLinkName = true ) const;
/*! Вывод состояния внутренних переменных */ /*! Вывод состояния внутренних переменных */
inline std::string dumpVars(){ return vmon.pretty_str(); } inline std::string dumpVars()
{
return vmon.pretty_str();
}
// ------------------------------------------------------------ // ------------------------------------------------------------
std::string help() const noexcept; std::string help() const noexcept;
...@@ -152,23 +161,29 @@ class UObject_SK: ...@@ -152,23 +161,29 @@ class UObject_SK:
virtual void callback() noexcept override; virtual void callback() noexcept override;
virtual void processingMessage( const uniset::VoidMessage* msg ) override; virtual void processingMessage( const uniset::VoidMessage* msg ) override;
virtual void sysCommand( const uniset::SystemMessage* sm ){}; virtual void sysCommand( const uniset::SystemMessage* sm ) {};
virtual void askSensors( UniversalIO::UIOCommand cmd ){} virtual void askSensors( UniversalIO::UIOCommand cmd ) {}
virtual void sensorInfo( const uniset::SensorMessage* sm ) override{} virtual void sensorInfo( const uniset::SensorMessage* sm ) override {}
virtual void timerInfo( const uniset::TimerMessage* tm ) override{} virtual void timerInfo( const uniset::TimerMessage* tm ) override {}
virtual bool activateObject() override; virtual bool activateObject() override;
virtual bool deactivateObject() override; virtual bool deactivateObject() override;
virtual std::string getMonitInfo() const { return ""; } /*!< пользовательская информация выводимая в getInfo() */ virtual std::string getMonitInfo() const
virtual std::string getTypeOfMessage( int t ) const { return uniset::strTypeOfMessage(t); } /*!< получение названия типа сообщения. Используется в getInfo() */ {
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
virtual std::string getTypeOfMessage( int t ) const
{
return uniset::strTypeOfMessage(t); /*!< получение названия типа сообщения. Используется в getInfo() */
}
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
virtual void httpGetUserData( Poco::JSON::Object::Ptr& jdata ){} /*!< для пользовательских данных в httpGet() */ virtual void httpGetUserData( Poco::JSON::Object::Ptr& jdata ) {} /*!< для пользовательских данных в httpGet() */
virtual Poco::JSON::Object::Ptr httpDumpIO(); virtual Poco::JSON::Object::Ptr httpDumpIO();
virtual Poco::JSON::Object::Ptr httpRequestLog( const Poco::URI::QueryParameters& p ); virtual Poco::JSON::Object::Ptr httpRequestLog( const Poco::URI::QueryParameters& p );
#endif #endif
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step(){} virtual void step() {}
void preAskSensors( UniversalIO::UIOCommand cmd ); void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const uniset::SystemMessage* sm ); void preSysCommand( const uniset::SystemMessage* sm );
...@@ -176,7 +191,7 @@ class UObject_SK: ...@@ -176,7 +191,7 @@ class UObject_SK:
virtual void testMode( bool state ); virtual void testMode( bool state );
void updateOutputs( bool force ); void updateOutputs( bool force );
void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId ); bool waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId );
uniset::ObjectId getSMTestID() const; uniset::ObjectId getSMTestID() const;
void resetMsg(); void resetMsg();
...@@ -197,9 +212,15 @@ class UObject_SK: ...@@ -197,9 +212,15 @@ class UObject_SK:
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) { return uniset::uniset_conf()->getIntProp(confnode, name); } int getIntProp(const std::string& name)
{
return uniset::uniset_conf()->getIntProp(confnode, name);
}
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) { return uniset::uniset_conf()->getProp(confnode, name); } inline const std::string getProp(const std::string& name)
{
return uniset::uniset_conf()->getProp(confnode, name);
}
uniset::timeout_t smReadyTimeout; /*!< время ожидания готовности SM */ uniset::timeout_t smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated = { false }; std::atomic_bool activated = { false };
...@@ -251,10 +272,10 @@ class UObject_SK: ...@@ -251,10 +272,10 @@ class UObject_SK:
} }
}; };
std::unordered_map<const uniset::ObjectId,size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */ std::unordered_map<const uniset::ObjectId, size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */
size_t processingMessageCatchCount = { 0 }; /*!< количество исключений пойманных в processingMessage */ size_t processingMessageCatchCount = { 0 }; /*!< количество исключений пойманных в processingMessage */
std::unordered_map<long,size_t> msgTypeStat; /*!< количество сообщений по типам */ std::unordered_map<long, size_t> msgTypeStat; /*!< количество сообщений по типам */
std::string ostate = { "" }; /*!< состояние процесса (выводится в getInfo()) */ std::string ostate = { "" }; /*!< состояние процесса (выводится в getInfo()) */
......
...@@ -346,7 +346,7 @@ namespace uniset ...@@ -346,7 +346,7 @@ namespace uniset
sort(cache.begin(), cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< ) sort(cache.begin(), cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
long Calibration::getRawValue( const long cal, bool range ) long Calibration::getRawValue( const long cal, bool range ) const
{ {
for( auto& it : pvec ) for( auto& it : pvec )
{ {
......
...@@ -274,7 +274,7 @@ using namespace uniset; ...@@ -274,7 +274,7 @@ using namespace uniset;
bool SMInterface::waitSMready( int ready_timeout, int pmsec ) bool SMInterface::waitSMready( int ready_timeout, int pmsec )
{ {
std::atomic_bool cancelFlag = { false }; std::atomic_bool cancelFlag = { false };
return waitSMreadyWithCancellation(ready_timeout,cancelFlag,pmsec); return waitSMreadyWithCancellation(ready_timeout, cancelFlag, pmsec);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
bool SMInterface::waitSMworking( uniset::ObjectId sid, int msec, int pmsec ) bool SMInterface::waitSMworking( uniset::ObjectId sid, int msec, int pmsec )
......
...@@ -43,7 +43,7 @@ namespace uniset ...@@ -43,7 +43,7 @@ namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер /*! \page pgLogServer Лог сервер
Лог сервер предназначен для возможности удалённого чтения логов (DebugStream). Лог сервер предназначен для возможности удалённого чтения логов (DebugStream).
Ему указывается host и port для прослушивания запросов, которые можно делать при помощи Ему указывается host и port на котором он отвечает, подключаться можно при помощи
LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession). LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession).
При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов, При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов,
записью, отключением записи или ротацией файла с логами. DebugStream за которым ведётся "слежение" записью, отключением записи или ротацией файла с логами. DebugStream за которым ведётся "слежение"
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#include <string> #include <string>
#include <memory> #include <memory>
#include <mutex>
#include <Poco/RWLock.h> #include <Poco/RWLock.h>
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
namespace uniset namespace uniset
......
...@@ -51,14 +51,6 @@ namespace uniset ...@@ -51,14 +51,6 @@ namespace uniset
//! Функция выделения имени из полного имени //! Функция выделения имени из полного имени
const std::string getShortName(const std::string& fullName, const std::string& brk = "/"); const std::string getShortName(const std::string& fullName, const std::string& brk = "/");
//! Проверка на наличие недопустимых символов
char checkBadSymbols(const std::string& str);
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
std::string BadSymbolsToStr();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
......
...@@ -25,11 +25,9 @@ ...@@ -25,11 +25,9 @@
#include <deque> #include <deque>
#include <memory> #include <memory>
#include <omniORB4/CORBA.h> #include <omniORB4/CORBA.h>
#include <ev++.h>
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "UniSetObject.h" #include "UniSetObject.h"
#include "UniSetManager.h" #include "UniSetManager.h"
#include "EventLoopServer.h"
#include "OmniThreadCreator.h" #include "OmniThreadCreator.h"
#include "UHttpRequestHandler.h" #include "UHttpRequestHandler.h"
#include "UHttpServer.h" #include "UHttpServer.h"
...@@ -52,15 +50,14 @@ namespace uniset ...@@ -52,15 +50,14 @@ namespace uniset
\endcode \endcode
* Активатор в свою очередь сам является менеджером(и объектом) и обладает всеми его свойствами * Активатор в свою очередь сам является менеджером(и объектом) и обладает всеми его свойствами
* *
* --uniset-no-use-gdb-for-stacktrace - НЕ ИСПОЛЬЗОВАТЬ gdb для stacktrace
* --uniset-abort-script - скрипт запускаемый при вылете, в качестве аргумента передаётся имя программы и pid
*
* \section act_HttpAPI REST API * \section act_HttpAPI REST API
* UniSetActivator реализует обработку команд /conf/.. * UniSetActivator выступает в роли http-сервера и релизует первчиную обработку запросов
* и перенаправление их указанным объектам. Помимо этого UniSetActivator реализует обработку команд /conf/..
* Для запуска http-сервера необходимо в аргументах командной строки указать --activator-run-httpserver
* Помимо этого можно задать параметры --activator-httpserver-host и --activator-httpserver-port.
* *
*/ */
class UniSetActivator: class UniSetActivator:
public EventLoopServer,
public UniSetManager public UniSetManager
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
, public uniset::UHttp::IHttpRequestRegistry , public uniset::UHttp::IHttpRequestRegistry
...@@ -72,8 +69,15 @@ namespace uniset ...@@ -72,8 +69,15 @@ namespace uniset
virtual ~UniSetActivator(); virtual ~UniSetActivator();
// запуск системы
// async = true - асинхронный запуск (создаётся отдельный поток).
void run( bool async ); void run( bool async );
void stop();
// штатное завершение работы
void shutdown();
// прерывание работы
void terminate();
virtual uniset::ObjectType getType() override virtual uniset::ObjectType getType() override
{ {
...@@ -91,7 +95,7 @@ namespace uniset ...@@ -91,7 +95,7 @@ namespace uniset
protected: protected:
virtual void work(); void work();
// уносим в protected, т.к. Activator должен быть только один.. // уносим в protected, т.к. Activator должен быть только один..
UniSetActivator(); UniSetActivator();
...@@ -101,19 +105,12 @@ namespace uniset ...@@ -101,19 +105,12 @@ namespace uniset
private: private:
void init(); void init();
static void on_finish_timeout(); static void on_finish_timeout();
static void evsignal( ev::sig& signal, int signo ); static void set_signals( bool set );
virtual void evprepare() override;
virtual void evfinish() override;
std::shared_ptr< OmniThreadCreator<UniSetActivator> > orbthr; std::shared_ptr< OmniThreadCreator<UniSetActivator> > orbthr;
CORBA::ORB_var orb; CORBA::ORB_var orb;
ev::sig sigINT;
ev::sig sigTERM;
ev::sig sigABRT;
ev::sig sigQUIT;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
std::shared_ptr<uniset::UHttp::UHttpServer> httpserv; std::shared_ptr<uniset::UHttp::UHttpServer> httpserv;
std::string httpHost = { "" }; std::string httpHost = { "" };
......
...@@ -63,8 +63,6 @@ namespace uniset ...@@ -63,8 +63,6 @@ namespace uniset
UniSetManager( const std::string& name, const std::string& section ); UniSetManager( const std::string& name, const std::string& section );
virtual ~UniSetManager(); virtual ~UniSetManager();
std::shared_ptr<UniSetManager> get_mptr();
virtual uniset::ObjectType getType() override virtual uniset::ObjectType getType() override
{ {
return uniset::ObjectType("UniSetManager"); return uniset::ObjectType("UniSetManager");
...@@ -83,6 +81,7 @@ namespace uniset ...@@ -83,6 +81,7 @@ namespace uniset
PortableServer::POA_ptr getPOA(); PortableServer::POA_ptr getPOA();
PortableServer::POAManager_ptr getPOAManager(); PortableServer::POAManager_ptr getPOAManager();
std::shared_ptr<UniSetManager> get_mptr();
protected: protected:
...@@ -134,7 +133,6 @@ namespace uniset ...@@ -134,7 +133,6 @@ namespace uniset
private: private:
int sig;
UniSetManagerList mlist; UniSetManagerList mlist;
ObjectsList olist; ObjectsList olist;
......
...@@ -84,8 +84,6 @@ namespace uniset ...@@ -84,8 +84,6 @@ namespace uniset
UniSetObject(); UniSetObject();
virtual ~UniSetObject(); virtual ~UniSetObject();
std::shared_ptr<UniSetObject> get_ptr();
// Функции объявленные в IDL // Функции объявленные в IDL
virtual CORBA::Boolean exist() override; virtual CORBA::Boolean exist() override;
...@@ -117,6 +115,7 @@ namespace uniset ...@@ -117,6 +115,7 @@ namespace uniset
// -------------- вспомогательные -------------- // -------------- вспомогательные --------------
/*! получить ссылку (на себя) */ /*! получить ссылку (на себя) */
uniset::ObjectPtr getRef() const; uniset::ObjectPtr getRef() const;
std::shared_ptr<UniSetObject> get_ptr();
/*! заказ таймера (вынесена в public, хотя должна была бы быть в protected */ /*! заказ таймера (вынесена в public, хотя должна была бы быть в protected */
virtual timeout_t askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_t ticks = -1, virtual timeout_t askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_t ticks = -1,
...@@ -128,7 +127,6 @@ namespace uniset ...@@ -128,7 +127,6 @@ namespace uniset
std::shared_ptr<UInterface> ui; /*!< универсальный интерфейс для работы с другими процессами */ std::shared_ptr<UInterface> ui; /*!< универсальный интерфейс для работы с другими процессами */
std::string myname; std::string myname;
std::string section;
std::weak_ptr<UniSetManager> mymngr; std::weak_ptr<UniSetManager> mymngr;
/*! обработка приходящих сообщений */ /*! обработка приходящих сообщений */
...@@ -143,7 +141,7 @@ namespace uniset ...@@ -143,7 +141,7 @@ namespace uniset
VoidMessagePtr receiveMessage(); VoidMessagePtr receiveMessage();
/*! Ожидать сообщения заданное время */ /*! Ожидать сообщения заданное время */
virtual VoidMessagePtr waitMessage( timeout_t msec = UniSetTimer::WaitUpTime ); VoidMessagePtr waitMessage( timeout_t msec = UniSetTimer::WaitUpTime );
/*! прервать ожидание сообщений */ /*! прервать ожидание сообщений */
void termWaiting(); void termWaiting();
...@@ -160,7 +158,8 @@ namespace uniset ...@@ -160,7 +158,8 @@ namespace uniset
//! Деактивиция объекта (переопределяется для необходимых действий при завершении работы) //! Деактивиция объекта (переопределяется для необходимых действий при завершении работы)
virtual bool deactivateObject(); virtual bool deactivateObject();
// void terminate(); // прерывание работы всей программы (с вызовом shutdown)
void uterminate();
// управление созданием потока обработки сообщений ------- // управление созданием потока обработки сообщений -------
...@@ -220,6 +219,8 @@ namespace uniset ...@@ -220,6 +219,8 @@ namespace uniset
/* удаление ссылки из репозитория объектов */ /* удаление ссылки из репозитория объектов */
void unregistration(); void unregistration();
void waitFinish();
void initObject(); void initObject();
pid_t msgpid = { 0 }; // pid потока обработки сообщений pid_t msgpid = { 0 }; // pid потока обработки сообщений
...@@ -241,7 +242,7 @@ namespace uniset ...@@ -241,7 +242,7 @@ namespace uniset
MQMutex mqueueMedium; MQMutex mqueueMedium;
MQMutex mqueueHi; MQMutex mqueueHi;
std::atomic_bool a_working; bool a_working;
std::mutex m_working; std::mutex m_working;
std::condition_variable cv_working; std::condition_variable cv_working;
}; };
......
...@@ -53,6 +53,19 @@ namespace uniset ...@@ -53,6 +53,19 @@ namespace uniset
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Вспомогательные типы данных и константы // Вспомогательные типы данных и константы
/*! Запрещенные для использования в именах объектов символы */
const char BadSymbols[] = {'.', '/'};
/*! Проверка на наличие недопустимых символов
* Запрещенные символы см. uniset::BadSymbols[]
* \return Если не найдено запрещенных символов то будет возвращен 0, иначе найденный символ
*/
char checkBadSymbols(const std::string& str);
/*! Получение запрещенных символов в виде строки '.', '/', и т.д. */
std::string BadSymbolsToStr();
const ObjectId DefaultObjectId = -1; /*!< Идентификатор объекта по умолчанию */ const ObjectId DefaultObjectId = -1; /*!< Идентификатор объекта по умолчанию */
const ThresholdId DefaultThresholdId = -1; /*!< идентификатор порогов по умолчанию */ const ThresholdId DefaultThresholdId = -1; /*!< идентификатор порогов по умолчанию */
const ThresholdId DefaultTimerId = -1; /*!< идентификатор таймера по умолчанию */ const ThresholdId DefaultTimerId = -1; /*!< идентификатор таймера по умолчанию */
...@@ -139,14 +152,10 @@ namespace uniset ...@@ -139,14 +152,10 @@ namespace uniset
/*! Информация об имени объекта */ /*! Информация об имени объекта */
struct ObjectInfo struct ObjectInfo
{ {
ObjectInfo() noexcept: ObjectId id = { DefaultObjectId }; /*!< идентификатор */
id(DefaultObjectId), std::string repName = { "" }; /*!< текстовое имя для регистрации в репозитории */
repName(""), textName(""), xmlnode(0) {} std::string textName = { "" }; /*!< текстовое имя */
xmlNode* xmlnode = { nullptr };
ObjectId id; /*!< идентификатор */
std::string repName; /*!< текстовое имя для регистрации в репозитории */
std::string textName; /*!< текстовое имя */
xmlNode* xmlnode;
inline bool operator < ( const ObjectInfo& o ) const inline bool operator < ( const ObjectInfo& o ) const
{ {
...@@ -156,9 +165,6 @@ namespace uniset ...@@ -156,9 +165,6 @@ namespace uniset
typedef std::list<NodeInfo> ListOfNode; typedef std::list<NodeInfo> ListOfNode;
/*! Запрещенные для использования в именах объектов символы */
const char BadSymbols[] = {'.', '/'};
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Различные преобразования // Различные преобразования
...@@ -298,25 +304,6 @@ namespace uniset ...@@ -298,25 +304,6 @@ namespace uniset
// если не задано f_val, то проверяется, что просто f_prop!="" // если не задано f_val, то проверяется, что просто f_prop!=""
bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept; bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
template<typename InputIterator,
typename OutputIterator,
typename Predicate>
OutputIterator copy_if(InputIterator begin,
InputIterator end,
OutputIterator destBegin,
Predicate p)
{
while( begin != end)
{
if( p(*begin) ) &(destBegin++) = *begin;
++begin;
}
return destBegin;
}
// RAII для флагов форматирования ostream.. // RAII для флагов форматирования ostream..
class ios_fmt_restorer class ios_fmt_restorer
{ {
......
...@@ -114,7 +114,7 @@ namespace uniset ...@@ -114,7 +114,7 @@ namespace uniset
/*! подключение обработчика 'передача файла' 0x66 */ /*! подключение обработчика 'передача файла' 0x66 */
void connectFileTransfer( FileTransferSlot sl ); void connectFileTransfer( FileTransferSlot sl );
virtual void terminate(){} virtual void terminate() {}
protected: protected:
ReadCoilSlot slReadCoil; ReadCoilSlot slReadCoil;
......
...@@ -1452,8 +1452,8 @@ namespace uniset ...@@ -1452,8 +1452,8 @@ namespace uniset
return uniset::uconf; return uniset::uconf;
} }
// atexit( UniSetActivator::normalexit ); // atexit( UniSetActivator::normalexit );
// set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений // set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений
string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile ); string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile );
uniset::uconf = make_shared<Configuration>(argc, argv, confile); uniset::uconf = make_shared<Configuration>(argc, argv, confile);
......
...@@ -2376,7 +2376,7 @@ namespace uniset ...@@ -2376,7 +2376,7 @@ namespace uniset
bool UInterface::waitReady( const uniset::ObjectId id, int msec, int pmsec, const uniset::ObjectId node ) noexcept bool UInterface::waitReady( const uniset::ObjectId id, int msec, int pmsec, const uniset::ObjectId node ) noexcept
{ {
std::atomic_bool cancelFlag = { false }; std::atomic_bool cancelFlag = { false };
return waitReadyWithCancellation(id,msec,cancelFlag,pmsec,node); return waitReadyWithCancellation(id, msec, cancelFlag, pmsec, node);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UInterface::waitWorking( const uniset::ObjectId id, int msec, int pmsec, const uniset::ObjectId node ) noexcept bool UInterface::waitWorking( const uniset::ObjectId id, int msec, int pmsec, const uniset::ObjectId node ) noexcept
......
...@@ -87,15 +87,13 @@ class OPush: public unary_function< const std::shared_ptr<uniset::UniSetObject>& ...@@ -87,15 +87,13 @@ class OPush: public unary_function< const std::shared_ptr<uniset::UniSetObject>&
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
UniSetManager::UniSetManager(): UniSetManager::UniSetManager():
UniSetObject(uniset::DefaultObjectId), UniSetObject(uniset::DefaultObjectId),
sig(0),
olistMutex("UniSetManager_olistMutex"), olistMutex("UniSetManager_olistMutex"),
mlistMutex("UniSetManager_mlistMutex") mlistMutex("UniSetManager_mlistMutex")
{ {
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
UniSetManager::UniSetManager( ObjectId id ): UniSetManager::UniSetManager( ObjectId id ):
UniSetObject(id), UniSetObject(id)
sig(0)
{ {
olistMutex.setName(myname + "_olistMutex"); olistMutex.setName(myname + "_olistMutex");
mlistMutex.setName(myname + "_mlistMutex"); mlistMutex.setName(myname + "_mlistMutex");
...@@ -104,8 +102,7 @@ UniSetManager::UniSetManager( ObjectId id ): ...@@ -104,8 +102,7 @@ UniSetManager::UniSetManager( ObjectId id ):
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
UniSetManager::UniSetManager(const string& name, const string& section): UniSetManager::UniSetManager(const string& name, const string& section):
UniSetObject(name, section), UniSetObject(name, section)
sig(0)
{ {
olistMutex.setName(myname + "_olistMutex"); olistMutex.setName(myname + "_olistMutex");
mlistMutex.setName(myname + "_mlistMutex"); mlistMutex.setName(myname + "_mlistMutex");
...@@ -132,7 +129,7 @@ void UniSetManager::initPOA( const std::weak_ptr<UniSetManager>& rmngr ) ...@@ -132,7 +129,7 @@ void UniSetManager::initPOA( const std::weak_ptr<UniSetManager>& rmngr )
ostringstream err; ostringstream err;
err << myname << "(initPOA): failed weak_ptr !!"; err << myname << "(initPOA): failed weak_ptr !!";
ucrit << err.str() << endl; ucrit << err.str() << endl;
throw SystemError(err.str()); throw uniset::SystemError(err.str());
} }
if( CORBA::is_nil(pman) ) if( CORBA::is_nil(pman) )
...@@ -144,7 +141,12 @@ void UniSetManager::initPOA( const std::weak_ptr<UniSetManager>& rmngr ) ...@@ -144,7 +141,12 @@ void UniSetManager::initPOA( const std::weak_ptr<UniSetManager>& rmngr )
poa = m->getPOA(); poa = m->getPOA();
if( CORBA::is_nil(poa) ) if( CORBA::is_nil(poa) )
ucrit << myname << "(initPOA): failed init poa " << endl; {
ostringstream err;
err << myname << "(initPOA): failed init poa ";
ucrit << err.str() << endl;
throw uniset::SystemError(err.str());
}
// Инициализация самого менеджера и его подобъектов // Инициализация самого менеджера и его подобъектов
UniSetObject::init(rmngr); UniSetObject::init(rmngr);
...@@ -589,43 +591,6 @@ bool UniSetManager::removeManager( const std::shared_ptr<UniSetManager>& child ) ...@@ -589,43 +591,6 @@ bool UniSetManager::removeManager( const std::shared_ptr<UniSetManager>& child )
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
#if 0
const std::shared_ptr<UniSetManager> UniSetManager::itemM( const ObjectId id )
{
{
//lock
uniset_rwmutex_rlock lock(mlistMutex);
for( const auto& li : mlist )
{
if ( li->getId() == id )
return li;
}
} // unlock
return nullptr; // std::shared_ptr<UniSetManager>();
}
// ------------------------------------------------------------------------------------------
const std::shared_ptr<UniSetObject> UniSetManager::itemO( const ObjectId id )
{
{
//lock
uniset_rwmutex_rlock lock(olistMutex);
for( const auto& li : olist )
{
if ( li->getId() == id )
return li;
}
} // unlock
return nullptr; // std::shared_ptr<UniSetObject>();
}
#endif
// ------------------------------------------------------------------------------------------
int UniSetManager::getObjectsInfo( const std::shared_ptr<UniSetManager>& mngr, SimpleInfoSeq* seq, int UniSetManager::getObjectsInfo( const std::shared_ptr<UniSetManager>& mngr, SimpleInfoSeq* seq,
int begin, const long uplimit, const char* userparam ) int begin, const long uplimit, const char* userparam )
......
...@@ -36,6 +36,7 @@ ...@@ -36,6 +36,7 @@
#include "UInterface.h" #include "UInterface.h"
#include "UniSetObject.h" #include "UniSetObject.h"
#include "UniSetManager.h" #include "UniSetManager.h"
#include "UniSetActivator.h"
#include "Debug.h" #include "Debug.h"
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -59,7 +60,6 @@ namespace uniset ...@@ -59,7 +60,6 @@ namespace uniset
tmr = CREATE_TIMER; tmr = CREATE_TIMER;
myname = "noname"; myname = "noname";
section = "nonameSection";
initObject(); initObject();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -74,18 +74,12 @@ namespace uniset ...@@ -74,18 +74,12 @@ namespace uniset
ui = make_shared<UInterface>(id); ui = make_shared<UInterface>(id);
tmr = CREATE_TIMER; tmr = CREATE_TIMER;
if (myid >= 0) if( myid != DefaultObjectId )
{ setID(id);
string myfullname = ui->getNameById(id);
myname = ORepHelpers::getShortName(myfullname);
section = ORepHelpers::getSectionName(myfullname);
}
else else
{ {
threadcreate = false; threadcreate = false;
myid = uniset::DefaultObjectId;
myname = "UnknownUniSetObject"; myname = "UnknownUniSetObject";
section = "UnknownSection";
} }
initObject(); initObject();
...@@ -106,15 +100,8 @@ namespace uniset ...@@ -106,15 +100,8 @@ namespace uniset
tmr = CREATE_TIMER; tmr = CREATE_TIMER;
myname = section + "/" + name; myname = section + "/" + name;
myid = ui->getIdByName(myname); myid = ui->getIdByName(myname);
setID(myid);
if( myid == DefaultObjectId )
{
uwarn << "name: my ID not found!" << endl;
throw Exception(name + ": my ID not found!");
}
initObject(); initObject();
ui->initBackId(myid);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -129,11 +116,10 @@ namespace uniset ...@@ -129,11 +116,10 @@ namespace uniset
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::initObject() void UniSetObject::initObject()
{ {
a_working = ATOMIC_VAR_INIT(0); // a_working = ATOMIC_VAR_INIT(0);
active = ATOMIC_VAR_INIT(0); active = ATOMIC_VAR_INIT(0);
refmutex.setName(myname + "_refmutex"); refmutex.setName(myname + "_refmutex");
// mutex_act.setName(myname + "_mutex_act");
auto conf = uniset_conf(); auto conf = uniset_conf();
...@@ -167,12 +153,11 @@ namespace uniset ...@@ -167,12 +153,11 @@ namespace uniset
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::setID( uniset::ObjectId id ) void UniSetObject::setID( uniset::ObjectId id )
{ {
if( myid != uniset::DefaultObjectId ) if( isActive() )
throw ObjectNameAlready("ObjectId already set(setID)"); throw ObjectNameAlready("Set ID error: ObjectId is active..");
string myfullname = ui->getNameById(id); string myfullname = ui->getNameById(id);
myname = ORepHelpers::getShortName(myfullname); myname = ORepHelpers::getShortName(myfullname);
section = ORepHelpers::getSectionName(myfullname);
myid = id; myid = id;
ui->initBackId(myid); ui->initBackId(myid);
} }
...@@ -332,12 +317,33 @@ namespace uniset ...@@ -332,12 +317,33 @@ namespace uniset
} }
catch(...) catch(...)
{ {
uwarn << myname << ": don`t registration in object repository" << endl; std::exception_ptr p = std::current_exception();
uwarn << myname << ": don`t registration in object repository"
<< " err: " << (p ? p.__cxa_exception_type()->name() : "unknown")
<< endl;
} }
regOK = false; regOK = false;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::waitFinish()
{
// поток завершаем в конце, после пользовательских deactivateObject()
if( !thr )
return;
std::unique_lock<std::mutex> lk(m_working);
// cv_working.wait_for(lk, std::chrono::milliseconds(workingTerminateTimeout), [&](){ return (a_working == false); } );
cv_working.wait(lk, [ = ]()
{
return a_working == false;
});
if( thr->isRunning() )
thr->join();
}
// ------------------------------------------------------------------------------------------
CORBA::Boolean UniSetObject::exist() CORBA::Boolean UniSetObject::exist()
{ {
return true; return true;
...@@ -550,10 +556,12 @@ namespace uniset ...@@ -550,10 +556,12 @@ namespace uniset
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
// void UniSetObject::terminate() void UniSetObject::uterminate()
// { {
// deactivate(); // setActive(false);
// } auto act = UniSetActivator::Instance();
act->terminate();
}
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::thread(bool create) void UniSetObject::thread(bool create)
{ {
...@@ -615,7 +623,8 @@ namespace uniset ...@@ -615,7 +623,8 @@ namespace uniset
unregistration(); unregistration();
PortableServer::ObjectId_var oid = poamngr->servant_to_id(static_cast<PortableServer::ServantBase*>(this)); PortableServer::ObjectId_var oid = poamngr->servant_to_id(static_cast<PortableServer::ServantBase*>(this));
poamngr->deactivate_object(oid); poamngr->deactivate_object(oid);
uinfo << myname << "(disacivate): finished..." << endl; uinfo << myname << "(deactivate): finished..." << endl;
waitFinish();
return true; return true;
} }
} }
...@@ -643,19 +652,6 @@ namespace uniset ...@@ -643,19 +652,6 @@ namespace uniset
uwarn << myname << "(deactivate): " << ex.what() << endl; uwarn << myname << "(deactivate): " << ex.what() << endl;
} }
if( thr )
{
std::unique_lock<std::mutex> lk(m_working);
// cv_working.wait_for(lk, std::chrono::milliseconds(workingTerminateTimeout), [&](){ return (a_working == false); } );
if( a_working )
cv_working.wait(lk);
if( a_working )
thr->stop();
}
return false; return false;
} }
...@@ -812,6 +808,9 @@ namespace uniset ...@@ -812,6 +808,9 @@ namespace uniset
if( m ) if( m )
processingMessage(m.get()); processingMessage(m.get());
if( !isActive() )
return;
sleepTime = checkTimers(this); sleepTime = checkTimers(this);
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
......
...@@ -626,3 +626,32 @@ timespec uniset::now_to_timespec() ...@@ -626,3 +626,32 @@ timespec uniset::now_to_timespec()
return to_timespec(d); return to_timespec(d);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
char uniset::checkBadSymbols( const string& str )
{
for ( const auto& c: str )
{
for( size_t k = 0; k < sizeof(BadSymbols); k++ )
{
if ( c == BadSymbols[k] )
return (char)BadSymbols[k];
}
}
return 0;
}
// ---------------------------------------------------------------------------------------------------------------
string uniset::BadSymbolsToStr()
{
string bad = "";
for( size_t i = 0; i < sizeof(BadSymbols); i++ )
{
bad += "'" +
bad += BadSymbols[i];
bad += "', ";
}
return bad;
}
// ---------------------------------------------------------------------------------------------------------------
...@@ -224,41 +224,5 @@ namespace uniset ...@@ -224,41 +224,5 @@ namespace uniset
} }
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
/*
* Запрещенные символы см. uniset::BadSymbols[]
* \return Если не найдено запрещенных символов то будет возвращен 0, иначе найденный символ
*/
char checkBadSymbols( const string& str )
{
using namespace uniset;
for ( size_t i = 0; i < str.length(); i++)
{
for(unsigned int k = 0; k < sizeof(BadSymbols); k++)
{
if ( str[i] == BadSymbols[k] )
return (char)BadSymbols[k];
}
}
return 0;
}
// ---------------------------------------------------------------------------------------------------------------
string BadSymbolsToStr()
{
string bad = "";
for( size_t i = 0; i < sizeof(uniset::BadSymbols); i++ )
{
bad += "'";
bad += uniset::BadSymbols[i];
bad += "', ";
}
return bad;
}
// ---------------------------------------------------------------------------------------------------------------
} }
} }
...@@ -103,7 +103,7 @@ throw(ORepFailed, ObjectNameAlready, InvalidObjectName, NameNotFound) ...@@ -103,7 +103,7 @@ throw(ORepFailed, ObjectNameAlready, InvalidObjectName, NameNotFound)
} }
// Проверка корректности имени // Проверка корректности имени
char bad = ORepHelpers::checkBadSymbols(name); char bad = uniset::checkBadSymbols(name);
if( bad != 0 ) if( bad != 0 )
{ {
...@@ -452,7 +452,7 @@ bool ObjectRepository::isExist( const ObjectPtr& oref ) const ...@@ -452,7 +452,7 @@ bool ObjectRepository::isExist( const ObjectPtr& oref ) const
bool ObjectRepository::createSection(const string& name, const string& in_section) const bool ObjectRepository::createSection(const string& name, const string& in_section) const
throw(ORepFailed, InvalidObjectName) throw(ORepFailed, InvalidObjectName)
{ {
char bad = ORepHelpers::checkBadSymbols(name); char bad = uniset::checkBadSymbols(name);
if (bad != 0) if (bad != 0)
{ {
......
...@@ -118,7 +118,8 @@ void IOController::activateInit() ...@@ -118,7 +118,8 @@ void IOController::activateInit()
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
ucrit << myname << "(activateInit): " << ex << endl; ucrit << myname << "(activateInit): " << ex << endl;
std::terminate(); //std::terminate();
uterminate();
} }
} }
} }
......
...@@ -829,7 +829,8 @@ void IONotifyController::readDump() ...@@ -829,7 +829,8 @@ void IONotifyController::readDump()
// и безопаснее "вылететь", чем запустится, т.к. часть датчиков не будет работать // и безопаснее "вылететь", чем запустится, т.к. часть датчиков не будет работать
// как ожидается. // как ожидается.
ucrit << myname << "(IONotifyController::readDump): " << ex.what() << endl; ucrit << myname << "(IONotifyController::readDump): " << ex.what() << endl;
std::terminate(); // std::abort(); //std::terminate(); // std::abort();
uterminate();
} }
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
......
...@@ -107,7 +107,8 @@ bool ProxyManager::activateObject() ...@@ -107,7 +107,8 @@ bool ProxyManager::activateObject()
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
ucrit << myname << "(activate): " << ex << endl; ucrit << myname << "(activate): " << ex << endl;
std::terminate(); //std::terminate();
uterminate();
} }
} }
......
...@@ -109,7 +109,7 @@ uniset_rwmutex_wrlock::~uniset_rwmutex_wrlock() ...@@ -109,7 +109,7 @@ uniset_rwmutex_wrlock::~uniset_rwmutex_wrlock()
//catch( Poco::SystemException& ex ) //catch( Poco::SystemException& ex )
catch( std::exception& ex ) catch( std::exception& ex )
{ {
std::terminate(); std::abort();
} }
} }
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
...@@ -127,7 +127,7 @@ uniset_rwmutex_rlock::~uniset_rwmutex_rlock() ...@@ -127,7 +127,7 @@ uniset_rwmutex_rlock::~uniset_rwmutex_rlock()
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
std::terminate(); std::abort();
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -70,13 +70,15 @@ void SMonitor::sysCommand( const SystemMessage* sm ) ...@@ -70,13 +70,15 @@ void SMonitor::sysCommand( const SystemMessage* sm )
{ {
cerr << myname << ":(askSensor): " << ex << endl; cerr << myname << ":(askSensor): " << ex << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); //std::terminate();
uterminate();
} }
catch(...) catch(...)
{ {
cerr << myname << ": НЕ СМОГ ЗАКАЗТЬ датчики " << endl; cerr << myname << ": НЕ СМОГ ЗАКАЗТЬ датчики " << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); //std::terminate();
uterminate();
} }
} }
} }
......
...@@ -16,7 +16,6 @@ extensions/tests/SMemoryTest ...@@ -16,7 +16,6 @@ extensions/tests/SMemoryTest
extensions/UNetUDP extensions/UNetUDP
extensions/UniNetwork extensions/UniNetwork
include include
include/libxml2/libxml
include/modbus include/modbus
python/lib/pyUniSet python/lib/pyUniSet
src/Log src/Log
...@@ -29,3 +28,5 @@ Utilities/NullController ...@@ -29,3 +28,5 @@ Utilities/NullController
/usr/include/sigc++-2.0 /usr/include/sigc++-2.0
/usr/include/omniORB4 /usr/include/omniORB4
/usr/include/Poco /usr/include/Poco
/usr/include/c++/5
/usr/include/libxml2/libxml
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