Commit 30930362 authored by Pavel Vainerman's avatar Pavel Vainerman

(codegen): добавил в httpDumpIO() вывод (в json)

всех полей указанных в item из src.xml Очередная расстановка const везде где можно make style ещё пачка const..
parent 120645de
...@@ -448,7 +448,7 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -448,7 +448,7 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
UniSetObject_i_var obj; UniSetObject_i_var obj;
string fullName; string fullName;
for( const auto& oname: olist ) for( const auto& oname : olist )
{ {
fullName = section + "/" + oname; fullName = section + "/" + oname;
......
...@@ -163,7 +163,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::initFromSM() ...@@ -163,7 +163,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::initFromSM()
</xsl:for-each> </xsl:for-each>
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() const
{ {
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
......
...@@ -233,7 +233,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force ) ...@@ -233,7 +233,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::updateOutputs( bool _force )
--> -->
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() const
{ {
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
......
...@@ -294,7 +294,7 @@ ...@@ -294,7 +294,7 @@
bool checkTestMode() const noexcept; bool checkTestMode() const noexcept;
</xsl:if> </xsl:if>
void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId ); void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId );
uniset::ObjectId getSMTestID(); uniset::ObjectId getSMTestID() const;
void resetMsg(); void resetMsg();
uniset::Trigger trResetMsg; uniset::Trigger trResetMsg;
...@@ -1430,7 +1430,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::resetMsg() ...@@ -1430,7 +1430,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::resetMsg()
</xsl:for-each> </xsl:for-each>
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() uniset::ObjectId <xsl:value-of select="$CLASSNAME"/>_SK::getSMTestID() const
{ {
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
...@@ -1472,6 +1472,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() ...@@ -1472,6 +1472,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
inf->set("id",<xsl:value-of select="@name"/>); inf->set("id",<xsl:value-of select="@name"/>);
inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))); inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>)));
inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>); inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>);
<xsl:for-each select="@*[not(name()='name')]">inf->set("<xsl:value-of select="name(.)"/>","<xsl:value-of select="."/>");
</xsl:for-each>
} }
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
...@@ -1486,6 +1488,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() ...@@ -1486,6 +1488,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
inf->set("id",<xsl:value-of select="@name"/>); inf->set("id",<xsl:value-of select="@name"/>);
inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))); inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>)));
inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>); inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>);
<xsl:for-each select="@*[not(name()='name')]">inf->set("<xsl:value-of select="name(.)"/>","<xsl:value-of select="."/>");
</xsl:for-each>
} }
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
...@@ -1872,6 +1876,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() ...@@ -1872,6 +1876,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
inf->set("id",<xsl:value-of select="../../@id"/>); inf->set("id",<xsl:value-of select="../../@id"/>);
inf->set("name", "<xsl:value-of select="../../@name"/>"); inf->set("name", "<xsl:value-of select="../../@name"/>");
inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>); inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>);
<xsl:for-each select="@*[not(name()='name' or name()='id')]">inf->set("<xsl:value-of select="name(.)"/>","<xsl:value-of select="."/>");
</xsl:for-each>
} }
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@vartype)='out'"> <xsl:if test="normalize-space(@vartype)='out'">
...@@ -1880,6 +1886,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() ...@@ -1880,6 +1886,8 @@ Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
inf->set("id",<xsl:value-of select="../../@id"/>); inf->set("id",<xsl:value-of select="../../@id"/>);
inf->set("name", "<xsl:value-of select="../../@name"/>"); inf->set("name", "<xsl:value-of select="../../@name"/>");
inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>); inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>);
<xsl:for-each select="@*[not(name()='name' or name()='id')]">inf->set("<xsl:value-of select="name(.)"/>","<xsl:value-of select="."/>");
</xsl:for-each>
} }
</xsl:if> </xsl:if>
</xsl:if> </xsl:if>
......
...@@ -37,7 +37,7 @@ using namespace std; ...@@ -37,7 +37,7 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
DBServer_MySQL::DBServer_MySQL(ObjectId id, const std::string& prefix ): DBServer_MySQL::DBServer_MySQL(ObjectId id, const std::string& prefix ):
DBServer(id, prefix) DBServer(id, prefix)
{ {
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
...@@ -275,8 +275,8 @@ void DBServer_MySQL::initDBServer() ...@@ -275,8 +275,8 @@ void DBServer_MySQL::initDBServer()
tblMap[uniset::Message::SensorInfo] = "main_history"; tblMap[uniset::Message::SensorInfo] = "main_history";
tblMap[uniset::Message::Confirm] = "main_history"; tblMap[uniset::Message::Confirm] = "main_history";
PingTime = conf->getPIntProp(node, "pingTime",PingTime); PingTime = conf->getPIntProp(node, "pingTime", PingTime);
ReconnectTime = conf->getPIntProp(node, "reconnectTime",ReconnectTime); ReconnectTime = conf->getPIntProp(node, "reconnectTime", ReconnectTime);
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize); qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize);
if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 ) if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
......
...@@ -254,8 +254,8 @@ void DBServer_SQLite::initDBServer() ...@@ -254,8 +254,8 @@ void DBServer_SQLite::initDBServer()
tblMap[uniset::Message::SensorInfo] = "main_history"; tblMap[uniset::Message::SensorInfo] = "main_history";
tblMap[uniset::Message::Confirm] = "main_history"; tblMap[uniset::Message::Confirm] = "main_history";
PingTime = conf->getPIntProp(node, "pingTime",PingTime); PingTime = conf->getPIntProp(node, "pingTime", PingTime);
ReconnectTime = conf->getPIntProp(node, "reconnectTime",ReconnectTime); ReconnectTime = conf->getPIntProp(node, "reconnectTime", ReconnectTime);
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize); qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize);
if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 ) if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
......
...@@ -80,7 +80,7 @@ namespace uniset ...@@ -80,7 +80,7 @@ namespace uniset
} }
protected: protected:
ComediInterface():card(nullptr){} ComediInterface(): card(nullptr) {}
comedi_t* card; /*!< интерфейс для работы с картами в/в */ comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname; std::string dname;
......
...@@ -142,7 +142,7 @@ namespace uniset ...@@ -142,7 +142,7 @@ namespace uniset
else else
{ {
noCards = false; noCards = false;
cards[i] = new ComediInterface(iodev,""); cards[i] = new ComediInterface(iodev, "");
iolog3 << myname << "(init): ADD card" << i << " dev=" << iodev << endl; iolog3 << myname << "(init): ADD card" << i << " dev=" << iodev << endl;
} }
...@@ -405,6 +405,7 @@ namespace uniset ...@@ -405,6 +405,7 @@ namespace uniset
catch(...) {} catch(...) {}
ioinfo << myname << "(iothread): run..." << endl; ioinfo << myname << "(iothread): run..." << endl;
while( !term ) while( !term )
{ {
try try
...@@ -520,7 +521,7 @@ namespace uniset ...@@ -520,7 +521,7 @@ namespace uniset
// опять опросим приоритетные // опять опросим приоритетные
if( !prior && i > maxHalf ) if( !prior && i > maxHalf )
{ {
for( const auto& p: pmap ) for( const auto& p : pmap )
{ {
if( p.priority > 1 ) if( p.priority > 1 )
{ {
...@@ -549,8 +550,8 @@ namespace uniset ...@@ -549,8 +550,8 @@ namespace uniset
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
void IOControl::ioread( std::shared_ptr<IOInfo>& it ) void IOControl::ioread( std::shared_ptr<IOInfo>& it )
{ {
// cout << uniset_conf()->oind->getMapName(it->si.id) << " ignore=" << it->ignore << " ncard=" << it->ncard << endl; // cout << uniset_conf()->oind->getMapName(it->si.id) << " ignore=" << it->ignore << " ncard=" << it->ncard << endl;
// cerr << it << endl; // cerr << it << endl;
if( it->ignore || it->ncard == defCardNum ) if( it->ignore || it->ncard == defCardNum )
return; return;
...@@ -841,7 +842,7 @@ namespace uniset ...@@ -841,7 +842,7 @@ namespace uniset
{ {
iolog3 << myname << "(readItem): add threshold '" << it.getProp("name") iolog3 << myname << "(readItem): add threshold '" << it.getProp("name")
<< " for '" << uniset_conf()->oind->getNameById(inf->t_ai) << endl; << " for '" << uniset_conf()->oind->getNameById(inf->t_ai) << endl;
std::swap(iomap[maxItem++],inf); std::swap(iomap[maxItem++], inf);
return true; return true;
} }
...@@ -887,7 +888,7 @@ namespace uniset ...@@ -887,7 +888,7 @@ namespace uniset
iolog3 << myname << "(readItem): add: " << inf->stype << " " << inf << endl; iolog3 << myname << "(readItem): add: " << inf->stype << " " << inf << endl;
std::swap(iomap[maxItem++],inf); std::swap(iomap[maxItem++], inf);
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -1033,7 +1034,7 @@ namespace uniset ...@@ -1033,7 +1034,7 @@ namespace uniset
if( lst.empty() ) if( lst.empty() )
return; return;
for( const auto& io: lst ) for( const auto& io : lst )
{ {
if( io->subdev == IOBase::DefaultSubdev || io->channel == IOBase::DefaultChannel ) if( io->subdev == IOBase::DefaultSubdev || io->channel == IOBase::DefaultChannel )
continue; continue;
...@@ -1289,7 +1290,7 @@ namespace uniset ...@@ -1289,7 +1290,7 @@ namespace uniset
cout << LogServer::help_print("prefix-logserver") << endl; cout << LogServer::help_print("prefix-logserver") << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
SimpleInfo*IOControl::getInfo( const char* userparam ) SimpleInfo* IOControl::getInfo( const char* userparam )
{ {
uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam); uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam);
...@@ -1298,6 +1299,7 @@ namespace uniset ...@@ -1298,6 +1299,7 @@ namespace uniset
inf << i->info << endl; inf << i->info << endl;
inf << "LogServer: " << logserv_host << ":" << logserv_port << endl; inf << "LogServer: " << logserv_host << ":" << logserv_port << endl;
if( logserv ) if( logserv )
inf << logserv->getShortInfo() << endl; inf << logserv->getShortInfo() << endl;
else else
...@@ -1313,9 +1315,11 @@ namespace uniset ...@@ -1313,9 +1315,11 @@ namespace uniset
<< endl; << endl;
inf << endl; inf << endl;
for( size_t i=0; i<cards.size(); i++ )
for( size_t i = 0; i < cards.size(); i++ )
{ {
auto c = cards[i]; auto c = cards[i];
if( c ) if( c )
{ {
inf << "card[" << setw(2) << i << "]:" inf << "card[" << setw(2) << i << "]:"
...@@ -1432,9 +1436,9 @@ namespace uniset ...@@ -1432,9 +1436,9 @@ namespace uniset
<< activateTimeout << " мсек"; << activateTimeout << " мсек";
iocrit << err.str() << endl; iocrit << err.str() << endl;
// kill(SIGTERM, getpid()); // прерываем (перезапускаем) процесс... // kill(SIGTERM, getpid()); // прерываем (перезапускаем) процесс...
std::terminate(); std::terminate();
// throw SystemError(err.str()); // throw SystemError(err.str());
} }
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
...@@ -1514,7 +1518,7 @@ namespace uniset ...@@ -1514,7 +1518,7 @@ namespace uniset
check_testmode(); check_testmode();
} }
for( auto&& it : iomap ) for( auto && it : iomap )
{ {
if( it->si.id == sm->id ) if( it->si.id == sm->id )
{ {
...@@ -1767,7 +1771,7 @@ namespace uniset ...@@ -1767,7 +1771,7 @@ namespace uniset
try try
{ {
cards[cardnum] = new ComediInterface(iodev,cname); cards[cardnum] = new ComediInterface(iodev, cname);
noCards = false; noCards = false;
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
......
...@@ -25,13 +25,13 @@ namespace uniset ...@@ -25,13 +25,13 @@ namespace uniset
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
FakeIOControl::FakeIOControl(uniset::ObjectId id, uniset::ObjectId icID, FakeIOControl::FakeIOControl(uniset::ObjectId id, uniset::ObjectId icID,
const std::shared_ptr<SharedMemory>& ic, int numcards, const std::string& prefix_ ): const std::shared_ptr<SharedMemory>& ic, int numcards, const std::string& prefix_ ):
IOControl(id,icID,ic,numcards,prefix_) IOControl(id, icID, ic, numcards, prefix_)
{ {
fcard = new FakeComediInterface(); fcard = new FakeComediInterface();
// Подменяем все карты на fake-овые // Подменяем все карты на fake-овые
for( size_t i=0; i < cards.size(); i++ ) for( size_t i = 0; i < cards.size(); i++ )
{ {
if( cards[i] ) if( cards[i] )
delete cards[i]; delete cards[i];
...@@ -44,7 +44,7 @@ namespace uniset ...@@ -44,7 +44,7 @@ namespace uniset
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
FakeIOControl::~FakeIOControl() FakeIOControl::~FakeIOControl()
{ {
for( size_t i=0; i < cards.size(); i++ ) for( size_t i = 0; i < cards.size(); i++ )
{ {
if( cards[i] ) if( cards[i] )
{ {
...@@ -73,7 +73,7 @@ namespace uniset ...@@ -73,7 +73,7 @@ namespace uniset
if( ID == uniset::DefaultObjectId ) if( ID == uniset::DefaultObjectId )
{ {
std::cerr << "(iocontrol): Unknown ID for " << name std::cerr << "(iocontrol): Unknown ID for " << name
<< "' Not found in <objects>" << std::endl; << "' Not found in <objects>" << std::endl;
return 0; return 0;
} }
...@@ -87,8 +87,8 @@ namespace uniset ...@@ -87,8 +87,8 @@ namespace uniset
chInputs(maxChannelNum), chInputs(maxChannelNum),
chOutputs(maxChannelNum) chOutputs(maxChannelNum)
{ {
name="FakeCard"; name = "FakeCard";
dname="/dev/fakecomedi"; dname = "/dev/fakecomedi";
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
FakeComediInterface::~FakeComediInterface() FakeComediInterface::~FakeComediInterface()
...@@ -105,6 +105,7 @@ namespace uniset ...@@ -105,6 +105,7 @@ namespace uniset
<< " Must be [0," << maxChannelNum << "]" << endl; << " Must be [0," << maxChannelNum << "]" << endl;
std::terminate(); std::terminate();
} }
return chInputs[channel]; return chInputs[channel];
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -130,6 +131,7 @@ namespace uniset ...@@ -130,6 +131,7 @@ namespace uniset
<< " Must be [0," << maxChannelNum << "]" << endl; << " Must be [0," << maxChannelNum << "]" << endl;
std::terminate(); std::terminate();
} }
return (bool)chInputs[channel]; return (bool)chInputs[channel];
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -30,38 +30,38 @@ namespace uniset ...@@ -30,38 +30,38 @@ namespace uniset
FakeComediInterface(); FakeComediInterface();
virtual ~FakeComediInterface(); virtual ~FakeComediInterface();
static const size_t maxChannelNum = 32; static const size_t maxChannelNum = 32;
// Управление тестированием // Управление тестированием
// -------------------------------------------- // --------------------------------------------
// для простоты массивы специально объявлены в public // для простоты массивы специально объявлены в public
// warning: надо только иметь ввиду, что доступ к ним будет из разных потоков // warning: надо только иметь ввиду, что доступ к ним будет из разных потоков
// из теста и из потока опроса карт в/в (IOControl) // из теста и из потока опроса карт в/в (IOControl)
// в данном случае это не страшно.. // в данном случае это не страшно..
// -------------------------------------------- // --------------------------------------------
std::vector<int> chInputs; // массив значений 'входов' (для проверки чтения) std::vector<int> chInputs; // массив значений 'входов' (для проверки чтения)
mutable std::vector<int> chOutputs; // массив значений 'выходов' (для проверки функций вывода) mutable std::vector<int> chOutputs; // массив значений 'выходов' (для проверки функций вывода)
// -------------------------------------------- // --------------------------------------------
// при тестировании параметры range,aref,subdev игнорируются! // при тестировании параметры range,aref,subdev игнорируются!
virtual int getAnalogChannel( int subdev, int channel, int range = 0, int aref = AREF_GROUND ) const virtual int getAnalogChannel( int subdev, int channel, int range = 0, int aref = AREF_GROUND ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
virtual void setAnalogChannel( int subdev, int channel, int data, int range = 0, int aref = AREF_GROUND ) const virtual void setAnalogChannel( int subdev, int channel, int data, int range = 0, int aref = AREF_GROUND ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
virtual bool getDigitalChannel( int subdev, int channel ) const virtual bool getDigitalChannel( int subdev, int channel ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
virtual void setDigitalChannel( int subdev, int channel, bool bit ) const virtual void setDigitalChannel( int subdev, int channel, bool bit ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
virtual void configureSubdev( int subdev, SubdevType type ) const virtual void configureSubdev( int subdev, SubdevType type ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
virtual void configureChannel( int subdev, int channel, ChannelType type, int range = 0, int aref = 0 ) const virtual void configureChannel( int subdev, int channel, ChannelType type, int range = 0, int aref = 0 ) const
throw(uniset::Exception) override; throw(uniset::Exception) override;
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
...@@ -38,7 +38,7 @@ int main( int argc, const char* argv[] ) ...@@ -38,7 +38,7 @@ int main( int argc, const char* argv[] )
return returnCode; return returnCode;
auto conf = uniset_init(argc, argv); auto conf = uniset_init(argc, argv);
// dlog()->logFile("./smtest.log"); // dlog()->logFile("./smtest.log");
bool apart = findArgParam("--apart", argc, argv) != -1; bool apart = findArgParam("--apart", argc, argv) != -1;
......
...@@ -46,12 +46,12 @@ TEST_CASE("IOControl: DI", "[iocontrol][di]") ...@@ -46,12 +46,12 @@ TEST_CASE("IOControl: DI", "[iocontrol][di]")
InitTest(); InitTest();
ioc->fcard->chInputs[0] = 1; ioc->fcard->chInputs[0] = 1;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1000) == 1 ); REQUIRE( ui->getValue(1000) == 1 );
REQUIRE( ui->getValue(1001) == 0 ); // invert REQUIRE( ui->getValue(1001) == 0 ); // invert
ioc->fcard->chInputs[0] = 0; ioc->fcard->chInputs[0] = 0;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1000) == 0 ); REQUIRE( ui->getValue(1000) == 0 );
REQUIRE( ui->getValue(1001) == 1 ); // invert REQUIRE( ui->getValue(1001) == 1 ); // invert
} }
...@@ -60,15 +60,15 @@ TEST_CASE("IOControl: DO", "[iocontrol][do]") ...@@ -60,15 +60,15 @@ TEST_CASE("IOControl: DO", "[iocontrol][do]")
{ {
InitTest(); InitTest();
ui->setValue(1002,1); ui->setValue(1002, 1);
ui->setValue(1003,1); ui->setValue(1003, 1);
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ioc->fcard->chOutputs[0] == 1 ); REQUIRE( ioc->fcard->chOutputs[0] == 1 );
REQUIRE( ioc->fcard->chOutputs[1] == 0 ); // invert REQUIRE( ioc->fcard->chOutputs[1] == 0 ); // invert
ui->setValue(1002,0); ui->setValue(1002, 0);
ui->setValue(1003,0); ui->setValue(1003, 0);
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ioc->fcard->chOutputs[0] == 0 ); REQUIRE( ioc->fcard->chOutputs[0] == 0 );
REQUIRE( ioc->fcard->chOutputs[1] == 1 ); // invert REQUIRE( ioc->fcard->chOutputs[1] == 1 ); // invert
} }
...@@ -78,7 +78,8 @@ static size_t pulseCount( FakeComediInterface* card, size_t ch ) ...@@ -78,7 +78,8 @@ static size_t pulseCount( FakeComediInterface* card, size_t ch )
// считаем количество импульсов "0 -> 1 -> 0" // считаем количество импульсов "0 -> 1 -> 0"
size_t npulse = 0; size_t npulse = 0;
bool prev = false; bool prev = false;
for( size_t i=0; i < 20 && npulse < 3; i ++ )
for( size_t i = 0; i < 20 && npulse < 3; i ++ )
{ {
if( card->chOutputs[ch] == 1 && !prev ) if( card->chOutputs[ch] == 1 && !prev )
prev = true; prev = true;
...@@ -117,7 +118,7 @@ TEST_CASE("IOControl: AO", "[iocontrol][ao]") ...@@ -117,7 +118,7 @@ TEST_CASE("IOControl: AO", "[iocontrol][ao]")
ui->setValue(1005, 10); ui->setValue(1005, 10);
ui->setValue(1006, 100); ui->setValue(1006, 100);
ui->setValue(1007, 300); ui->setValue(1007, 300);
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ioc->fcard->chOutputs[5] == 10 ); REQUIRE( ioc->fcard->chOutputs[5] == 10 );
REQUIRE( ioc->fcard->chOutputs[6] == 1000 ); // calibration channel REQUIRE( ioc->fcard->chOutputs[6] == 1000 ); // calibration channel
...@@ -126,7 +127,7 @@ TEST_CASE("IOControl: AO", "[iocontrol][ao]") ...@@ -126,7 +127,7 @@ TEST_CASE("IOControl: AO", "[iocontrol][ao]")
ui->setValue(1005, 100); ui->setValue(1005, 100);
ui->setValue(1006, -100); ui->setValue(1006, -100);
ui->setValue(1007, -300); ui->setValue(1007, -300);
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ioc->fcard->chOutputs[5] == 100 ); REQUIRE( ioc->fcard->chOutputs[5] == 100 );
REQUIRE( ioc->fcard->chOutputs[6] == 0 ); // calibration channel REQUIRE( ioc->fcard->chOutputs[6] == 0 ); // calibration channel
...@@ -140,27 +141,27 @@ TEST_CASE("IOControl: threshold", "[iocontrol][threshold]") ...@@ -140,27 +141,27 @@ TEST_CASE("IOControl: threshold", "[iocontrol][threshold]")
auto card = ioc->fcard; auto card = ioc->fcard;
ioc->fcard->chInputs[10] = 20; ioc->fcard->chInputs[10] = 20;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1010) == 20 ); REQUIRE( ui->getValue(1010) == 20 );
REQUIRE( ui->getValue(1011) == 0 ); // threshold [30,40] REQUIRE( ui->getValue(1011) == 0 ); // threshold [30,40]
ioc->fcard->chInputs[10] = 35; ioc->fcard->chInputs[10] = 35;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1010) == 35 ); REQUIRE( ui->getValue(1010) == 35 );
REQUIRE( ui->getValue(1011) == 0 ); // threshold [30,40] REQUIRE( ui->getValue(1011) == 0 ); // threshold [30,40]
ioc->fcard->chInputs[10] = 45; ioc->fcard->chInputs[10] = 45;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1010) == 45 ); REQUIRE( ui->getValue(1010) == 45 );
REQUIRE( ui->getValue(1011) == 1 ); // threshold [30,40] REQUIRE( ui->getValue(1011) == 1 ); // threshold [30,40]
ioc->fcard->chInputs[10] = 35; ioc->fcard->chInputs[10] = 35;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1010) == 35 ); REQUIRE( ui->getValue(1010) == 35 );
REQUIRE( ui->getValue(1011) == 1 ); // threshold [30,40] REQUIRE( ui->getValue(1011) == 1 ); // threshold [30,40]
ioc->fcard->chInputs[10] = 25; ioc->fcard->chInputs[10] = 25;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1010) == 25 ); REQUIRE( ui->getValue(1010) == 25 );
REQUIRE( ui->getValue(1011) == 0 ); // < lowlimit (30) REQUIRE( ui->getValue(1011) == 0 ); // < lowlimit (30)
} }
...@@ -173,14 +174,14 @@ TEST_CASE("IOControl: test lamp", "[iocontrol][testlamp]") ...@@ -173,14 +174,14 @@ TEST_CASE("IOControl: test lamp", "[iocontrol][testlamp]")
// отключаем тест ламп // отключаем тест ламп
card->chInputs[12] = 0; card->chInputs[12] = 0;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1012) == 0 ); REQUIRE( ui->getValue(1012) == 0 );
REQUIRE( ui->getValue(1013) == 0 ); REQUIRE( ui->getValue(1013) == 0 );
REQUIRE( card->chOutputs[13] == 0 ); REQUIRE( card->chOutputs[13] == 0 );
// включаем тест ламп // включаем тест ламп
card->chInputs[12] = 1; card->chInputs[12] = 1;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1012) == 1 ); REQUIRE( ui->getValue(1012) == 1 );
// должны ловить мигание лампочки.. // должны ловить мигание лампочки..
...@@ -189,7 +190,7 @@ TEST_CASE("IOControl: test lamp", "[iocontrol][testlamp]") ...@@ -189,7 +190,7 @@ TEST_CASE("IOControl: test lamp", "[iocontrol][testlamp]")
// отключаем тест ламп // отключаем тест ламп
card->chInputs[12] = 0; card->chInputs[12] = 0;
msleep(polltime+10); msleep(polltime + 10);
REQUIRE( ui->getValue(1012) == 0 ); REQUIRE( ui->getValue(1012) == 0 );
REQUIRE( ui->getValue(1013) == 0 ); REQUIRE( ui->getValue(1013) == 0 );
REQUIRE( card->chOutputs[13] == 0 ); REQUIRE( card->chOutputs[13] == 0 );
......
...@@ -117,7 +117,7 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -117,7 +117,7 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd )
{ {
try try
{ {
for( auto&& it : extInputs ) for( auto && it : extInputs )
shm->askSensor(it.sid, cmd); shm->askSensor(it.sid, cmd);
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
...@@ -129,7 +129,7 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -129,7 +129,7 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd )
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::sensorInfo( const uniset::SensorMessage* sm ) void PassiveLProcessor::sensorInfo( const uniset::SensorMessage* sm )
{ {
for( auto&& it : extInputs ) for( auto && it : extInputs )
{ {
if( it.sid == sm->id ) if( it.sid == sm->id )
it.value = sm->value; it.value = sm->value;
...@@ -230,7 +230,7 @@ void PassiveLProcessor::initIterators() ...@@ -230,7 +230,7 @@ void PassiveLProcessor::initIterators()
void PassiveLProcessor::setOuts() void PassiveLProcessor::setOuts()
{ {
// выcтавляем выходы // выcтавляем выходы
for( auto&& it : extOuts ) for( auto && it : extOuts )
{ {
try try
{ {
...@@ -249,7 +249,7 @@ void PassiveLProcessor::setOuts() ...@@ -249,7 +249,7 @@ void PassiveLProcessor::setOuts()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::sigterm( int signo ) void PassiveLProcessor::sigterm( int signo )
{ {
for( auto&& it : extOuts ) for( auto && it : extOuts )
{ {
try try
{ {
......
...@@ -597,7 +597,7 @@ namespace uniset ...@@ -597,7 +597,7 @@ namespace uniset
for( const auto& m : d.pollmap ) for( const auto& m : d.pollmap )
{ {
for( const auto& it : *(m.second) ) for( const auto& it : * (m.second) )
os << " " << it.second << endl; os << " " << it.second << endl;
} }
...@@ -620,7 +620,7 @@ namespace uniset ...@@ -620,7 +620,7 @@ namespace uniset
<< " mtrType=" << MTR::type2str(r.mtrType) << " mtrType=" << MTR::type2str(r.mtrType)
<< endl; << endl;
for( const auto& s: r.slst ) for( const auto& s : r.slst )
os << " " << s << endl; os << " " << s << endl;
return os; return os;
...@@ -629,11 +629,12 @@ namespace uniset ...@@ -629,11 +629,12 @@ namespace uniset
void MBExchange::rtuQueryOptimization( RTUDeviceMap& dm ) void MBExchange::rtuQueryOptimization( RTUDeviceMap& dm )
{ {
mbinfo << myname << "(rtuQueryOptimization): optimization..." << endl; mbinfo << myname << "(rtuQueryOptimization): optimization..." << endl;
for( const auto& d: dm )
for( const auto& d : dm )
rtuQueryOptimizationForDevice(d.second); rtuQueryOptimizationForDevice(d.second);
// printMap(dm); // printMap(dm);
// assert(false); // assert(false);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::rtuQueryOptimizationForDevice( const std::shared_ptr<RTUDevice>& d ) void MBExchange::rtuQueryOptimizationForDevice( const std::shared_ptr<RTUDevice>& d )
...@@ -674,7 +675,7 @@ namespace uniset ...@@ -674,7 +675,7 @@ namespace uniset
beg->q_count++; beg->q_count++;
regID = it->second->regID; regID = it->second->regID;
it->second->q_num = beg->q_count-1; it->second->q_num = beg->q_count - 1;
it->second->q_count = 0; it->second->q_count = 0;
if( beg->q_count >= maxQueryCount ) if( beg->q_count >= maxQueryCount )
...@@ -717,7 +718,7 @@ namespace uniset ...@@ -717,7 +718,7 @@ namespace uniset
os << "[ "; os << "[ ";
for( const auto& p: lst ) for( const auto& p : lst )
os << "(" << p.si.id << ")" << conf->oind->getBaseName(conf->oind->getMapName(p.si.id)) << " "; os << "(" << p.si.id << ")" << conf->oind->getBaseName(conf->oind->getMapName(p.si.id)) << " ";
os << "]"; os << "]";
...@@ -1421,6 +1422,7 @@ namespace uniset ...@@ -1421,6 +1422,7 @@ namespace uniset
else else
r->mbval = IOBase::processingAsAO( p, shm, force_out ); r->mbval = IOBase::processingAsAO( p, shm, force_out );
} }
r->sm_initOK = true; r->sm_initOK = true;
} }
} }
...@@ -1926,6 +1928,7 @@ namespace uniset ...@@ -1926,6 +1928,7 @@ namespace uniset
long val = safeMode ? it->safeval : IOBase::processingAsAO( &(*it), shm, force_out ); long val = safeMode ? it->safeval : IOBase::processingAsAO( &(*it), shm, force_out );
MTR::T5 t(val); MTR::T5 t(val);
for( size_t k = 0; k < MTR::T5::wsize(); k++, i++ ) for( size_t k = 0; k < MTR::T5::wsize(); k++, i++ )
i->second->mbval = t.raw.v[k]; i->second->mbval = t.raw.v[k];
} }
...@@ -3510,7 +3513,7 @@ namespace uniset ...@@ -3510,7 +3513,7 @@ namespace uniset
return os; return os;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::string to_string( const MBExchange::SafeMode & m ) std::string to_string( const MBExchange::SafeMode& m )
{ {
if( m == MBExchange::safeNone ) if( m == MBExchange::safeNone )
return "safeNone"; return "safeNone";
......
...@@ -83,7 +83,7 @@ namespace uniset ...@@ -83,7 +83,7 @@ namespace uniset
}; };
friend std::string to_string( const SafeMode & m ); friend std::string to_string( const SafeMode& m );
friend std::ostream& operator<<( std::ostream& os, const SafeMode& m ); friend std::ostream& operator<<( std::ostream& os, const SafeMode& m );
enum DeviceType enum DeviceType
......
...@@ -64,8 +64,10 @@ MBTCPMaster::MBTCPMaster(uniset::ObjectId objId, uniset::ObjectId shmId, ...@@ -64,8 +64,10 @@ MBTCPMaster::MBTCPMaster(uniset::ObjectId objId, uniset::ObjectId shmId,
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
readConfiguration(); readConfiguration();
if( !noQueryOptimization ) if( !noQueryOptimization )
rtuQueryOptimization(devices); rtuQueryOptimization(devices);
initDeviceList(); initDeviceList();
} }
else else
......
...@@ -181,14 +181,16 @@ MBTCPMultiMaster::MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shm ...@@ -181,14 +181,16 @@ MBTCPMultiMaster::MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shm
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
readConfiguration(); readConfiguration();
if( !noQueryOptimization ) if( !noQueryOptimization )
rtuQueryOptimization(devices); rtuQueryOptimization(devices);
initDeviceList(); initDeviceList();
} }
else else
ic->addReadItem( sigc::mem_fun(this, &MBTCPMultiMaster::readItem) ); ic->addReadItem( sigc::mem_fun(this, &MBTCPMultiMaster::readItem) );
pollThread =unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::poll_thread); pollThread = unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::poll_thread);
pollThread->setFinalAction(this, &MBTCPMultiMaster::final_thread); pollThread->setFinalAction(this, &MBTCPMultiMaster::final_thread);
checkThread = unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::check_thread); checkThread = unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::check_thread);
checkThread->setFinalAction(this, &MBTCPMultiMaster::final_thread); checkThread->setFinalAction(this, &MBTCPMultiMaster::final_thread);
......
...@@ -85,8 +85,10 @@ RTUExchange::RTUExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const s ...@@ -85,8 +85,10 @@ RTUExchange::RTUExchange(uniset::ObjectId objId, uniset::ObjectId shmId, const s
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
readConfiguration(); readConfiguration();
if( !noQueryOptimization ) if( !noQueryOptimization )
rtuQueryOptimization(devices); rtuQueryOptimization(devices);
initDeviceList(); initDeviceList();
} }
else else
......
...@@ -683,7 +683,7 @@ TEST_CASE("MBTCPMaster: 0x66 (file transfer)", "[modbus][0x66][mbmaster][mbtcpma ...@@ -683,7 +683,7 @@ TEST_CASE("MBTCPMaster: 0x66 (file transfer)", "[modbus][0x66][mbmaster][mbtcpma
TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]") TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]")
{ {
InitTest(); InitTest();
ui->setValue(1050,0); // отключаем safeMode ui->setValue(1050, 0); // отключаем safeMode
mbs->setReply(53); mbs->setReply(53);
msleep(polltime + 200); msleep(polltime + 200);
...@@ -695,7 +695,7 @@ TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]") ...@@ -695,7 +695,7 @@ TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]")
REQUIRE( ui->getValue(1051) == 0 ); REQUIRE( ui->getValue(1051) == 0 );
REQUIRE( ui->getValue(1052) == 0 ); REQUIRE( ui->getValue(1052) == 0 );
ui->setValue(1050,42); // включаем safeMode ui->setValue(1050, 42); // включаем safeMode
msleep(polltime + 200); msleep(polltime + 200);
REQUIRE( ui->getValue(1051) == 42 ); REQUIRE( ui->getValue(1051) == 42 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
...@@ -705,7 +705,7 @@ TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]") ...@@ -705,7 +705,7 @@ TEST_CASE("MBTCPMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmaster]")
REQUIRE( ui->getValue(1051) == 42 ); REQUIRE( ui->getValue(1051) == 42 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
ui->setValue(1050,0); // отключаем safeMode ui->setValue(1050, 0); // отключаем safeMode
msleep(polltime + 200); msleep(polltime + 200);
REQUIRE( ui->getValue(1051) == 53 ); REQUIRE( ui->getValue(1051) == 53 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
......
...@@ -155,7 +155,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult ...@@ -155,7 +155,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult
{ {
InitTest(); InitTest();
ui->setValue(1050,0); // отключаем safeMode ui->setValue(1050, 0); // отключаем safeMode
mbs1->setReply(53); mbs1->setReply(53);
msleep(polltime + 200); msleep(polltime + 200);
...@@ -167,7 +167,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult ...@@ -167,7 +167,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult
REQUIRE( ui->getValue(1051) == 0 ); REQUIRE( ui->getValue(1051) == 0 );
REQUIRE( ui->getValue(1052) == 0 ); REQUIRE( ui->getValue(1052) == 0 );
ui->setValue(1050,42); // включаем safeMode ui->setValue(1050, 42); // включаем safeMode
msleep(polltime + 200); msleep(polltime + 200);
REQUIRE( ui->getValue(1051) == 42 ); REQUIRE( ui->getValue(1051) == 42 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
...@@ -178,7 +178,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult ...@@ -178,7 +178,7 @@ TEST_CASE("MBTCPMultiMaster: safe mode", "[modbus][safemode][mbmaster][mbtcpmult
REQUIRE( ui->getValue(1051) == 42 ); REQUIRE( ui->getValue(1051) == 42 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
ui->setValue(1050,0); // отключаем safeMode ui->setValue(1050, 0); // отключаем safeMode
msleep(polltime + 200); msleep(polltime + 200);
REQUIRE( ui->getValue(1051) == 53 ); REQUIRE( ui->getValue(1051) == 53 );
REQUIRE( ui->getValue(1052) == 1 ); REQUIRE( ui->getValue(1052) == 1 );
......
...@@ -801,15 +801,17 @@ namespace uniset ...@@ -801,15 +801,17 @@ namespace uniset
static size_t upCounter = 0; static size_t upCounter = 0;
upCounter++; upCounter++;
if( ++upCounter > 5 ) if( ++upCounter > 5 )
{ {
// IOMap::iterator i; // IOMap::iterator i;
// cout << "SEGFAULT: " << i->first << endl; // cout << "SEGFAULT: " << i->first << endl;
upCounter = 0; upCounter = 0;
cerr << ".....THROW...." << endl; cerr << ".....THROW...." << endl;
throw std::string("TEST STRING EXCEPTION"); throw std::string("TEST STRING EXCEPTION");
} }
#endif #endif
// ВНИМАНИЕ! Эта функция вызывается из основного eventLoop // ВНИМАНИЕ! Эта функция вызывается из основного eventLoop
...@@ -978,7 +980,7 @@ namespace uniset ...@@ -978,7 +980,7 @@ namespace uniset
else if( mbtype == "TCP") else if( mbtype == "TCP")
execute_tcp(); execute_tcp();
askTimer(tmCheckExchange,checkExchangeTime); askTimer(tmCheckExchange, checkExchangeTime);
} }
break; break;
......
...@@ -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,89 +43,98 @@ class UObject_SK: ...@@ -43,89 +43,98 @@ 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
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
/*! вывод в строку значение всех входов и выходов в формате /*! вывод в строку значение всех входов и выходов в формате
ObjectName: ObjectName:
in_xxx = val in_xxx = val
in_xxx2 = val in_xxx2 = val
out_zzz = val out_zzz = val
... ...
*/ */
std::string dumpIO(); std::string dumpIO();
/*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName) /*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName)
\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()
// ------------------------------------------------------------ {
std::string help() const noexcept; return vmon.pretty_str();
}
// ------------------------------------------------------------
std::string help() const noexcept;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// HTTP API // HTTP API
virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& p ) override;
virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
#endif #endif
...@@ -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 void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool activateObject() override; virtual bool activateObject() 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 );
...@@ -177,7 +192,7 @@ class UObject_SK: ...@@ -177,7 +192,7 @@ class UObject_SK:
void updateOutputs( bool force ); void updateOutputs( bool force );
void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId ); void waitSM( int wait_msec, uniset::ObjectId testID = uniset::DefaultObjectId );
uniset::ObjectId getSMTestID(); uniset::ObjectId getSMTestID() const;
void resetMsg(); void resetMsg();
uniset::Trigger trResetMsg; uniset::Trigger trResetMsg;
...@@ -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; std::atomic_bool activated;
...@@ -244,16 +265,16 @@ class UObject_SK: ...@@ -244,16 +265,16 @@ class UObject_SK:
class StatHashFn class StatHashFn
{ {
public: public:
size_t operator() (const uniset::ObjectId& key) const size_t operator() (const uniset::ObjectId& key) const
{ {
return std::hash<long>()(key); return std::hash<long>()(key);
} }
}; };
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()) */
......
...@@ -635,6 +635,7 @@ namespace uniset ...@@ -635,6 +635,7 @@ namespace uniset
std::string ssafe = initProp(it, "safeval", prefix, init_prefix_only); std::string ssafe = initProp(it, "safeval", prefix, init_prefix_only);
b->safevalDefined = !ssafe.empty(); b->safevalDefined = !ssafe.empty();
if( b->safevalDefined ) if( b->safevalDefined )
b->safeval = uni_atoi(ssafe); b->safeval = uni_atoi(ssafe);
......
...@@ -32,28 +32,28 @@ using namespace uniset; ...@@ -32,28 +32,28 @@ using namespace uniset;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK(): UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables (public and proteced) // variables (public and proteced)
// ------------------ // ------------------
active(false), active(false),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(0), confnode(0),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(2000), askPause(2000),
forceOut(false), forceOut(false),
// private variables // private variables
end_private(false) end_private(false)
{ {
mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl; mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception( std::string(myname+": init failed!!!") ); throw uniset::Exception( std::string(myname + ": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
...@@ -61,6 +61,7 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -61,6 +61,7 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{ {
if( !s1.empty() ) if( !s1.empty() )
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
...@@ -74,41 +75,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop ) ...@@ -74,41 +75,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
auto conf = uniset_conf(); auto conf = uniset_conf();
if( conf->getProp(cnode,prop).empty() ) if( conf->getProp(cnode, prop).empty() )
return conf->getLocalNode(); return conf->getLocalNode();
return conf->getNodeID(conf->getProp(cnode,prop)); return conf->getNodeID(conf->getProp(cnode, prop));
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ): UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ):
UniSetObject(id), UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables // variables
sleep_msec(150), sleep_msec(150),
active(true), active(true),
argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ), argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)), askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)),
forceOut(false), forceOut(false),
end_private(false) end_private(false)
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
if( uniset::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 ) if( uniset::findArgParam("--print-id-list", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 )
{ {
// abort(); // abort();
} }
...@@ -119,15 +120,15 @@ end_private(false) ...@@ -119,15 +120,15 @@ end_private(false)
throw uniset::SystemError( err.str() ); throw uniset::SystemError( err.str() );
} }
mylog = make_shared<DebugStream>(); mylog = make_shared<DebugStream>();
mylog->setLogName(myname); mylog->setLogName(myname);
{ {
ostringstream s; ostringstream s;
s << argprefix << "log"; s << argprefix << "log";
conf->initLogStream(mylog,s.str()); conf->initLogStream(mylog, s.str());
} }
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(mylog); loga->add(mylog);
loga->add(ulog()); loga->add(ulog());
...@@ -145,12 +146,14 @@ end_private(false) ...@@ -145,12 +146,14 @@ end_private(false)
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId()); logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
} }
forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false); forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() ) if( !heart.empty() )
{ {
idHeartBeat = conf->getSensorID(heart); idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId ) if( idHeartBeat == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
...@@ -158,13 +161,14 @@ end_private(false) ...@@ -158,13 +161,14 @@ end_private(false)
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime());
if( heartbeatTime>0 )
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10); maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10);
} }
// Инициализация значений // Инициализация значений
...@@ -173,16 +177,18 @@ end_private(false) ...@@ -173,16 +177,18 @@ end_private(false)
si.id = uniset::DefaultObjectId; si.id = uniset::DefaultObjectId;
si.node = conf->getLocalNode(); si.node = conf->getLocalNode();
sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec","150", 150); sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec", "150", 150);
string s_resetTime(""); string s_resetTime("");
if( s_resetTime.empty() ) if( s_resetTime.empty() )
s_resetTime = "500"; s_resetTime = "500";
resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"),conf->getProp(cnode,"resetMsgTime"),s_resetTime)); resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"), conf->getProp(cnode, "resetMsgTime"), s_resetTime));
ptResetMsg.setTiming(resetMsgTime); ptResetMsg.setTiming(resetMsgTime);
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout",""); int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", "");
if( sm_tout == 0 ) if( sm_tout == 0 )
smReadyTimeout = conf->getNCReadyTimeout(); smReadyTimeout = conf->getNCReadyTimeout();
else if( sm_tout < 0 ) else if( sm_tout < 0 )
...@@ -190,7 +196,7 @@ end_private(false) ...@@ -190,7 +196,7 @@ end_private(false)
else else
smReadyTimeout = sm_tout; smReadyTimeout = sm_tout;
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),"")); smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"), conf->getProp(cnode, "smTestID"), ""));
if( smTestID == DefaultObjectId ) if( smTestID == DefaultObjectId )
...@@ -217,7 +223,7 @@ end_private(false) ...@@ -217,7 +223,7 @@ end_private(false)
// help надо выводить в конце, когда уже все переменные инициализированы по умолчанию // help надо выводить в конце, когда уже все переменные инициализированы по умолчанию
if( uniset::findArgParam("--" + argprefix + "help",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 ) if( uniset::findArgParam("--" + argprefix + "help", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 )
cout << help() << endl; cout << help() << endl;
} }
...@@ -251,29 +257,29 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept ...@@ -251,29 +257,29 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
return false; return false;
} }
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl; mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс // взводим автоматический сброс
if( _state ) if( _state )
{ {
ptResetMsg.reset(); ptResetMsg.reset();
trResetMsg.hi(false); trResetMsg.hi(false);
} }
mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl; mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl;
return false; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
{ {
mylog8 << myname << "(resetMsg): reset messages.." << endl; mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages // reset messages
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::ObjectId UObject_SK::getSMTestID() uniset::ObjectId UObject_SK::getSMTestID() const
{ {
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
...@@ -298,11 +304,11 @@ Poco::JSON::Object::Ptr UObject_SK::httpDumpIO() ...@@ -298,11 +304,11 @@ Poco::JSON::Object::Ptr UObject_SK::httpDumpIO()
{ {
Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object(); Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata,"in"); Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata, "in");
Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata,"out"); Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata, "out");
...@@ -327,19 +333,23 @@ std::string UObject_SK::dumpIO() ...@@ -327,19 +333,23 @@ std::string UObject_SK::dumpIO()
s << endl; s << endl;
int n = 0; int n = 0;
for( const auto& e: v_in )
for( const auto& e : v_in )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
s << endl; s << endl;
n = 0; n = 0;
for( const auto& e: v_out )
for( const auto& e : v_out )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
...@@ -393,11 +403,11 @@ void UObject_SK::processingMessage( const uniset::VoidMessage* _msg ) ...@@ -393,11 +403,11 @@ void UObject_SK::processingMessage( const uniset::VoidMessage* _msg )
case Message::Timer: case Message::Timer:
preTimerInfo( reinterpret_cast<const TimerMessage*>(_msg) ); preTimerInfo( reinterpret_cast<const TimerMessage*>(_msg) );
break; break;
case Message::SysCommand: case Message::SysCommand:
preSysCommand( reinterpret_cast<const SystemMessage*>(_msg) ); preSysCommand( reinterpret_cast<const SystemMessage*>(_msg) );
break; break;
default: default:
break; break;
...@@ -418,14 +428,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -418,14 +428,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{ {
case SystemMessage::WatchDog: case SystemMessage::WatchDog:
myinfo << myname << "(preSysCommand): WatchDog" << endl; myinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() ) if( !active || !ptStartUpTimeout.checkTime() )
{ {
mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl; mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break; break;
} }
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
ostate = "StartUp..."; ostate = "StartUp...";
try try
{ {
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() ) if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
...@@ -475,9 +488,10 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -475,9 +488,10 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
// переоткрываем логи // переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl; mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() ); string fname( log()->getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
mylog->logFile(fname.c_str(),true); mylog->logFile(fname.c_str(), true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl; mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
} }
...@@ -532,8 +546,10 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) ...@@ -532,8 +546,10 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << "statistics: " << endl inf << "statistics: " << endl
<< " processingMessageCatchCount: " << processingMessageCatchCount << endl; << " processingMessageCatchCount: " << processingMessageCatchCount << endl;
inf << " Type of messages: " << endl; inf << " Type of messages: " << endl;
for( const auto& s: msgTypeStat )
for( const auto& s : msgTypeStat )
inf << " (" << s.first << ")" << setw(10) << getTypeOfMessage(s.first) << ": " << setw(5) << s.second << endl; inf << " (" << s.first << ")" << setw(10) << getTypeOfMessage(s.first) << ": " << setw(5) << s.second << endl;
inf << endl; inf << endl;
...@@ -541,14 +557,16 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) ...@@ -541,14 +557,16 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << endl; inf << endl;
auto timers = getTimersList(); auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl; inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t: timers )
for( const auto& t : timers )
{ {
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec=" inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval() << setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS << " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 ) << " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 )
<< endl; << endl;
} }
inf << endl; inf << endl;
inf << vmon.pretty_str() << endl; inf << vmon.pretty_str() << endl;
inf << endl; inf << endl;
...@@ -566,49 +584,53 @@ Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& p ...@@ -566,49 +584,53 @@ Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& p
Poco::JSON::Object::Ptr json = UniSetObject::httpGet(params); Poco::JSON::Object::Ptr json = UniSetObject::httpGet(params);
Poco::JSON::Object::Ptr jdata = json->getObject(myname); Poco::JSON::Object::Ptr jdata = json->getObject(myname);
if( !jdata ) if( !jdata )
jdata = uniset::json::make_child(json,myname); jdata = uniset::json::make_child(json, myname);
Poco::JSON::Object::Ptr jserv = uniset::json::make_child(jdata, "LogServer");
Poco::JSON::Object::Ptr jserv = uniset::json::make_child(jdata,"LogServer");
if( logserv ) if( logserv )
{ {
jserv->set("host",logserv_host); jserv->set("host", logserv_host);
jserv->set("port",logserv_port); jserv->set("port", logserv_port);
jserv->set("state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" )); jserv->set("state", ( logserv->isRunning() ? "RUNNIG" : "STOPPED" ));
jserv->set("info", logserv->httpGetShortInfo()); jserv->set("info", logserv->httpGetShortInfo());
} }
jdata->set("io", httpDumpIO()); jdata->set("io", httpDumpIO());
auto timers = getTimersList(); auto timers = getTimersList();
auto jtm = uniset::json::make_child(jdata,"Timers"); auto jtm = uniset::json::make_child(jdata, "Timers");
jtm->set("count", timers.size());
jtm->set("count",timers.size()); for( const auto& t : timers )
for( const auto& t: timers )
{ {
auto jt = uniset::json::make_child(jtm,to_string(t.id)); auto jt = uniset::json::make_child(jtm, to_string(t.id));
jt->set("id", t.id); jt->set("id", t.id);
jt->set("name", getTimerName(t.id)); jt->set("name", getTimerName(t.id));
jt->set("msec", t.tmr.getInterval()); jt->set("msec", t.tmr.getInterval());
jt->set("timeleft", t.curTimeMS); jt->set("timeleft", t.curTimeMS);
jt->set("tick", ( t.curTick>=0 ? t.curTick : -1 )); jt->set("tick", ( t.curTick >= 0 ? t.curTick : -1 ));
} }
auto vlist = vmon.getList(); auto vlist = vmon.getList();
auto jvmon = uniset::json::make_child(jdata,"Variables"); auto jvmon = uniset::json::make_child(jdata, "Variables");
for( const auto& v: vlist ) for( const auto& v : vlist )
jvmon->set(v.first,v.second); jvmon->set(v.first, v.second);
auto jstat = uniset::json::make_child(jdata,"Statistics"); auto jstat = uniset::json::make_child(jdata, "Statistics");
jstat->set("processingMessageCatchCount", processingMessageCatchCount); jstat->set("processingMessageCatchCount", processingMessageCatchCount);
auto jsens = uniset::json::make_child(jstat,"sensors"); auto jsens = uniset::json::make_child(jstat, "sensors");
for( const auto& s: smStat )
for( const auto& s : smStat )
{ {
std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first))); std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first)));
auto js = uniset::json::make_child(jsens,sname); auto js = uniset::json::make_child(jsens, sname);
js->set("id", s.first); js->set("id", s.first);
js->set("name", sname); js->set("name", sname);
js->set("count", s.second); js->set("count", s.second);
...@@ -625,7 +647,7 @@ Poco::JSON::Object::Ptr UObject_SK::httpHelp( const Poco::URI::QueryParameters& ...@@ -625,7 +647,7 @@ Poco::JSON::Object::Ptr UObject_SK::httpHelp( const Poco::URI::QueryParameters&
uniset::json::help::object myhelp(myname, UniSetObject::httpGet(params)); uniset::json::help::object myhelp(myname, UniSetObject::httpGet(params));
// 'log' // 'log'
uniset::json::help::item cmd("log","show log level"); uniset::json::help::item cmd("log", "show log level");
myhelp.add(cmd); myhelp.add(cmd);
return myhelp; return myhelp;
...@@ -636,13 +658,13 @@ Poco::JSON::Object::Ptr UObject_SK::httpRequest( const std::string& req, const P ...@@ -636,13 +658,13 @@ Poco::JSON::Object::Ptr UObject_SK::httpRequest( const std::string& req, const P
if( req == "log" ) if( req == "log" )
return httpRequestLog(p); return httpRequestLog(p);
return UniSetObject::httpRequest(req,p); return UniSetObject::httpRequest(req, p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Poco::JSON::Object::Ptr UObject_SK::httpRequestLog( const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UObject_SK::httpRequestLog( const Poco::URI::QueryParameters& p )
{ {
Poco::JSON::Object::Ptr jret = new Poco::JSON::Object(); Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
jret->set("log",Debug::str(mylog->level())); jret->set("log", Debug::str(mylog->level()));
return jret; return jret;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -688,23 +710,23 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -688,23 +710,23 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
return; return;
myinfo << myname << "(waitSM): waiting SM ready " myinfo << myname << "(waitSM): waiting SM ready "
<< wait_msec << " msec" << wait_msec << " msec"
<< " testID=" << _testID << endl; << " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController // waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID,wait_msec) ) if( !ui->waitReady(_testID, wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
<< wait_msec << " мсек"; << wait_msec << " мсек";
mycrit << err.str() << endl; mycrit << err.str() << endl;
std::abort(); std::abort();
// throw uniset::SystemError(err.str()); // throw uniset::SystemError(err.str());
} }
if( !ui->waitWorking(_testID,wait_msec) ) if( !ui->waitWorking(_testID, wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
...@@ -713,7 +735,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -713,7 +735,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit << err.str() << endl; mycrit << err.str() << endl;
std::abort(); std::abort();
// throw uniset::SystemError(err.str()); // throw uniset::SystemError(err.str());
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -731,9 +753,9 @@ std::string UObject_SK::help() const noexcept ...@@ -731,9 +753,9 @@ std::string UObject_SK::help() const noexcept
s << "--" << argprefix << "activate-timeout msec - activate process timeout. Now: " << activateTimeout << endl; s << "--" << argprefix << "activate-timeout msec - activate process timeout. Now: " << activateTimeout << endl;
s << "--" << argprefix << "startup-timeout msec - wait startup timeout. Now: " << ptStartUpTimeout.getInterval() << endl; s << "--" << argprefix << "startup-timeout msec - wait startup timeout. Now: " << ptStartUpTimeout.getInterval() << endl;
s << "--" << argprefix << "force-out [0|1] - 1 - save out-values in SM at each step. Now: " << forceOut << endl; s << "--" << argprefix << "force-out [0|1] - 1 - save out-values in SM at each step. Now: " << forceOut << endl;
s << "--" << argprefix << "heartbeat-max num - max value for heartbeat counter. Now: " << maxHeartBeat << endl; s << "--" << argprefix << "heartbeat-max num - max value for heartbeat counter. Now: " << maxHeartBeat << endl;
s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl; s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl;
s << endl; s << endl;
s << "--print-id-list - print ID list" << endl; s << "--print-id-list - print ID list" << endl;
s << endl; s << endl;
...@@ -749,39 +771,42 @@ void UObject_SK::callback() noexcept ...@@ -749,39 +771,42 @@ void UObject_SK::callback() noexcept
{ {
if( !active ) if( !active )
return; return;
try try
{ {
// проверка таймеров // проверка таймеров
checkTimers(this); checkTimers(this);
if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) ) if( resetMsgTime > 0 && trResetMsg.hi(ptResetMsg.checkTime()) )
{ {
// cout << myname << ": ********* reset messages *********" << endl; // cout << myname << ": ********* reset messages *********" << endl;
resetMsg(); resetMsg();
} }
// обработка сообщений (таймеров и т.п.) // обработка сообщений (таймеров и т.п.)
for( unsigned int i=0; i<20; i++ ) for( unsigned int i = 0; i < 20; i++ )
{ {
auto m = receiveMessage(); auto m = receiveMessage();
if( !m )
break; if( !m )
processingMessage(m.get()); break;
processingMessage(m.get());
updateOutputs(forceOut); updateOutputs(forceOut);
// updatePreviousValues(); // updatePreviousValues();
} }
// Выполнение шага программы // Выполнение шага программы
step(); step();
// "сердцебиение" // "сердцебиение"
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() ) if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
{ {
try try
{ {
ui->setValue(idHeartBeat,maxHeartBeat); ui->setValue(idHeartBeat, maxHeartBeat);
ptHeartBeat.reset(); ptHeartBeat.reset();
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
...@@ -796,17 +821,17 @@ void UObject_SK::callback() noexcept ...@@ -796,17 +821,17 @@ void UObject_SK::callback() noexcept
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
mycrit << myname << "(execute): " << ex << endl; mycrit << myname << "(execute): " << ex << endl;
} }
catch( const CORBA::SystemException& ex ) catch( const CORBA::SystemException& ex )
{ {
mycrit << myname << "(execute): СORBA::SystemException: " mycrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
if( !active ) if( !active )
return; return;
...@@ -821,7 +846,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val ) ...@@ -821,7 +846,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
ui->setValue(_sid,_val); ui->setValue(_sid, _val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
...@@ -843,7 +868,7 @@ void UObject_SK::initFromSM() ...@@ -843,7 +868,7 @@ void UObject_SK::initFromSM()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::askSensor( uniset::ObjectId _sid, UniversalIO::UIOCommand _cmd, uniset::ObjectId _node ) void UObject_SK::askSensor( uniset::ObjectId _sid, UniversalIO::UIOCommand _cmd, uniset::ObjectId _node )
{ {
ui->askRemoteSensor(_sid,_cmd,_node,getId()); ui->askRemoteSensor(_sid, _cmd, _node, getId());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long UObject_SK::getValue( uniset::ObjectId _sid ) long UObject_SK::getValue( uniset::ObjectId _sid )
...@@ -856,7 +881,7 @@ long UObject_SK::getValue( uniset::ObjectId _sid ) ...@@ -856,7 +881,7 @@ long UObject_SK::getValue( uniset::ObjectId _sid )
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
mycrit << myname << "(getValue): " << ex << endl; mycrit << myname << "(getValue): " << ex << endl;
throw; throw;
} }
} }
...@@ -865,17 +890,19 @@ long UObject_SK::getValue( uniset::ObjectId _sid ) ...@@ -865,17 +890,19 @@ long UObject_SK::getValue( uniset::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !activated && !ptAct.checkTime() )
{ {
cout << myname << "(preAskSensors): wait activate..." << endl; cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300); msleep(300);
if( activated ) if( activated )
break; break;
} }
if( !activated ) if( !activated )
mycrit << myname mycrit << myname
<< "(preAskSensors): ************* don`t activated?! ************" << endl; << "(preAskSensors): ************* don`t activated?! ************" << endl;
for( ;; ) for( ;; )
{ {
...@@ -886,12 +913,12 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) ...@@ -886,12 +913,12 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
} }
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
mycrit << myname << "(preAskSensors): " << ex << endl; mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception&ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
msleep(askPause); msleep(askPause);
} }
......
...@@ -180,7 +180,7 @@ namespace uniset ...@@ -180,7 +180,7 @@ namespace uniset
static std::vector<std::string> splitFirst( const std::string& lname, const std::string s = "/" ); static std::vector<std::string> splitFirst( const std::string& lname, const std::string s = "/" );
std::ostream& printLogList( std::ostream& os, const std::string& regexp_str = "" ); std::ostream& printLogList( std::ostream& os, const std::string& regexp_str = "" ) const;
static std::ostream& printLogList( std::ostream& os, std::list<iLog>& lst ); static std::ostream& printLogList( std::ostream& os, std::list<iLog>& lst );
protected: protected:
...@@ -192,7 +192,7 @@ namespace uniset ...@@ -192,7 +192,7 @@ namespace uniset
std::shared_ptr<DebugStream> findLog( const std::string& lname ) const; std::shared_ptr<DebugStream> findLog( const std::string& lname ) const;
// вывод в виде "дерева" // вывод в виде "дерева"
std::ostream& printTree(std::ostream& os, const std::string& g_tab = ""); std::ostream& printTree(std::ostream& os, const std::string& g_tab = "") const;
// получить список с именами (длинными) и с указателями на логи // получить список с именами (длинными) и с указателями на логи
std::list<iLog> makeLogNameList( const std::string& prefix ) const; std::list<iLog> makeLogNameList( const std::string& prefix ) const;
......
...@@ -178,10 +178,10 @@ namespace uniset ...@@ -178,10 +178,10 @@ namespace uniset
void read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNode* node, IONotifyController* ic); void read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNode* node, IONotifyController* ic);
void init( const std::string& fname ); void init( const std::string& fname );
bool getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, IOController_i::SensorInfo& si ); bool getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, IOController_i::SensorInfo& si ) const;
bool getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* snode, std::shared_ptr<NCRestorer_XML::SInfo>& si ); bool getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* snode, std::shared_ptr<NCRestorer_XML::SInfo>& si ) const;
bool getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNode* node, IONotifyController::ConsumerListInfo& lst); bool getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNode* node, IONotifyController::ConsumerListInfo& lst) const;
bool getThresholdInfo(const std::shared_ptr<UniXML>& xml, xmlNode* tnode, IONotifyController::ThresholdInfoExt& ti); bool getThresholdInfo(const std::shared_ptr<UniXML>& xml, xmlNode* tnode, IONotifyController::ThresholdInfoExt& ti) const;
static void set_dumptime( const std::shared_ptr<UniXML>& xml, xmlNode* node ); static void set_dumptime( const std::shared_ptr<UniXML>& xml, xmlNode* node );
static xmlNode* bind_node( const std::shared_ptr<UniXML>& xml, xmlNode* root, const std::string& nodename, const std::string& nm = ""); static xmlNode* bind_node( const std::shared_ptr<UniXML>& xml, xmlNode* root, const std::string& nodename, const std::string& nm = "");
......
...@@ -54,19 +54,19 @@ namespace uniset ...@@ -54,19 +54,19 @@ namespace uniset
@{ */ @{ */
//! Функция регистрации объекта по имени с указанием секции //! Функция регистрации объекта по имени с указанием секции
void registration(const std::string& name, const uniset::ObjectPtr oRef, const std::string& section, bool force = false) const void registration(const std::string& name, const uniset::ObjectPtr oRef, const std::string& section, bool force = false) const
throw(uniset::ORepFailed, uniset::ObjectNameAlready, uniset::InvalidObjectName, uniset::NameNotFound); throw(uniset::ORepFailed, uniset::ObjectNameAlready, uniset::InvalidObjectName, uniset::NameNotFound);
//! Функция регистрации объекта по полному имени. //! Функция регистрации объекта по полному имени.
void registration(const std::string& fullName, const uniset::ObjectPtr oRef, bool force = false) const void registration(const std::string& fullName, const uniset::ObjectPtr oRef, bool force = false) const
throw(uniset::ORepFailed, uniset::ObjectNameAlready, uniset::InvalidObjectName, uniset::NameNotFound); throw(uniset::ORepFailed, uniset::ObjectNameAlready, uniset::InvalidObjectName, uniset::NameNotFound);
//! Удаление записи об объекте name в секции section //! Удаление записи об объекте name в секции section
void unregistration(const std::string& name, const std::string& section) const void unregistration(const std::string& name, const std::string& section) const
throw(uniset::ORepFailed, uniset::NameNotFound); throw(uniset::ORepFailed, uniset::NameNotFound);
//! Удаление записи об объекте по полному имени //! Удаление записи об объекте по полному имени
void unregistration(const std::string& fullName) const void unregistration(const std::string& fullName) const
throw(uniset::ORepFailed, uniset::NameNotFound); throw(uniset::ORepFailed, uniset::NameNotFound);
// @} // @}
// end of ORepGroup // end of ORepGroup
...@@ -99,11 +99,11 @@ namespace uniset ...@@ -99,11 +99,11 @@ namespace uniset
// ------------------------------------------------------------------- // -------------------------------------------------------------------
//! Создание секции //! Создание секции
bool createSection( const std::string& name, const std::string& in_section ) const bool createSection( const std::string& name, const std::string& in_section ) const
throw(uniset::ORepFailed, uniset::InvalidObjectName); throw(uniset::ORepFailed, uniset::InvalidObjectName);
/*! Создание секции по полному имени */ /*! Создание секции по полному имени */
bool createSectionF(const std::string& fullName) const bool createSectionF(const std::string& fullName) const
throw(uniset::ORepFailed, uniset::InvalidObjectName); throw(uniset::ORepFailed, uniset::InvalidObjectName);
//! Функция создания секции в корневом 'каталоге' //! Функция создания секции в корневом 'каталоге'
bool createRootSection( const std::string& name ) const; bool createRootSection( const std::string& name ) const;
......
...@@ -94,15 +94,15 @@ namespace uniset ...@@ -94,15 +94,15 @@ namespace uniset
\return true - если идентификаторы определены \return true - если идентификаторы определены
*/ */
bool getConsumerInfo( UniXML::iterator& it, bool getConsumerInfo( UniXML::iterator& it,
uniset::ObjectId& cid, uniset::ObjectId& cnode ); uniset::ObjectId& cid, uniset::ObjectId& cnode ) const;
/*! Функция поиска по текущему уровню (без рекурсии для дочерних узлов) */ /*! Функция поиска по текущему уровню (без рекурсии для дочерних узлов) */
static xmlNode* find_node( const std::shared_ptr<UniXML>& xml, xmlNode* root, const std::string& nodename, const std::string& nm = "" ); static xmlNode* find_node( const std::shared_ptr<UniXML>& xml, xmlNode* root, const std::string& nodename, const std::string& nm = "" );
protected: protected:
virtual bool check_list_item( UniXML::iterator& it ); virtual bool check_list_item( UniXML::iterator& it ) const;
virtual bool check_consumer_item( UniXML::iterator& it ); virtual bool check_consumer_item( UniXML::iterator& it ) const;
ReaderSlot rslot; ReaderSlot rslot;
ReaderSlot cslot; ReaderSlot cslot;
......
...@@ -248,7 +248,7 @@ namespace uniset ...@@ -248,7 +248,7 @@ namespace uniset
MaxSize(maxsize), minCallCount(cleancount) {}; MaxSize(maxsize), minCallCount(cleancount) {};
~CacheOfResolve() {}; ~CacheOfResolve() {};
uniset::ObjectPtr resolve( const uniset::ObjectId id, const uniset::ObjectId node ) const throw(uniset::NameNotFound,uniset::SystemError); uniset::ObjectPtr resolve( const uniset::ObjectId id, const uniset::ObjectId node ) const throw(uniset::NameNotFound, uniset::SystemError);
void cache(const uniset::ObjectId id, const uniset::ObjectId node, uniset::ObjectVar& ptr ) const; void cache(const uniset::ObjectId id, const uniset::ObjectId node, uniset::ObjectVar& ptr ) const;
void erase( const uniset::ObjectId id, const uniset::ObjectId node ) const noexcept; void erase( const uniset::ObjectId id, const uniset::ObjectId node ) const noexcept;
......
...@@ -24,9 +24,9 @@ namespace uniset ...@@ -24,9 +24,9 @@ namespace uniset
Buffer( const std::string& s ); Buffer( const std::string& s );
virtual ~Buffer(); virtual ~Buffer();
unsigned char* dpos() noexcept; unsigned char* dpos() const noexcept;
size_t nbytes() noexcept; size_t nbytes() const noexcept;
unsigned char* data = { 0 }; unsigned char* data = { 0 };
size_t len; size_t len;
......
...@@ -27,7 +27,7 @@ namespace uniset ...@@ -27,7 +27,7 @@ namespace uniset
// return true if OK // return true if OK
bool setKeepAliveParams( timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ); bool setKeepAliveParams( timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 );
int getSocket() noexcept; int getSocket() const noexcept;
protected: protected:
void init(); void init();
......
...@@ -39,7 +39,7 @@ namespace uniset ...@@ -39,7 +39,7 @@ namespace uniset
void create( const std::string& hname, uint16_t port, timeout_t tout_msec = 1000 ); void create( const std::string& hname, uint16_t port, timeout_t tout_msec = 1000 );
bool isConnected() noexcept; bool isConnected() const noexcept;
// set keepalive params // set keepalive params
// return true if OK // return true if OK
......
...@@ -122,7 +122,7 @@ namespace uniset ...@@ -122,7 +122,7 @@ namespace uniset
return lst.empty(); return lst.empty();
} }
std::list<ObjectId> getList() noexcept; std::list<ObjectId> getList() const noexcept;
// за освобождение выделеной памяти // за освобождение выделеной памяти
// отвечает вызывающий! // отвечает вызывающий!
...@@ -322,7 +322,10 @@ namespace uniset ...@@ -322,7 +322,10 @@ namespace uniset
{ {
public: public:
ios_fmt_restorer( std::ostream& s ): ios_fmt_restorer( std::ostream& s ):
os(s),f(nullptr){ f.copyfmt(s); } os(s), f(nullptr)
{
f.copyfmt(s);
}
~ios_fmt_restorer() ~ios_fmt_restorer()
{ {
......
...@@ -196,7 +196,7 @@ namespace uniset ...@@ -196,7 +196,7 @@ namespace uniset
} }
}; };
std::unique_ptr<xmlDoc,UniXMLDocDeleter> doc; std::unique_ptr<xmlDoc, UniXMLDocDeleter> doc;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
......
...@@ -124,13 +124,13 @@ namespace uniset ...@@ -124,13 +124,13 @@ namespace uniset
static const int ColCount = { 2 }; static const int ColCount = { 2 };
/*! вывести все элементы в "простом формате" (строки "varname = value") */ /*! вывести все элементы в "простом формате" (строки "varname = value") */
std::string str(); std::string str() const;
/*! вывести все элементы "с форматированием" (отсортированные по алфавиту) /*! вывести все элементы "с форматированием" (отсортированные по алфавиту)
* \param namewidth - ширина резервируемая под "имя" * \param namewidth - ширина резервируемая под "имя"
* \param colnum - количество столбцов вывода * \param colnum - количество столбцов вывода
*/ */
std::string pretty_str( int namewidth = NameWidth, int colnum = ColCount ); std::string pretty_str( int namewidth = NameWidth, int colnum = ColCount ) const;
// перегрузки для стандартных типов.. // перегрузки для стандартных типов..
VMON_DEF_FUNC2(int); VMON_DEF_FUNC2(int);
...@@ -150,7 +150,7 @@ namespace uniset ...@@ -150,7 +150,7 @@ namespace uniset
static const std::string pretty_str( const std::string& name, const std::string* v, int width = NameWidth ); static const std::string pretty_str( const std::string& name, const std::string* v, int width = NameWidth );
static const std::string pretty_str( const std::string& name, const std::string& v, int width = NameWidth ); static const std::string pretty_str( const std::string& name, const std::string& v, int width = NameWidth );
std::list<std::pair<std::string, std::string>> getList(); std::list<std::pair<std::string, std::string>> getList() const;
protected: protected:
......
...@@ -25,14 +25,15 @@ ...@@ -25,14 +25,15 @@
#include <memory> #include <memory>
#include <utility> #include <utility>
namespace unisetstd { namespace unisetstd
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{ {
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
} template<typename T, typename ...Args>
// -------------------------------------------------------------------------- std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
// --------------------------------------------------------------------------
} // end of namespace unisetcpp } // end of namespace unisetcpp
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#endif #endif
...@@ -147,7 +147,7 @@ namespace uniset ...@@ -147,7 +147,7 @@ namespace uniset
ioTimer.set(loop); ioTimer.set(loop);
if( tmTime_msec != UniSetTimer::WaitUpTime ) if( tmTime_msec != UniSetTimer::WaitUpTime )
ioTimer.start(0,tmTime); ioTimer.start(0, tmTime);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void ModbusTCPServer::terminate() void ModbusTCPServer::terminate()
......
...@@ -495,6 +495,7 @@ namespace uniset ...@@ -495,6 +495,7 @@ namespace uniset
os << "["; os << "[";
int max = d.b.size(); int max = d.b.size();
if( max > 0 ) if( max > 0 )
max--; max--;
...@@ -3071,13 +3072,13 @@ namespace uniset ...@@ -3071,13 +3072,13 @@ namespace uniset
ostringstream s; ostringstream s;
s << setfill('0') s << setfill('0')
<< setw(2) << (int)m.day << "-" << setw(2) << (int)m.day << "-"
<< setw(2) << (int)m.mon << "-" << setw(2) << (int)m.mon << "-"
<< setw(2) << (int)m.century << setw(2) << (int)m.century
<< setw(2) << (int)m.year << " " << setw(2) << (int)m.year << " "
<< setw(2) << (int)m.hour << ":" << setw(2) << (int)m.hour << ":"
<< setw(2) << (int)m.min << ":" << setw(2) << (int)m.min << ":"
<< setw(2) << (int)m.sec; << setw(2) << (int)m.sec;
return os << s.str(); return os << s.str();
} }
......
...@@ -56,12 +56,12 @@ namespace uniset ...@@ -56,12 +56,12 @@ namespace uniset
delete [] data; delete [] data;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
unsigned char* UTCPCore::Buffer::dpos() noexcept unsigned char* UTCPCore::Buffer::dpos() const noexcept
{ {
return data + pos; return data + pos;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
size_t UTCPCore::Buffer::nbytes() noexcept size_t UTCPCore::Buffer::nbytes() const noexcept
{ {
return len - pos; return len - pos;
} }
......
...@@ -44,7 +44,7 @@ namespace uniset ...@@ -44,7 +44,7 @@ namespace uniset
return UTCPCore::setKeepAliveParams(Poco::Net::ServerSocket::sockfd() , timeout_sec, keepcnt, keepintvl); return UTCPCore::setKeepAliveParams(Poco::Net::ServerSocket::sockfd() , timeout_sec, keepcnt, keepintvl);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
int UTCPSocket::getSocket() noexcept int UTCPSocket::getSocket() const noexcept
{ {
return Poco::Net::ServerSocket::sockfd(); return Poco::Net::ServerSocket::sockfd();
} }
......
...@@ -116,7 +116,7 @@ namespace uniset ...@@ -116,7 +116,7 @@ namespace uniset
setKeepAliveParams(); setKeepAliveParams();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool UTCPStream::isConnected() noexcept bool UTCPStream::isConnected() const noexcept
{ {
return ( Poco::Net::StreamSocket::sockfd() != POCO_INVALID_SOCKET ); return ( Poco::Net::StreamSocket::sockfd() != POCO_INVALID_SOCKET );
/* /*
......
...@@ -1265,7 +1265,7 @@ namespace uniset ...@@ -1265,7 +1265,7 @@ namespace uniset
} }
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
uniset::ObjectPtr UInterface::CacheOfResolve::resolve( const uniset::ObjectId id, const uniset::ObjectId node ) const uniset::ObjectPtr UInterface::CacheOfResolve::resolve( const uniset::ObjectId id, const uniset::ObjectId node ) const
throw(uniset::NameNotFound,uniset::SystemError) throw(uniset::NameNotFound, uniset::SystemError)
{ {
try try
{ {
......
...@@ -216,6 +216,7 @@ bool gdb_print_trace() ...@@ -216,6 +216,7 @@ bool gdb_print_trace()
sprintf(pid_buf, "%d", getpid()); sprintf(pid_buf, "%d", getpid());
char name_buf[512]; char name_buf[512];
ssize_t ind = readlink("/proc/self/exe", name_buf, 511); ssize_t ind = readlink("/proc/self/exe", name_buf, 511);
if( ind < 0 ) if( ind < 0 )
{ {
perror("Can't readlink..."); perror("Can't readlink...");
...@@ -301,6 +302,7 @@ static void start_terminate_process() ...@@ -301,6 +302,7 @@ static void start_terminate_process()
// посылаем сигнал потоку завершения, чтобы проснулся и начал заверешение // посылаем сигнал потоку завершения, чтобы проснулся и начал заверешение
{ {
std::unique_lock<std::mutex> lk(g_termmutex); std::unique_lock<std::mutex> lk(g_termmutex);
if( g_term ) if( g_term )
return; return;
...@@ -312,8 +314,12 @@ static void start_terminate_process() ...@@ -312,8 +314,12 @@ static void start_terminate_process()
static void wait_done() static void wait_done()
{ {
std::unique_lock<std::mutex> lk(g_donemutex); std::unique_lock<std::mutex> lk(g_donemutex);
while( !g_done ) while( !g_done )
g_doneevent.wait(lk, []() { return (g_done == true); } ); g_doneevent.wait(lk, []()
{
return (g_done == true);
} );
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
static void activator_terminate( int signo ) static void activator_terminate( int signo )
...@@ -322,6 +328,7 @@ static void activator_terminate( int signo ) ...@@ -322,6 +328,7 @@ static void activator_terminate( int signo )
return; return;
g_signo = signo; g_signo = signo;
if( signo == SIGABRT ) if( signo == SIGABRT )
{ {
if( g_act && !g_act->noUseGdbForStackTrace() ) if( g_act && !g_act->noUseGdbForStackTrace() )
...@@ -332,11 +339,12 @@ static void activator_terminate( int signo ) ...@@ -332,11 +339,12 @@ static void activator_terminate( int signo )
else else
printStackTrace(); printStackTrace();
// exit(EXIT_FAILURE); // exit(EXIT_FAILURE);
// return; // return;
} }
// else
// exit(EXIT_SUCCESS); // else
// exit(EXIT_SUCCESS);
start_terminate_process(); start_terminate_process();
} }
...@@ -495,7 +503,7 @@ namespace uniset ...@@ -495,7 +503,7 @@ namespace uniset
} }
} }
// g_act = nullptr; // g_act = nullptr;
UniSetActivator::set_signals(false); UniSetActivator::set_signals(false);
} }
......
...@@ -165,7 +165,7 @@ void uniset::IDList::del( ObjectId id ) ...@@ -165,7 +165,7 @@ void uniset::IDList::del( ObjectId id )
} }
} }
std::list<uniset::ObjectId> uniset::IDList::getList() noexcept std::list<uniset::ObjectId> uniset::IDList::getList() const noexcept
{ {
return lst; return lst;
} }
......
...@@ -170,7 +170,7 @@ namespace uniset ...@@ -170,7 +170,7 @@ namespace uniset
return findLog(logname); return findLog(logname);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& LogAgregator::printLogList( std::ostream& os, const std::string& regexp_str ) std::ostream& LogAgregator::printLogList( std::ostream& os, const std::string& regexp_str ) const
{ {
std::list<iLog> lst; std::list<iLog> lst;
...@@ -195,7 +195,7 @@ namespace uniset ...@@ -195,7 +195,7 @@ namespace uniset
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_tab ) std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_tab ) const
{ {
const std::string::size_type tab_width = 15; const std::string::size_type tab_width = 15;
......
...@@ -387,7 +387,7 @@ void LogReader::readlogs( const std::string& _addr, int _port, LogServerTypes::C ...@@ -387,7 +387,7 @@ void LogReader::readlogs( const std::string& _addr, int _port, LogServerTypes::C
{ {
// Всё это пока не оптимально, // Всё это пока не оптимально,
// но мы ведь и не спешим.. // но мы ведь и не спешим..
for( ssize_t i=0; i<n; i++ ) for( ssize_t i = 0; i < n; i++ )
{ {
// пока не встретили конец строки // пока не встретили конец строки
// наполняем line.. // наполняем line..
......
...@@ -450,7 +450,7 @@ bool ObjectRepository::isExist( const ObjectPtr& oref ) const ...@@ -450,7 +450,7 @@ bool ObjectRepository::isExist( const ObjectPtr& oref ) const
* \exception ORepFailed - генерируется если произошла при получении доступа к секции * \exception ORepFailed - генерируется если произошла при получении доступа к секции
*/ */
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 = ORepHelpers::checkBadSymbols(name);
...@@ -582,7 +582,7 @@ void ObjectRepository::printSection( const string& fullName ) const ...@@ -582,7 +582,7 @@ void ObjectRepository::printSection( const string& fullName ) const
cout << fullName << "(" << olist.size() << "):" << endl; cout << fullName << "(" << olist.size() << "):" << endl;
for( const auto& v: olist ) for( const auto& v : olist )
cout << v << endl; cout << v << endl;
} }
......
...@@ -27,6 +27,7 @@ namespace uniset ...@@ -27,6 +27,7 @@ namespace uniset
{ {
{ {
std::lock_guard<std::timed_mutex> l(run_mutex); std::lock_guard<std::timed_mutex> l(run_mutex);
if( isactive ) if( isactive )
return false; return false;
...@@ -42,7 +43,7 @@ namespace uniset ...@@ -42,7 +43,7 @@ namespace uniset
if( !run_mutex.try_lock_for(std::chrono::milliseconds(timeout_msec)) ) if( !run_mutex.try_lock_for(std::chrono::milliseconds(timeout_msec)) )
return false; return false;
std::lock_guard<std::timed_mutex> l(run_mutex,std::adopt_lock); std::lock_guard<std::timed_mutex> l(run_mutex, std::adopt_lock);
if( isactive ) if( isactive )
return true; return true;
...@@ -101,6 +102,7 @@ namespace uniset ...@@ -101,6 +102,7 @@ namespace uniset
{ {
if( thr->joinable() ) if( thr->joinable() )
thr->join(); thr->join();
thr = nullptr; thr = nullptr;
} }
} }
......
...@@ -222,7 +222,7 @@ void NCRestorer_XML::read( IONotifyController* ic, const std::shared_ptr<UniXML> ...@@ -222,7 +222,7 @@ void NCRestorer_XML::read( IONotifyController* ic, const std::shared_ptr<UniXML>
read_thresholds(xml, tnode, ic); read_thresholds(xml, tnode, ic);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, IOController_i::SensorInfo& si ) bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, IOController_i::SensorInfo& si ) const
{ {
string sname( xml->getProp(it, "name")); string sname( xml->getProp(it, "name"));
...@@ -267,7 +267,7 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i ...@@ -267,7 +267,7 @@ bool NCRestorer_XML::getBaseInfo( const std::shared_ptr<UniXML>& xml, xmlNode* i
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, std::shared_ptr<NCRestorer_XML::SInfo>& inf ) bool NCRestorer_XML::getSensorInfo( const std::shared_ptr<UniXML>& xml, xmlNode* it, std::shared_ptr<NCRestorer_XML::SInfo>& inf ) const
{ {
if( !getBaseInfo(xml, it, inf->si) ) if( !getBaseInfo(xml, it, inf->si) )
return false; return false;
...@@ -467,7 +467,7 @@ void NCRestorer_XML::read_consumers( const std::shared_ptr<UniXML>& xml, xmlNode ...@@ -467,7 +467,7 @@ void NCRestorer_XML::read_consumers( const std::shared_ptr<UniXML>& xml, xmlNode
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool NCRestorer_XML::getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNode* node, bool NCRestorer_XML::getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNode* node,
IONotifyController::ConsumerListInfo& lst ) IONotifyController::ConsumerListInfo& lst ) const
{ {
UniXML::iterator it(node); UniXML::iterator it(node);
...@@ -490,7 +490,7 @@ bool NCRestorer_XML::getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -490,7 +490,7 @@ bool NCRestorer_XML::getConsumerList( const std::shared_ptr<UniXML>& xml, xmlNod
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml, xmlNode* node, bool NCRestorer_XML::getThresholdInfo( const std::shared_ptr<UniXML>& xml, xmlNode* node,
IONotifyController::ThresholdInfoExt& ti ) IONotifyController::ThresholdInfoExt& ti ) const
{ {
UniXML::iterator uit(node); UniXML::iterator uit(node);
......
...@@ -189,8 +189,11 @@ timeout_t LT_Object::askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_ ...@@ -189,8 +189,11 @@ timeout_t LT_Object::askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_
{ {
li->curTick = ticks; li->curTick = ticks;
li->tmr.setTiming(timeMS); li->tmr.setTiming(timeMS);
uinfo << "(LT_askTimer): заказ на таймер ["
<< timerid << "]" << getTimerName(timerid) << " " << timeMS << " [мс] уже есть..." << endl; if( ulog()->debugging(loglevel) )
ulog()->debug(loglevel) << "(LT_askTimer): заказ на таймер ["
<< timerid << "]" << getTimerName(timerid) << " " << timeMS << " [мс] уже есть..." << endl;
return sleepTime; return sleepTime;
} }
} }
...@@ -200,13 +203,16 @@ timeout_t LT_Object::askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_ ...@@ -200,13 +203,16 @@ timeout_t LT_Object::askTimer( uniset::TimerId timerid, timeout_t timeMS, clock_
tlst.emplace_back(timerid, timeMS, ticks, p); tlst.emplace_back(timerid, timeMS, ticks, p);
} // unlock } // unlock
uinfo << "(LT_askTimer): поступил заказ на таймер [" << timerid << "]" if( ulog()->debugging(loglevel) )
<< getTimerName(timerid) << " " << timeMS << " [мс]\n"; ulog()->debug(loglevel) << "(LT_askTimer): поступил заказ на таймер [" << timerid << "]"
<< getTimerName(timerid) << " " << timeMS << " [мс]\n";
} }
else // отказ (при timeMS == 0) else // отказ (при timeMS == 0)
{ {
uinfo << "(LT_askTimer): поступил отказ по таймеру [" << timerid << "]" if( ulog()->debugging(loglevel) )
<< getTimerName(timerid) << endl; ulog()->debug(loglevel) << "(LT_askTimer): поступил отказ по таймеру [" << timerid << "]"
<< getTimerName(timerid) << endl;
{ {
// lock // lock
uniset_rwmutex_wrlock lock(lstMutex); uniset_rwmutex_wrlock lock(lstMutex);
......
...@@ -63,7 +63,7 @@ namespace uniset ...@@ -63,7 +63,7 @@ namespace uniset
// не знаю как по другому // не знаю как по другому
// приходиться делать это через промежуточную переменную // приходиться делать это через промежуточную переменную
std::chrono::milliseconds ms(msec); std::chrono::milliseconds ms(msec);
std::swap(t_inner_msec,ms); std::swap(t_inner_msec, ms);
PassiveTimer::reset(); PassiveTimer::reset();
return getInterval(); return getInterval();
......
...@@ -55,7 +55,7 @@ void Restorer_XML::setConsumerFilter( const string& field, const string& val ) ...@@ -55,7 +55,7 @@ void Restorer_XML::setConsumerFilter( const string& field, const string& val )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool Restorer_XML::getConsumerInfo( UniXML::iterator& it, bool Restorer_XML::getConsumerInfo( UniXML::iterator& it,
ObjectId& cid, ObjectId& cnode ) ObjectId& cid, ObjectId& cnode ) const
{ {
if( !check_consumer_item(it) ) if( !check_consumer_item(it) )
return false; return false;
...@@ -110,12 +110,12 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it, ...@@ -110,12 +110,12 @@ bool Restorer_XML::getConsumerInfo( UniXML::iterator& it,
return true; return true;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool Restorer_XML::check_list_item( UniXML::iterator& it ) bool Restorer_XML::check_list_item( UniXML::iterator& it ) const
{ {
return uniset::check_filter(it, i_filterField, i_filterValue); return uniset::check_filter(it, i_filterField, i_filterValue);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool Restorer_XML::check_consumer_item( UniXML::iterator& it ) bool Restorer_XML::check_consumer_item( UniXML::iterator& it ) const
{ {
return uniset::check_filter(it, c_filterField, c_filterValue); return uniset::check_filter(it, c_filterField, c_filterValue);
} }
......
...@@ -74,7 +74,7 @@ void UniXML::newDoc(const string& root_node, const string& xml_ver) ...@@ -74,7 +74,7 @@ void UniXML::newDoc(const string& root_node, const string& xml_ver)
if( d == NULL ) if( d == NULL )
throw NameNotFound("UniXML(open): не смогли создать doc=" + root_node); throw NameNotFound("UniXML(open): не смогли создать doc=" + root_node);
doc = std::unique_ptr<xmlDoc,UniXMLDocDeleter>(d); doc = std::unique_ptr<xmlDoc, UniXMLDocDeleter>(d);
// xmlEncodeEntitiesReentrant(doc, (const xmlChar*)ExternalEncoding.c_str()); // xmlEncodeEntitiesReentrant(doc, (const xmlChar*)ExternalEncoding.c_str());
xmlNode* rootnode = xmlNewDocNode(d, NULL, (const xmlChar*)root_node.c_str(), NULL); xmlNode* rootnode = xmlNewDocNode(d, NULL, (const xmlChar*)root_node.c_str(), NULL);
...@@ -118,7 +118,7 @@ void UniXML::open( const string& _filename ) ...@@ -118,7 +118,7 @@ void UniXML::open( const string& _filename )
if( d == NULL ) if( d == NULL )
throw NameNotFound("UniXML(open): NotFound file=" + _filename); throw NameNotFound("UniXML(open): NotFound file=" + _filename);
doc = std::unique_ptr<xmlDoc,UniXMLDocDeleter>(d); doc = std::unique_ptr<xmlDoc, UniXMLDocDeleter>(d);
// Support for XInclude (see eterbug #6304) // Support for XInclude (see eterbug #6304)
// main tag must to have follow property: xmlns:xi="http://www.w3.org/2001/XInclude" // main tag must to have follow property: xmlns:xi="http://www.w3.org/2001/XInclude"
......
...@@ -150,7 +150,13 @@ namespace uniset ...@@ -150,7 +150,13 @@ namespace uniset
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, VMonitor& m ) std::ostream& operator<<( std::ostream& os, VMonitor& m )
{ {
auto vlist = m.getList(); return os << m.str();
}
// --------------------------------------------------------------------------
std::string VMonitor::str() const
{
std::ostringstream s;
auto vlist = getList();
// сортируем по алфавиту // сортируем по алфавиту
vlist.sort( []( const std::pair<std::string, std::string>& a, const std::pair<std::string, std::string>& b ) vlist.sort( []( const std::pair<std::string, std::string>& a, const std::pair<std::string, std::string>& b )
{ {
...@@ -158,19 +164,12 @@ namespace uniset ...@@ -158,19 +164,12 @@ namespace uniset
}); });
for( const auto& e : vlist ) for( const auto& e : vlist )
os << e.first << " = " << e.second; s << e.first << " = " << e.second;
return os;
}
// --------------------------------------------------------------------------
std::string VMonitor::str()
{
std::ostringstream s;
s << (*this);
return s.str(); return s.str();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
std::list<std::pair<std::string, std::string> > VMonitor::getList() std::list<std::pair<std::string, std::string> > VMonitor::getList() const
{ {
std::list<std::pair<std::string, std::string>> vlist; std::list<std::pair<std::string, std::string>> vlist;
VMON_MAKE_PAIR2(vlist, int); VMON_MAKE_PAIR2(vlist, int);
...@@ -184,7 +183,7 @@ namespace uniset ...@@ -184,7 +183,7 @@ namespace uniset
return vlist; return vlist;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
std::string VMonitor::pretty_str( int namewidth, int colnum ) std::string VMonitor::pretty_str( int namewidth, int colnum ) const
{ {
auto vlist = getList(); auto vlist = getList();
std::ostringstream os; std::ostringstream os;
......
...@@ -22,7 +22,7 @@ struct TestClass ...@@ -22,7 +22,7 @@ struct TestClass
{ {
TestClass() TestClass()
{ {
memset(&data,0,sizeof(data)); memset(&data, 0, sizeof(data));
cerr << "TEST CLASS CREATE.." << endl; cerr << "TEST CLASS CREATE.." << endl;
} }
......
...@@ -203,7 +203,7 @@ TEST_CASE("[DelayTimer]: zero time", "[DelayTimer]" ) ...@@ -203,7 +203,7 @@ TEST_CASE("[DelayTimer]: zero time", "[DelayTimer]" )
// проверка работы при вызове check() // проверка работы при вызове check()
// уже после срабатывания таймера // уже после срабатывания таймера
dt.set(0,100); dt.set(0, 100);
REQUIRE( dt.check(true) ); // взводим REQUIRE( dt.check(true) ); // взводим
REQUIRE( dt.check(false) ); // отпускаем.. REQUIRE( dt.check(false) ); // отпускаем..
msleep(150); msleep(150);
......
...@@ -72,7 +72,7 @@ TEST_CASE("Pulse: basic tests", "[pulse][basic]" ) ...@@ -72,7 +72,7 @@ TEST_CASE("Pulse: basic tests", "[pulse][basic]" )
TEST_CASE("Pulse: ext tests", "[pulse][ext]" ) TEST_CASE("Pulse: ext tests", "[pulse][ext]" )
{ {
Pulse p; Pulse p;
p.setTiming(50,100,false); p.setTiming(50, 100, false);
REQUIRE_FALSE( p.isOn() ); REQUIRE_FALSE( p.isOn() );
p.set(true); p.set(true);
...@@ -87,7 +87,7 @@ TEST_CASE("Pulse: ext tests", "[pulse][ext]" ) ...@@ -87,7 +87,7 @@ TEST_CASE("Pulse: ext tests", "[pulse][ext]" )
REQUIRE_FALSE( p.isOn() ); REQUIRE_FALSE( p.isOn() );
REQUIRE_FALSE( p.step() ); REQUIRE_FALSE( p.step() );
p.setTiming(50,100,true); p.setTiming(50, 100, true);
REQUIRE( p.isOn() ); REQUIRE( p.isOn() );
REQUIRE( p.step() ); REQUIRE( p.step() );
} }
......
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