Commit afa98d71 authored by Pavel Vainerman's avatar Pavel Vainerman

make style

parent 1dabf74a
...@@ -177,7 +177,7 @@ int main( int argc, char** argv ) ...@@ -177,7 +177,7 @@ int main( int argc, char** argv )
case 'g': case 'g':
ignoreErrors = true; ignoreErrors = true;
break; break;
case 'e': case 'e':
{ {
......
...@@ -183,11 +183,11 @@ int main( int argc, char** argv ) ...@@ -183,11 +183,11 @@ int main( int argc, char** argv )
dlog4->addLevel(Debug::ANY); dlog4->addLevel(Debug::ANY);
ls.async_run( addr, port ); ls.async_run( addr, port );
if( verb ) if( verb )
ls.setSessionLog(Debug::ANY); ls.setSessionLog(Debug::ANY);
if( !ls.isRunning() ) if( !ls.isRunning() )
{ {
cerr << "LOG SERVER NOT RUNNING!!" << endl; cerr << "LOG SERVER NOT RUNNING!!" << endl;
......
...@@ -45,16 +45,17 @@ int main(int argc, char** argv) ...@@ -45,16 +45,17 @@ int main(int argc, char** argv)
for( DBResult::iterator it = r.begin(); it != r.end(); it++ ) for( DBResult::iterator it = r.begin(); it != r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
// DBResult::COL col(*it); // DBResult::COL col(*it);
// for( DBResult::COL::iterator cit = col.begin(); cit != col.end(); cit++ ) // for( DBResult::COL::iterator cit = col.begin(); cit != col.end(); cit++ )
// cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | "; // cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
// cout << endl; // cout << endl;
for( DBResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ ) for( DBResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | "; cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
cout << endl; cout << endl;
cout << "ID: " << r.as_string(it,"id") << endl; cout << "ID: " << r.as_string(it, "id") << endl;
cout << "ID: " << it.as_string("id") << endl; cout << "ID: " << it.as_string("id") << endl;
} }
......
...@@ -230,7 +230,7 @@ DBResult PostgreSQLInterface::makeResult( const pqxx::result& res ) ...@@ -230,7 +230,7 @@ DBResult PostgreSQLInterface::makeResult( const pqxx::result& res )
col.push_back(""); col.push_back("");
else else
{ {
result.setColName(i.num(),i.name()); result.setColName(i.num(), i.name());
col.push_back( i.as<string>() ); col.push_back( i.as<string>() );
} }
} }
......
...@@ -225,6 +225,7 @@ bool SQLiteInterface::isConnection() const ...@@ -225,6 +225,7 @@ bool SQLiteInterface::isConnection() const
DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize ) DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize )
{ {
DBResult result; DBResult result;
if( !s ) if( !s )
{ {
if( finalize ) if( finalize )
...@@ -253,9 +254,10 @@ DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize ) ...@@ -253,9 +254,10 @@ DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize )
if( p ) if( p )
{ {
const char* cname = (const char*)sqlite3_column_name(s,i); const char* cname = (const char*)sqlite3_column_name(s, i);
if( cname ) if( cname )
result.setColName(i,cname); result.setColName(i, cname);
c.emplace_back(p); c.emplace_back(p);
} }
......
...@@ -38,11 +38,11 @@ int main(int argc, char** argv) ...@@ -38,11 +38,11 @@ int main(int argc, char** argv)
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | "; cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
cout << endl; cout << endl;
// for( int i=0; i<col.size(); i++ )
// cerr << "[" << i << "]: " << r.getColName(i) << endl;
cout << "ID: " << r.as_string(it,"id") << endl; // for( int i=0; i<col.size(); i++ )
// cerr << "[" << i << "]: " << r.getColName(i) << endl;
cout << "ID: " << r.as_string(it, "id") << endl;
cout << "date: " << it.as_string("date") << endl; cout << "date: " << it.as_string("date") << endl;
} }
......
...@@ -76,7 +76,7 @@ namespace uniset ...@@ -76,7 +76,7 @@ namespace uniset
{ {
long _myout = getOut(); long _myout = getOut();
for( auto&& it: outs ) for( auto && it : outs )
it.el->setIn(it.num, _myout); it.el->setIn(it.num, _myout);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -95,7 +95,7 @@ namespace uniset ...@@ -95,7 +95,7 @@ namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addInput(size_t num, long value ) void Element::addInput(size_t num, long value )
{ {
for( auto&& it : ins ) for( auto && it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
......
...@@ -153,7 +153,7 @@ void LProcessor::build( const string& lfile ) ...@@ -153,7 +153,7 @@ void LProcessor::build( const string& lfile )
*/ */
void LProcessor::getInputs() void LProcessor::getInputs()
{ {
for( auto&& it : extInputs ) for( auto && it : extInputs )
{ {
// try // try
// { // {
......
...@@ -30,7 +30,7 @@ namespace uniset ...@@ -30,7 +30,7 @@ namespace uniset
{ {
public: public:
TA2D( Element::ElementID id, long filterValue=1 ); TA2D( Element::ElementID id, long filterValue = 1 );
virtual ~TA2D(); virtual ~TA2D();
/*! num игнорируется, т.к. элемент с одним входом */ /*! num игнорируется, т.к. элемент с одним входом */
......
...@@ -36,7 +36,7 @@ namespace uniset ...@@ -36,7 +36,7 @@ namespace uniset
void TAND::setIn( size_t num, long value ) void TAND::setIn( size_t num, long value )
{ {
// cout << this << ": input " << num << " set " << state << endl; // cout << this << ": input " << num << " set " << state << endl;
for( auto&& it : ins ) for( auto && it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
...@@ -53,7 +53,7 @@ namespace uniset ...@@ -53,7 +53,7 @@ namespace uniset
// проверяем изменился ли выход // проверяем изменился ли выход
// для тригера 'AND' проверка до первого 0 // для тригера 'AND' проверка до первого 0
for( auto&& it : ins ) for( auto && it : ins )
{ {
if( !it.value ) if( !it.value )
{ {
......
...@@ -50,7 +50,7 @@ namespace uniset ...@@ -50,7 +50,7 @@ namespace uniset
{ {
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl; // cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto&& it : ins ) for( auto && it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
...@@ -67,7 +67,7 @@ namespace uniset ...@@ -67,7 +67,7 @@ namespace uniset
// проверяем изменился ли выход // проверяем изменился ли выход
// для тригера 'OR' проверка до первой единицы // для тригера 'OR' проверка до первой единицы
for( auto&& it : ins ) for( auto && it : ins )
{ {
if( it.value ) if( it.value )
{ {
......
...@@ -144,7 +144,7 @@ TEST_CASE("Logic processor: elements", "[LogicProcessor][elements]") ...@@ -144,7 +144,7 @@ TEST_CASE("Logic processor: elements", "[LogicProcessor][elements]")
SECTION( "TA2D" ) SECTION( "TA2D" )
{ {
TA2D e("1",10); TA2D e("1", 10);
REQUIRE_FALSE( e.getOut() ); REQUIRE_FALSE( e.getOut() );
e.setIn(1, 5); e.setIn(1, 5);
......
...@@ -160,7 +160,7 @@ int main( int argc, char** argv ) ...@@ -160,7 +160,7 @@ int main( int argc, char** argv )
case 'g': case 'g':
ignoreErrors = true; ignoreErrors = true;
break; break;
case 'n': case 'n':
{ {
...@@ -221,7 +221,7 @@ int main( int argc, char** argv ) ...@@ -221,7 +221,7 @@ int main( int argc, char** argv )
{ {
auto mbtcp = new ModbusTCPMaster(); auto mbtcp = new ModbusTCPMaster();
mbtcp->connect(iaddr, port); mbtcp->connect(iaddr, port);
// mbtcp->setForceDisconnect(!persist); // mbtcp->setForceDisconnect(!persist);
mb = mbtcp; mb = mbtcp;
} }
else else
......
...@@ -278,7 +278,7 @@ int main( int argc, char** argv ) ...@@ -278,7 +278,7 @@ int main( int argc, char** argv )
{ {
auto mbtcp = new ModbusTCPMaster(); auto mbtcp = new ModbusTCPMaster();
mbtcp->connect(iaddr, port); mbtcp->connect(iaddr, port);
// mbtcp->setForceDisconnect(!persist); // mbtcp->setForceDisconnect(!persist);
mb = mbtcp; mb = mbtcp;
} }
else else
...@@ -323,6 +323,7 @@ int main( int argc, char** argv ) ...@@ -323,6 +323,7 @@ int main( int argc, char** argv )
cout << "(mtr-setup): save: autodetect speed... (addr=" << ModbusRTU::addr2str(slaveaddr) << ")" << endl; cout << "(mtr-setup): save: autodetect speed... (addr=" << ModbusRTU::addr2str(slaveaddr) << ")" << endl;
auto mbrtu = dynamic_cast<ModbusRTUMaster*>(mb); auto mbrtu = dynamic_cast<ModbusRTUMaster*>(mb);
if( mbrtu ) if( mbrtu )
{ {
mb->setTimeout(50); mb->setTimeout(50);
......
...@@ -671,6 +671,7 @@ namespace uniset ...@@ -671,6 +671,7 @@ namespace uniset
mbcrit << myname << "(execute_tcp): catch exception: " mbcrit << myname << "(execute_tcp): catch exception: "
<< tcpserver->getInetAddress() << tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << " err: " << ex << endl; << ":" << tcpserver->getInetPort() << " err: " << ex << endl;
if( tcpBreakIfFailRun ) if( tcpBreakIfFailRun )
throw ex; throw ex;
} }
...@@ -680,6 +681,7 @@ namespace uniset ...@@ -680,6 +681,7 @@ namespace uniset
<< tcpserver->getInetAddress() << tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << ":" << tcpserver->getInetPort()
<< " err: " << e.displayText() << endl; << " err: " << e.displayText() << endl;
if( tcpBreakIfFailRun ) if( tcpBreakIfFailRun )
throw e; throw e;
} }
...@@ -689,6 +691,7 @@ namespace uniset ...@@ -689,6 +691,7 @@ namespace uniset
<< tcpserver->getInetAddress() << tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << ":" << tcpserver->getInetPort()
<< " err: " << e.what() << endl; << " err: " << e.what() << endl;
if( tcpBreakIfFailRun ) if( tcpBreakIfFailRun )
throw e; throw e;
} }
...@@ -698,6 +701,7 @@ namespace uniset ...@@ -698,6 +701,7 @@ namespace uniset
<< tcpserver->getInetAddress() << tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << ":" << tcpserver->getInetPort()
<< endl; << endl;
if( tcpBreakIfFailRun ) if( tcpBreakIfFailRun )
throw; throw;
} }
...@@ -2074,7 +2078,7 @@ namespace uniset ...@@ -2074,7 +2078,7 @@ namespace uniset
if( !params.empty() ) if( !params.empty() )
{ {
for( const auto& p: params ) for( const auto& p : params )
{ {
if( p.first == "regs" ) if( p.first == "regs" )
q_regs = uniset::explode_str(p.second, ','); q_regs = uniset::explode_str(p.second, ',');
...@@ -2095,22 +2099,23 @@ namespace uniset ...@@ -2095,22 +2099,23 @@ namespace uniset
// Проход по списку заданных addr.. // Проход по списку заданных addr..
if( !q_addr.empty() ) if( !q_addr.empty() )
{ {
for( const auto& a: q_addr ) for( const auto& a : q_addr )
{ {
ModbusRTU::ModbusAddr mbaddr = ModbusRTU::str2mbAddr(a); ModbusRTU::ModbusAddr mbaddr = ModbusRTU::str2mbAddr(a);
auto i = iomap.find(mbaddr); auto i = iomap.find(mbaddr);
if( i != iomap.end() ) if( i != iomap.end() )
{ {
Poco::JSON::Object::Ptr jaddr = get_regs(i->first,i->second, q_regs); Poco::JSON::Object::Ptr jaddr = get_regs(i->first, i->second, q_regs);
jdata->add(jaddr); jdata->add(jaddr);
} }
} }
} }
else // Проход по всему списку else // Проход по всему списку
{ {
for( const auto& i: iomap ) for( const auto& i : iomap )
{ {
Poco::JSON::Object::Ptr jaddr = get_regs(i.first,i.second, q_regs); Poco::JSON::Object::Ptr jaddr = get_regs(i.first, i.second, q_regs);
jdata->add(jaddr); jdata->add(jaddr);
} }
} }
...@@ -2126,7 +2131,7 @@ namespace uniset ...@@ -2126,7 +2131,7 @@ namespace uniset
if( q_regs.empty() ) if( q_regs.empty() )
{ {
for( const auto& r: rmap ) for( const auto& r : rmap )
{ {
Poco::JSON::Object::Ptr reginfo = get_reginfo(r.second); Poco::JSON::Object::Ptr reginfo = get_reginfo(r.second);
regs->add(reginfo); regs->add(reginfo);
...@@ -2138,6 +2143,7 @@ namespace uniset ...@@ -2138,6 +2143,7 @@ namespace uniset
{ {
auto reg = genRegID( ModbusRTU::str2mbData(s), default_mbfunc); auto reg = genRegID( ModbusRTU::str2mbData(s), default_mbfunc);
auto r = rmap.find(reg); auto r = rmap.find(reg);
if( r != rmap.end() ) if( r != rmap.end() )
{ {
Poco::JSON::Object::Ptr reginfo = get_reginfo(r->second); Poco::JSON::Object::Ptr reginfo = get_reginfo(r->second);
......
...@@ -27,7 +27,7 @@ int main( int argc, const char** argv ) ...@@ -27,7 +27,7 @@ int main( int argc, const char** argv )
for( int i = 1; i <= num; i++) for( int i = 1; i <= num; i++)
{ {
// auto mbs = MBSlave::init_mbslave(argc, argv, shm->getId(), shm, "mbs"); // auto mbs = MBSlave::init_mbslave(argc, argv, shm->getId(), shm, "mbs");
ostringstream s; ostringstream s;
s << "MBTCP" << i; s << "MBTCP" << i;
...@@ -36,7 +36,7 @@ int main( int argc, const char** argv ) ...@@ -36,7 +36,7 @@ int main( int argc, const char** argv )
ostringstream p; ostringstream p;
p << "mbs" << i; p << "mbs" << i;
auto mbs = make_shared<MBSlave>( conf->getObjectID(s.str()),shm->getId(), shm, p.str()); auto mbs = make_shared<MBSlave>( conf->getObjectID(s.str()), shm->getId(), shm, p.str());
if( !mbs ) if( !mbs )
{ {
......
...@@ -763,6 +763,7 @@ namespace uniset ...@@ -763,6 +763,7 @@ namespace uniset
return; return;
HistoryItList* lst = static_cast<HistoryItList*>(usi->getUserData(udataHistory)); HistoryItList* lst = static_cast<HistoryItList*>(usi->getUserData(udataHistory));
if( !lst ) if( !lst )
return; return;
...@@ -781,7 +782,7 @@ namespace uniset ...@@ -781,7 +782,7 @@ namespace uniset
<< " value=" << value << " value=" << value
<< endl; << endl;
for( auto&& it1 : (*lst) ) for( auto && it1 : (*lst) )
{ {
History::iterator it = it1; History::iterator it = it1;
......
...@@ -49,7 +49,7 @@ void TestObject::sensorInfo( const SensorMessage* sm ) ...@@ -49,7 +49,7 @@ void TestObject::sensorInfo( const SensorMessage* sm )
<< " lost: " << (sm->value - lastValue) << " lost: " << (sm->value - lastValue)
<< endl; << endl;
lostMessages += (sm->value - lastValue -1); lostMessages += (sm->value - lastValue - 1);
} }
lastValue = sm->value; lastValue = sm->value;
......
...@@ -270,13 +270,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]") ...@@ -270,13 +270,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
// Для проверки этого датчик монотонно увеличивается на +1 // Для проверки этого датчик монотонно увеличивается на +1
// сама проверка см. TestObject::sensorInfo() // сама проверка см. TestObject::sensorInfo()
auto conf = uniset_conf(); auto conf = uniset_conf();
const long max = uniset::getArgInt("--monotonic-max-value", conf->getArgc(),conf->getArgv(),"1000"); const long max = uniset::getArgInt("--monotonic-max-value", conf->getArgc(), conf->getArgv(), "1000");
auto&& write_worker = [&max] auto&& write_worker = [&max]
{ {
try try
{ {
for( long val=0; val<=max; val++ ) for( long val = 0; val <= max; val++ )
ui->setValue(516, val); ui->setValue(516, val);
} }
catch( std::exception& ex ) catch( std::exception& ex )
...@@ -291,12 +291,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]") ...@@ -291,12 +291,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
auto ret = std::async(std::launch::async, write_worker); auto ret = std::async(std::launch::async, write_worker);
for( long n=0; n <= max; n++ ) for( long n = 0; n <= max; n++ )
obj->askMonotonic(); obj->askMonotonic();
REQUIRE( ret.get() ); REQUIRE( ret.get() );
DelayTimer dt(2000,0); DelayTimer dt(2000, 0);
while( !dt.check(obj->isEmptyQueue()) ) while( !dt.check(obj->isEmptyQueue()) )
msleep(500); msleep(500);
...@@ -306,7 +307,7 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]") ...@@ -306,7 +307,7 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
REQUIRE( obj->getLastValue() == max ); REQUIRE( obj->getLastValue() == max );
// print statistic // print statistic
// uniset::SimpleInfo_var si = obj->getInfo(0); // uniset::SimpleInfo_var si = obj->getInfo(0);
// cerr << std::string(si->info) << endl; // cerr << std::string(si->info) << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -475,7 +475,7 @@ void UNetExchange::startReceivers() ...@@ -475,7 +475,7 @@ void UNetExchange::startReceivers()
void UNetExchange::waitSMReady() void UNetExchange::waitSMReady()
{ {
// waiting for SM is ready... // waiting for SM is ready...
int tout = uniset_conf()->getArgPInt("--unet-sm-ready-timeout", "",uniset_conf()->getNCReadyTimeout()); int tout = uniset_conf()->getArgPInt("--unet-sm-ready-timeout", "", uniset_conf()->getNCReadyTimeout());
timeout_t ready_timeout = uniset_conf()->getNCReadyTimeout(); timeout_t ready_timeout = uniset_conf()->getNCReadyTimeout();
......
...@@ -229,6 +229,7 @@ void UNetReceiver::start() ...@@ -229,6 +229,7 @@ void UNetReceiver::start()
if( !activated ) if( !activated )
{ {
activated = true; activated = true;
if( !loop.async_evrun(this, evrunTimeout) ) if( !loop.async_evrun(this, evrunTimeout) )
{ {
unetcrit << myname << "(start): evrun FAILED! (timeout=" << evrunTimeout << " msec)" << endl; unetcrit << myname << "(start): evrun FAILED! (timeout=" << evrunTimeout << " msec)" << endl;
......
...@@ -442,7 +442,7 @@ namespace uniset ...@@ -442,7 +442,7 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP DIGITAL DATA LIMIT! max=" << "(readItem): OVERFLOW! MAX UDP DIGITAL DATA LIMIT! max="
<< UniSetUDP::MaxDCount << endl; << UniSetUDP::MaxDCount << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
...@@ -481,7 +481,7 @@ namespace uniset ...@@ -481,7 +481,7 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP ANALOG DATA LIMIT! max=" << "(readItem): OVERFLOW! MAX UDP ANALOG DATA LIMIT! max="
<< UniSetUDP::MaxACount << endl; << UniSetUDP::MaxACount << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
...@@ -494,7 +494,7 @@ namespace uniset ...@@ -494,7 +494,7 @@ namespace uniset
{ {
unetcrit << myname unetcrit << myname
<< "(readItem): Sensor (" << p.id << ")" << sname << " ALREADY ADDED!! ABORT!" << endl; << "(readItem): Sensor (" << p.id << ")" << sname << " ALREADY ADDED!! ABORT!" << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); std::terminate();
return false; return false;
} }
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2017-06-03+03:00 // generate timestamp: 2017-06-03+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -29,11 +29,11 @@ class UObject_SK: ...@@ -29,11 +29,11 @@ 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();
long getValue( uniset::ObjectId sid ); long getValue( uniset::ObjectId sid );
void setValue( uniset::ObjectId sid, long value ); void setValue( uniset::ObjectId sid, long value );
void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
...@@ -43,136 +43,151 @@ class UObject_SK: ...@@ -43,136 +43,151 @@ 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() noexcept; return vmon.pretty_str();
}
// ------------------------------------------------------------
std::string help() 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
// Используемые идентификаторы // Используемые идентификаторы
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// Текущее значение // Текущее значение
// --- public variables --- // --- public variables ---
// --- end of public variables --- // --- end of public variables ---
protected: protected:
// --- protected variables --- // --- protected variables ---
// ---- end of protected variables ---- // ---- end of protected variables ----
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(){ return ""; } /*!< пользовательская информация выводимая в getInfo() */ virtual std::string getMonitInfo()
virtual std::string getTypeOfMessage( int t ){ return uniset::strTypeOfMessage(t); } /*!< получение названия типа сообщения. Используется в getInfo() */ {
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
virtual std::string getTypeOfMessage( int t )
{
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 );
virtual void testMode( bool state ); virtual void testMode( bool state );
void updateOutputs( bool force ); void updateOutputs( bool force );
...@@ -194,22 +209,28 @@ class UObject_SK: ...@@ -194,22 +209,28 @@ class UObject_SK:
uniset::PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */ uniset::PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
uniset::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */ uniset::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
long maxHeartBeat; /*! < сохраняемое значение */ long maxHeartBeat; /*! < сохраняемое значение */
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;
uniset::timeout_t activateTimeout; /*!< время ожидания готовности UniSetObject к работе */ uniset::timeout_t activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
uniset::PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */ uniset::PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */ int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */ bool forceOut; /*!< флаг принудительного обноления "выходов" */
std::shared_ptr<uniset::LogAgregator> loga; std::shared_ptr<uniset::LogAgregator> loga;
std::shared_ptr<DebugStream> mylog; std::shared_ptr<DebugStream> mylog;
std::shared_ptr<uniset::LogServer> logserv; std::shared_ptr<uniset::LogServer> logserv;
...@@ -218,21 +239,21 @@ class UObject_SK: ...@@ -218,21 +239,21 @@ class UObject_SK:
uniset::VMonitor vmon; uniset::VMonitor vmon;
private: private:
// --- private variables --- // --- private variables ---
// --- end of private variables --- // --- end of private variables ---
// предыдущее значение (для работы UpdateValue()) // предыдущее значение (для работы UpdateValue())
// Текущее значение (rw-переменные) // Текущее значение (rw-переменные)
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// ------------ private функции --------------- // ------------ private функции ---------------
void updatePreviousValues() noexcept; void updatePreviousValues() noexcept;
void preSensorInfo( const uniset::SensorMessage* sm ); void preSensorInfo( const uniset::SensorMessage* sm );
...@@ -240,23 +261,23 @@ class UObject_SK: ...@@ -240,23 +261,23 @@ class UObject_SK:
void initFromSM(); void initFromSM();
void checkSensors(); void checkSensors();
// -------------------------------------------- // --------------------------------------------
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()) */
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода) bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
}; };
......
...@@ -247,7 +247,7 @@ namespace uniset ...@@ -247,7 +247,7 @@ namespace uniset
} }
if( !it->noprecision && it->cal.precision != 0 ) if( !it->noprecision && it->cal.precision != 0 )
val = lround( val*pow10(it->cal.precision) ); val = lround( val * pow10(it->cal.precision) );
} }
} // end of 'check_depend' } // end of 'check_depend'
......
...@@ -430,6 +430,7 @@ namespace uniset ...@@ -430,6 +430,7 @@ namespace uniset
if( mbrtu ) if( mbrtu )
{ {
mbrtu->setSpeed(speed); mbrtu->setSpeed(speed);
if( verb ) if( verb )
cout << "(mtr-setup): speed is set to " cout << "(mtr-setup): speed is set to "
<< ComPort::getSpeed(speed) << endl; << ComPort::getSpeed(speed) << endl;
...@@ -459,6 +460,7 @@ namespace uniset ...@@ -459,6 +460,7 @@ namespace uniset
if( mbrtu ) if( mbrtu )
{ {
mbrtu->setParity(get_parity(data)); mbrtu->setParity(get_parity(data));
if( verb ) if( verb )
cout << "(mtr-setup): parity is set to " cout << "(mtr-setup): parity is set to "
<< (data ? ((data == 1) ? "odd" : "even") : "no") << endl; << (data ? ((data == 1) ? "odd" : "even") : "no") << endl;
...@@ -557,7 +559,7 @@ namespace uniset ...@@ -557,7 +559,7 @@ namespace uniset
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
MTR::MTRError update_configuration(ModbusClient* mb, ModbusRTU::ModbusAddr slaveaddr, MTR::MTRError update_configuration(ModbusClient* mb, ModbusRTU::ModbusAddr slaveaddr,
const std::string& mtrconfile, int verb ) const std::string& mtrconfile, int verb )
{ {
std::string m = MTR::getModelNumber(mb, slaveaddr); std::string m = MTR::getModelNumber(mb, slaveaddr);
......
...@@ -6,10 +6,10 @@ ...@@ -6,10 +6,10 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2017-06-03+03:00 // generate timestamp: 2017-06-03+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -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( string(myname+": init failed!!!") ); throw uniset::Exception( string(myname + ": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
...@@ -61,9 +61,10 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -61,9 +61,10 @@ 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;
return s3; return s3;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -71,44 +72,44 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop ) ...@@ -71,44 +72,44 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
{ {
if( prop.empty() ) if( prop.empty() )
return uniset_conf()->getLocalNode(); return uniset_conf()->getLocalNode();
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());
...@@ -144,13 +145,15 @@ end_private(false) ...@@ -144,13 +145,15 @@ end_private(false)
logserv_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost"); logserv_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost");
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);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id")); forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false);
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,31 +161,34 @@ end_private(false) ...@@ -158,31 +161,34 @@ 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);
} }
// Инициализация значений // Инициализация значений
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,8 +196,8 @@ end_private(false) ...@@ -190,8 +196,8 @@ 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 )
smTestID = getSMTestID(); smTestID = getSMTestID();
...@@ -202,7 +208,7 @@ end_private(false) ...@@ -202,7 +208,7 @@ end_private(false)
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
// ===================== <variables> ===================== // ===================== <variables> =====================
// ===================== end of <variables> ===================== // ===================== end of <variables> =====================
vmonit(sleep_msec); vmonit(sleep_msec);
...@@ -214,10 +220,10 @@ end_private(false) ...@@ -214,10 +220,10 @@ end_private(false)
vmonit(activateTimeout); vmonit(activateTimeout);
vmonit(smReadyTimeout); vmonit(smReadyTimeout);
vmonit(smTestID); vmonit(smTestID);
// 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;
} }
...@@ -230,17 +236,17 @@ UObject_SK::~UObject_SK() ...@@ -230,17 +236,17 @@ UObject_SK::~UObject_SK()
void UObject_SK::updateValues() void UObject_SK::updateValues()
{ {
// Опрашиваем все входы... // Опрашиваем все входы...
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updatePreviousValues() noexcept void UObject_SK::updatePreviousValues() noexcept
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::checkSensors() void UObject_SK::checkSensors()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
...@@ -248,28 +254,28 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept ...@@ -248,28 +254,28 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
if( _code == uniset::DefaultObjectId ) if( _code == uniset::DefaultObjectId )
{ {
mylog8 << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl; mylog8 << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl;
return false; return false;
} }
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl; mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс
if( _state )
{
ptResetMsg.reset();
trResetMsg.hi(false);
}
// взводим автоматический сброс
if( _state )
{
ptResetMsg.reset();
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
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -278,7 +284,7 @@ uniset::ObjectId UObject_SK::getSMTestID() ...@@ -278,7 +284,7 @@ uniset::ObjectId UObject_SK::getSMTestID()
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
return DefaultObjectId; return DefaultObjectId;
} }
...@@ -289,7 +295,7 @@ void UObject_SK::testMode( bool _state ) ...@@ -289,7 +295,7 @@ void UObject_SK::testMode( bool _state )
return; return;
// отключаем все выходы // отключаем все выходы
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -298,13 +304,13 @@ Poco::JSON::Object::Ptr UObject_SK::httpDumpIO() ...@@ -298,13 +304,13 @@ 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");
return jdata; return jdata;
} }
...@@ -319,44 +325,48 @@ std::string UObject_SK::dumpIO() ...@@ -319,44 +325,48 @@ std::string UObject_SK::dumpIO()
std::list<std::string> v_in; std::list<std::string> v_in;
ostringstream s1; ostringstream s1;
std::list<std::string> v_out; std::list<std::string> v_out;
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;
} }
return s.str(); return s.str();
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::str( uniset::ObjectId id, bool showLinkName ) const std::string UObject_SK::str( uniset::ObjectId id, bool showLinkName ) const
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::strval( uniset::ObjectId id, bool showLinkName ) const std::string UObject_SK::strval( uniset::ObjectId id, bool showLinkName ) const
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -373,38 +383,38 @@ void UObject_SK::processingMessage( const uniset::VoidMessage* _msg ) ...@@ -373,38 +383,38 @@ void UObject_SK::processingMessage( const uniset::VoidMessage* _msg )
{ {
try try
{ {
msgTypeStat[_msg->type] += 1; msgTypeStat[_msg->type] += 1;
switch( _msg->type ) switch( _msg->type )
{ {
case Message::SensorInfo: case Message::SensorInfo:
{ {
const SensorMessage* sm = reinterpret_cast<const SensorMessage*>(_msg); const SensorMessage* sm = reinterpret_cast<const SensorMessage*>(_msg);
smStat[sm->id] += 1; smStat[sm->id] += 1;
preSensorInfo(sm); preSensorInfo(sm);
} }
break; break;
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;
} }
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
processingMessageCatchCount++; processingMessageCatchCount++;
mycrit << myname << "(processingMessage): " << ex.what() << endl; mycrit << myname << "(processingMessage): " << ex.what() << endl;
} }
} }
...@@ -415,14 +425,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -415,14 +425,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() )
...@@ -460,24 +473,25 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -460,24 +473,25 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
ostate = "StartUp: [OK]"; ostate = "StartUp: [OK]";
break; break;
} }
case SystemMessage::FoldUp: case SystemMessage::FoldUp:
case SystemMessage::Finish: case SystemMessage::Finish:
preAskSensors(UniversalIO::UIODontNotify); preAskSensors(UniversalIO::UIODontNotify);
askSensors(UniversalIO::UIODontNotify); askSensors(UniversalIO::UIODontNotify);
break; break;
case SystemMessage::LogRotate: case SystemMessage::LogRotate:
{ {
// переоткрываем логи // переоткрываем логи
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;
} }
if( logserv && !logserv_host.empty() && logserv_port != 0 ) if( logserv && !logserv_host.empty() && logserv_port != 0 )
{ {
try try
...@@ -500,7 +514,7 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -500,7 +514,7 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
default: default:
break; break;
} }
sysCommand(_sm); sysCommand(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -508,51 +522,55 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -508,51 +522,55 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
{ {
uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam); uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam);
ostringstream inf; ostringstream inf;
inf << i->info << endl; inf << i->info << endl;
inf << "process state: " << ostate << endl; inf << "process state: " << ostate << endl;
if( logserv /* && userparam < 0 */ ) if( logserv /* && userparam < 0 */ )
{ {
inf << "LogServer: " << logserv_host << ":" << logserv_port inf << "LogServer: " << logserv_host << ":" << logserv_port
<< ( logserv->isRunning() ? " [RUNNIG]" : " [STOPPED]" ) << endl; << ( logserv->isRunning() ? " [RUNNIG]" : " [STOPPED]" ) << endl;
inf << " " << logserv->getShortInfo() << endl; inf << " " << logserv->getShortInfo() << endl;
} }
else else
inf << "LogServer: NONE" << endl; inf << "LogServer: NONE" << endl;
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;
inf << dumpIO() << endl; inf << dumpIO() << endl;
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;
inf << getMonitInfo() << endl; inf << getMonitInfo() << endl;
i->info = inf.str().c_str(); i->info = inf.str().c_str();
return i._retn(); return i._retn();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -561,57 +579,61 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) ...@@ -561,57 +579,61 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& params ) Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
{ {
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);
} }
httpGetUserData(jdata); httpGetUserData(jdata);
return json; return json;
...@@ -622,7 +644,7 @@ Poco::JSON::Object::Ptr UObject_SK::httpHelp( const Poco::URI::QueryParameters& ...@@ -622,7 +644,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;
...@@ -632,14 +654,14 @@ Poco::JSON::Object::Ptr UObject_SK::httpRequest( const std::string& req, const P ...@@ -632,14 +654,14 @@ 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;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -657,7 +679,7 @@ void UObject_SK::sigterm( int signo ) ...@@ -657,7 +679,7 @@ void UObject_SK::sigterm( int signo )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::activateObject() bool UObject_SK::activateObject()
{ {
// блокирование обработки Startup // блокирование обработки Startup
// пока не пройдёт инициализация датчиков // пока не пройдёт инициализация датчиков
// см. preSysCommand() // см. preSysCommand()
{ {
...@@ -683,34 +705,34 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -683,34 +705,34 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
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
<< "(waitSM): Не дождались готовности(work) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(work) 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());
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -721,22 +743,22 @@ std::string UObject_SK::help() noexcept ...@@ -721,22 +743,22 @@ std::string UObject_SK::help() noexcept
s << "Init default values: " << endl; s << "Init default values: " << endl;
s << endl; s << endl;
s << "--" << argprefix << "sm-ready-timeout msec - wait SM ready for ask sensors. Now: " << smReadyTimeout << endl; s << "--" << argprefix << "sm-ready-timeout msec - wait SM ready for ask sensors. Now: " << smReadyTimeout << endl;
s << "--" << argprefix << "sm-test-id msec sensor - sensor for test SM ready. Now: " << smTestID << endl; s << "--" << argprefix << "sm-test-id msec sensor - sensor for test SM ready. Now: " << smTestID << endl;
s << "--" << argprefix << "sleep-msec msec - step period. Now: " << sleep_msec << endl; s << "--" << argprefix << "sleep-msec msec - step period. Now: " << sleep_msec << endl;
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;
s << " ****************************************************************************************** " << endl; s << " ****************************************************************************************** " << endl;
return s.str(); return s.str();
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -746,39 +768,42 @@ void UObject_SK::callback() noexcept ...@@ -746,39 +768,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 )
...@@ -793,21 +818,21 @@ void UObject_SK::callback() noexcept ...@@ -793,21 +818,21 @@ 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;
msleep( sleep_msec ); msleep( sleep_msec );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -815,32 +840,32 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val ) ...@@ -815,32 +840,32 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
{ {
if( _sid == uniset::DefaultObjectId ) if( _sid == uniset::DefaultObjectId )
return; return;
ui->setValue(_sid,_val);
ui->setValue(_sid, _val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preSensorInfo( const uniset::SensorMessage* _sm ) void UObject_SK::preSensorInfo( const uniset::SensorMessage* _sm )
{ {
sensorInfo(_sm); sensorInfo(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::initFromSM() 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 )
...@@ -853,7 +878,7 @@ long UObject_SK::getValue( uniset::ObjectId _sid ) ...@@ -853,7 +878,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;
} }
} }
...@@ -862,33 +887,35 @@ long UObject_SK::getValue( uniset::ObjectId _sid ) ...@@ -862,33 +887,35 @@ 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( ;; )
{ {
try try
{ {
return; return;
} }
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);
} }
......
...@@ -20,7 +20,7 @@ static void init_test() ...@@ -20,7 +20,7 @@ static void init_test()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static float myRound( float v, size_t delim ) static float myRound( float v, size_t delim )
{ {
return ( std::round(v*delim) / (float)delim ); return ( std::round(v * delim) / (float)delim );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static bool init_iobase( IOBase* ib, const std::string& sensor ) static bool init_iobase( IOBase* ib, const std::string& sensor )
......
...@@ -32,12 +32,12 @@ TEST_CASE("[REST API: conf]", "[restapi][conf]") ...@@ -32,12 +32,12 @@ TEST_CASE("[REST API: conf]", "[restapi][conf]")
// Ожидаемый формат ответа: // Ожидаемый формат ответа:
// {"conf": [ // {"conf": [
// {"id":"2","iotype":"DI","mbaddr":"0x01","mbfunc":"0x06","mbreg":"0x02","mbtype":"rtu","name":"Input2_S","nbit":"11","priority":"Medium","rs":"4","textname":"Команда 2"} // {"id":"2","iotype":"DI","mbaddr":"0x01","mbfunc":"0x06","mbreg":"0x02","mbtype":"rtu","name":"Input2_S","nbit":"11","priority":"Medium","rs":"4","textname":"Команда 2"}
// ], // ],
// "object": // "object":
// {"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"} // {"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}
// } // }
// //
Poco::JSON::Object::Ptr json = result.extract<Poco::JSON::Object::Ptr>(); Poco::JSON::Object::Ptr json = result.extract<Poco::JSON::Object::Ptr>();
REQUIRE(json); REQUIRE(json);
...@@ -155,8 +155,8 @@ TEST_CASE("[REST API: /get]", "[restapi][get]") ...@@ -155,8 +155,8 @@ TEST_CASE("[REST API: /get]", "[restapi][get]")
{ {
// QUERY: /get?dummy // QUERY: /get?dummy
// Ожидаемый формат ответа: // Ожидаемый формат ответа:
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}, // {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[{"error":"Sensor not found","name":"dummy"}]} // "sensors":[{"error":"Sensor not found","name":"dummy"}]}
std::string s = shm->apiRequest("/get?dummy"); std::string s = shm->apiRequest("/get?dummy");
Poco::JSON::Parser parser; Poco::JSON::Parser parser;
...@@ -245,17 +245,17 @@ TEST_CASE("[REST API: /consumers]", "[restapi][consumers]") ...@@ -245,17 +245,17 @@ TEST_CASE("[REST API: /consumers]", "[restapi][consumers]")
// QUERY: /consumers // QUERY: /consumers
// Ожидаемый формат ответа: // Ожидаемый формат ответа:
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}, // {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[ // "sensors":[
// {"consumers":[ // {"consumers":[
// {"attempt":10,"id":6000,"lostEvents":0,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0} // {"attempt":10,"id":6000,"lostEvents":0,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ], // ],
// "sensor":{"id":1,"name":"Input1_S"}}, // "sensor":{"id":1,"name":"Input1_S"}},
// {"consumers":[ // {"consumers":[
// {"attempt":4,"id":6000,"lostEvents":4,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0} // {"attempt":4,"id":6000,"lostEvents":4,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ], // ],
// "sensor":{"id":10,"name":"AI_AS"}} // "sensor":{"id":10,"name":"AI_AS"}}
// ]} // ]}
std::string s = shm->apiRequest("/consumers"); std::string s = shm->apiRequest("/consumers");
...@@ -287,11 +287,11 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]") ...@@ -287,11 +287,11 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]")
// QUERY: /lost // QUERY: /lost
// Ожидаемый формат ответа: // Ожидаемый формат ответа:
// {"lost consumers":[ // {"lost consumers":[
// ... // ...
// ], // ],
// "object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"} // "object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}
// } // }
// Сперва имитируем зазачика (который "исчезнет"). // Сперва имитируем зазачика (который "исчезнет").
const ObjectId myID = 6013; // TestProc2 const ObjectId myID = 6013; // TestProc2
...@@ -300,8 +300,8 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]") ...@@ -300,8 +300,8 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]")
shm->askSensor(sid, UniversalIO::UIONotify, myID ); shm->askSensor(sid, UniversalIO::UIONotify, myID );
// имитируем изменения // имитируем изменения
for( size_t i=200; i<220; i++ ) for( size_t i = 200; i < 220; i++ )
shm->setValue(sid,i); shm->setValue(sid, i);
// проверяем список "потерянных" // проверяем список "потерянных"
std::string s = shm->apiRequest("/lost"); std::string s = shm->apiRequest("/lost");
......
...@@ -112,10 +112,10 @@ namespace uniset ...@@ -112,10 +112,10 @@ namespace uniset
// ---------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------
class DBRowIterator: class DBRowIterator:
public std::iterator<std::bidirectional_iterator_tag, public std::iterator<std::bidirectional_iterator_tag,
DBResult::ROW::value_type, DBResult::ROW::value_type,
DBResult::ROW::difference_type, DBResult::ROW::difference_type,
DBResult::ROW::pointer, DBResult::ROW::pointer,
DBResult::ROW::reference> DBResult::ROW::reference>
{ {
public: public:
......
...@@ -165,7 +165,10 @@ namespace uniset ...@@ -165,7 +165,10 @@ namespace uniset
virtual void dump(const IONotifyController* ic, std::shared_ptr<NCRestorer::SInfo>& inf, const IONotifyController::ConsumerListInfo& lst) override; virtual void dump(const IONotifyController* ic, std::shared_ptr<NCRestorer::SInfo>& inf, const IONotifyController::ConsumerListInfo& lst) override;
virtual void dumpThreshold(const IONotifyController* ic, std::shared_ptr<NCRestorer::SInfo>& inf, const IONotifyController::ThresholdExtList& lst) override; virtual void dumpThreshold(const IONotifyController* ic, std::shared_ptr<NCRestorer::SInfo>& inf, const IONotifyController::ThresholdExtList& lst) override;
virtual bool readOnly() const { return true; } virtual bool readOnly() const
{
return true;
}
protected: protected:
......
...@@ -75,7 +75,7 @@ namespace uniset ...@@ -75,7 +75,7 @@ namespace uniset
namespace UHttp namespace UHttp
{ {
// текущая версия API // текущая версия API
const std::string UHTTP_API_VERSION="v01"; const std::string UHTTP_API_VERSION = "v01";
/*! интерфейс для объекта выдающего json-данные */ /*! интерфейс для объекта выдающего json-данные */
class IHttpRequest class IHttpRequest
......
...@@ -27,148 +27,148 @@ namespace uniset ...@@ -27,148 +27,148 @@ namespace uniset
{ {
using namespace UHttp; using namespace UHttp;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ): UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
registry(_registry) registry(_registry)
{
log = make_shared<DebugStream>();
}
// -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
{
if( !registry )
{ {
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); log = make_shared<DebugStream>();
resp.setContentType("text/json");
std::ostream& out = resp.send();
Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
jdata->set("error", resp.getReasonForStatus(resp.getStatus()));
jdata->set("ecode", resp.getStatus());
jdata->set("message", "Unknown 'registry of objects'");
jdata->stringify(out);
out.flush();
return;
} }
// -------------------------------------------------------------------------
// В этой версии API поддерживается только GET void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
if( req.getMethod() != "GET" )
{ {
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST); if( !registry )
resp.setContentType("text/json"); {
std::ostream& out = resp.send(); resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
Poco::JSON::Object jdata; resp.setContentType("text/json");
jdata.set("error", resp.getReasonForStatus(resp.getStatus())); std::ostream& out = resp.send();
jdata.set("ecode", (int)resp.getStatus()); Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
jdata.set("message", "method must be 'GET'"); jdata->set("error", resp.getReasonForStatus(resp.getStatus()));
jdata.stringify(out); jdata->set("ecode", resp.getStatus());
out.flush(); jdata->set("message", "Unknown 'registry of objects'");
return; jdata->stringify(out);
} out.flush();
return;
Poco::URI uri(req.getURI()); }
if( log->is_info() ) // В этой версии API поддерживается только GET
log->info() << req.getHost() << ": query: " << uri.getQuery() << endl; if( req.getMethod() != "GET" )
{
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp.setContentType("text/json");
std::ostream& out = resp.send();
Poco::JSON::Object jdata;
jdata.set("error", resp.getReasonForStatus(resp.getStatus()));
jdata.set("ecode", (int)resp.getStatus());
jdata.set("message", "method must be 'GET'");
jdata.stringify(out);
out.flush();
return;
}
std::vector<std::string> seg; Poco::URI uri(req.getURI());
uri.getPathSegments(seg);
// example: http://host:port/api/version/ObjectName if( log->is_info() )
if( seg.size() < 3 log->info() << req.getHost() << ": query: " << uri.getQuery() << endl;
|| seg[0] != "api"
|| seg[1] != UHTTP_API_VERSION
|| seg[2].empty() )
{
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp.setContentType("text/json");
std::ostream& out = resp.send();
Poco::JSON::Object jdata;
jdata.set("error", resp.getReasonForStatus(resp.getStatus()));
jdata.set("ecode", (int)resp.getStatus());
jdata.set("message", "BAD REQUEST STRUCTURE");
jdata.stringify(out);
out.flush();
return;
}
const std::string objectName(seg[2]);
auto qp = uri.getQueryParameters();
resp.setStatus(HTTPResponse::HTTP_OK); std::vector<std::string> seg;
resp.setContentType("text/json"); uri.getPathSegments(seg);
std::ostream& out = resp.send();
try // example: http://host:port/api/version/ObjectName
{ if( seg.size() < 3
if( objectName == "help" ) || seg[0] != "api"
{ || seg[1] != UHTTP_API_VERSION
out << "{ \"help\": [" || seg[2].empty() )
"{\"help\": {\"desc\": \"this help\"}},"
"{\"list\": {\"desc\": \"list of objects\"}},"
"{\"ObjectName\": {\"desc\": \"ObjectName information\"}},"
"{\"ObjectName/help\": {\"desc\": \"help for ObjectName\"}},"
"{\"apidocs\": {\"desc\": \"https://github.com/Etersoft/uniset2\"}}"
"]}";
}
else if( objectName == "list" )
{ {
auto json = registry->httpGetObjectsList(qp); resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
json->stringify(out); resp.setContentType("text/json");
std::ostream& out = resp.send();
Poco::JSON::Object jdata;
jdata.set("error", resp.getReasonForStatus(resp.getStatus()));
jdata.set("ecode", (int)resp.getStatus());
jdata.set("message", "BAD REQUEST STRUCTURE");
jdata.stringify(out);
out.flush();
return;
} }
else if( seg.size() == 4 && seg[3] == "help" ) // /api/version/ObjectName/help
{ const std::string objectName(seg[2]);
auto json = registry->httpHelpByName(objectName, qp); auto qp = uri.getQueryParameters();
json->stringify(out);
} resp.setStatus(HTTPResponse::HTTP_OK);
else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx.. resp.setContentType("text/json");
std::ostream& out = resp.send();
try
{ {
auto json = registry->httpRequestByName(objectName, seg[3], qp); if( objectName == "help" )
json->stringify(out); {
out << "{ \"help\": ["
"{\"help\": {\"desc\": \"this help\"}},"
"{\"list\": {\"desc\": \"list of objects\"}},"
"{\"ObjectName\": {\"desc\": \"ObjectName information\"}},"
"{\"ObjectName/help\": {\"desc\": \"help for ObjectName\"}},"
"{\"apidocs\": {\"desc\": \"https://github.com/Etersoft/uniset2\"}}"
"]}";
}
else if( objectName == "list" )
{
auto json = registry->httpGetObjectsList(qp);
json->stringify(out);
}
else if( seg.size() == 4 && seg[3] == "help" ) // /api/version/ObjectName/help
{
auto json = registry->httpHelpByName(objectName, qp);
json->stringify(out);
}
else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx..
{
auto json = registry->httpRequestByName(objectName, seg[3], qp);
json->stringify(out);
}
else
{
auto json = registry->httpGetByName(objectName, qp);
json->stringify(out);
}
} }
else // catch( Poco::JSON::JSONException jsone )
// {
// std::cout << "JSON ERROR: " << jsone.message() << std::endl;
// }
catch( std::exception& ex )
{ {
auto json = registry->httpGetByName(objectName, qp); ostringstream err;
json->stringify(out); err << ex.what();
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
resp.setContentType("text/json");
Poco::JSON::Object jdata;
jdata.set("error", err.str());
jdata.set("ecode", (int)resp.getStatus());
jdata.stringify(out);
} }
}
// catch( Poco::JSON::JSONException jsone )
// {
// std::cout << "JSON ERROR: " << jsone.message() << std::endl;
// }
catch( std::exception& ex )
{
ostringstream err;
err << ex.what();
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
resp.setContentType("text/json");
Poco::JSON::Object jdata;
jdata.set("error", err.str());
jdata.set("ecode", (int)resp.getStatus());
jdata.stringify(out);
}
out.flush(); out.flush();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpRequestHandlerFactory::UHttpRequestHandlerFactory(std::shared_ptr<IHttpRequestRegistry>& _registry ): UHttpRequestHandlerFactory::UHttpRequestHandlerFactory(std::shared_ptr<IHttpRequestRegistry>& _registry ):
registry(_registry) registry(_registry)
{ {
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req ) HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{ {
return new UHttpRequestHandler(registry); return new UHttpRequestHandler(registry);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Poco::JSON::Object::Ptr IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
std::ostringstream err; std::ostringstream err;
err << "(IHttpRequest::Request): " << req << " not supported"; err << "(IHttpRequest::Request): " << req << " not supported";
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of namespace uniset } // end of namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif #endif
...@@ -25,59 +25,59 @@ using namespace Poco::Net; ...@@ -25,59 +25,59 @@ using namespace Poco::Net;
namespace uniset namespace uniset
{ {
using namespace UHttp; using namespace UHttp;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ): UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host, _port) sa(_host, _port)
{
try
{ {
mylog = std::make_shared<DebugStream>(); try
{
mylog = std::make_shared<DebugStream>();
/*! \FIXME: доделать конфигурирование параметров */
HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1);
/*! \FIXME: доделать конфигурирование параметров */ reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier);
HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1);
reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier); http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams );
}
catch( std::exception& ex )
{
std::stringstream err;
err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what();
throw uniset::SystemError(err.str());
}
http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams ); mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl;
} }
catch( std::exception& ex ) // -------------------------------------------------------------------------
UHttpServer::~UHttpServer()
{ {
std::stringstream err; if( http )
err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what(); http->stop();
throw uniset::SystemError(err.str());
} }
// -------------------------------------------------------------------------
mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl; void UHttpServer::start()
} {
// ------------------------------------------------------------------------- http->start();
UHttpServer::~UHttpServer() }
{ // -------------------------------------------------------------------------
if( http ) void UHttpServer::stop()
{
http->stop(); http->stop();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpServer::start() UHttpServer::UHttpServer()
{ {
http->start(); }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- std::shared_ptr<DebugStream> UHttpServer::log()
void UHttpServer::stop() {
{ return mylog;
http->stop(); }
} // -------------------------------------------------------------------------
// -------------------------------------------------------------------------
UHttpServer::UHttpServer()
{
}
// -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log()
{
return mylog;
}
// -------------------------------------------------------------------------
} // end of namespace uniset } // end of namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
...@@ -125,6 +125,7 @@ namespace uniset ...@@ -125,6 +125,7 @@ namespace uniset
io.start(sock->getSocket(), ev::READ); io.start(sock->getSocket(), ev::READ);
ioTimeout.set(loop); ioTimeout.set(loop);
if( sessTimeout > 0 ) if( sessTimeout > 0 )
ioTimeout.start(sessTimeout); ioTimeout.start(sessTimeout);
} }
......
...@@ -50,10 +50,11 @@ namespace uniset ...@@ -50,10 +50,11 @@ namespace uniset
{ {
try try
{ {
std::future<bool> future = std::async(std::launch::async, [=]() std::future<bool> future = std::async(std::launch::async, [ = ]()
{ {
// Сама проверка... // Сама проверка...
bool result = false; bool result = false;
try try
{ {
UTCPStream t; UTCPStream t;
...@@ -68,9 +69,11 @@ namespace uniset ...@@ -68,9 +69,11 @@ namespace uniset
}); });
std::future_status status; std::future_status status;
do do
{ {
status = future.wait_for(std::chrono::milliseconds(tout_msec)); status = future.wait_for(std::chrono::milliseconds(tout_msec));
if( status == std::future_status::timeout ) if( status == std::future_status::timeout )
return false; return false;
} }
...@@ -82,6 +85,7 @@ namespace uniset ...@@ -82,6 +85,7 @@ namespace uniset
{ {
} }
return false; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -89,7 +93,7 @@ namespace uniset ...@@ -89,7 +93,7 @@ namespace uniset
{ {
try try
{ {
std::future<bool> future = std::async(std::launch::async, [=]() std::future<bool> future = std::async(std::launch::async, [ = ]()
{ {
// Сама проверка... // Сама проверка...
ostringstream cmd; ostringstream cmd;
...@@ -101,9 +105,11 @@ namespace uniset ...@@ -101,9 +105,11 @@ namespace uniset
}); });
std::future_status status; std::future_status status;
do do
{ {
status = future.wait_for(std::chrono::milliseconds(tout_msec)); status = future.wait_for(std::chrono::milliseconds(tout_msec));
if( status == std::future_status::timeout ) if( status == std::future_status::timeout )
return false; return false;
} }
......
...@@ -438,7 +438,8 @@ namespace uniset ...@@ -438,7 +438,8 @@ namespace uniset
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
auto idlist = uniset::explode_str(params[0].first,','); auto idlist = uniset::explode_str(params[0].first, ',');
if( idlist.empty() ) if( idlist.empty() )
{ {
ostringstream err; ostringstream err;
...@@ -447,7 +448,8 @@ namespace uniset ...@@ -447,7 +448,8 @@ namespace uniset
} }
string props = {""}; string props = {""};
for( const auto& p: params )
for( const auto& p : params )
{ {
if( p.first == "props" ) if( p.first == "props" )
{ {
...@@ -456,9 +458,10 @@ namespace uniset ...@@ -456,9 +458,10 @@ namespace uniset
} }
} }
for( const auto& id: idlist ) for( const auto& id : idlist )
{ {
Poco::JSON::Object::Ptr j = request_conf_name(id,props); Poco::JSON::Object::Ptr j = request_conf_name(id, props);
if( j ) if( j )
jdata->add(j); jdata->add(j);
} }
...@@ -477,8 +480,8 @@ namespace uniset ...@@ -477,8 +480,8 @@ namespace uniset
{ {
ostringstream err; ostringstream err;
err << name << " not found.."; err << name << " not found..";
jdata->set(name,""); jdata->set(name, "");
jdata->set("error",err.str()); jdata->set("error", err.str());
return jdata; return jdata;
} }
...@@ -488,27 +491,29 @@ namespace uniset ...@@ -488,27 +491,29 @@ namespace uniset
{ {
ostringstream err; ostringstream err;
err << name << " not found confnode.."; err << name << " not found confnode..";
jdata->set(name,""); jdata->set(name, "");
jdata->set("error",err.str()); jdata->set("error", err.str());
return jdata; return jdata;
} }
UniXML::iterator it(xmlnode); UniXML::iterator it(xmlnode);
jdata->set("name",it.getProp("name")); jdata->set("name", it.getProp("name"));
jdata->set("id",it.getProp("id")); jdata->set("id", it.getProp("id"));
if( !props.empty() ) if( !props.empty() )
{ {
auto lst = uniset::explode_str(props,','); auto lst = uniset::explode_str(props, ',');
for( const auto& p: lst )
jdata->set(p,it.getProp(p)); for( const auto& p : lst )
jdata->set(p, it.getProp(p));
} }
else else
{ {
auto lst = it.getPropList(); auto lst = it.getPropList();
for( const auto& p: lst )
jdata->set(p.first,p.second); for( const auto& p : lst )
jdata->set(p.first, p.second);
} }
return jdata; return jdata;
...@@ -682,6 +687,7 @@ namespace uniset ...@@ -682,6 +687,7 @@ namespace uniset
bool actOK = false; bool actOK = false;
auto conf = uniset_conf(); auto conf = uniset_conf();
for( size_t i = 0; i < conf->getRepeatCount(); i++ ) for( size_t i = 0; i < conf->getRepeatCount(); i++ )
{ {
try try
...@@ -982,7 +988,7 @@ namespace uniset ...@@ -982,7 +988,7 @@ namespace uniset
else if( query == "conf" ) else if( query == "conf" )
{ {
// запрос вида: /conf/query?params // запрос вида: /conf/query?params
string qconf = ( seg.size() > (qind+1) ) ? seg[qind+1] : ""; string qconf = ( seg.size() > (qind + 1) ) ? seg[qind + 1] : "";
auto reply = request_conf(qconf, uri.getQueryParameters()); auto reply = request_conf(qconf, uri.getQueryParameters());
reply->stringify(out); reply->stringify(out);
} }
...@@ -1018,7 +1024,7 @@ namespace uniset ...@@ -1018,7 +1024,7 @@ namespace uniset
Poco::JSON::Object jdata; Poco::JSON::Object jdata;
jdata.set("error", err.str()); jdata.set("error", err.str());
jdata.set("ecode", (int)Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); jdata.set("ecode", (int)Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
// jdata.set("ename", Poco::Net::HTTPResponse::getReasonForStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR)); // jdata.set("ename", Poco::Net::HTTPResponse::getReasonForStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR));
ostringstream out; ostringstream out;
jdata.stringify(out); jdata.stringify(out);
......
...@@ -38,6 +38,7 @@ namespace uniset ...@@ -38,6 +38,7 @@ namespace uniset
bool CommonEventLoop::runDefaultLoop( size_t waitTimeout_msec ) bool CommonEventLoop::runDefaultLoop( size_t waitTimeout_msec )
{ {
std::lock_guard<std::mutex> lock(thr_mutex); std::lock_guard<std::mutex> lock(thr_mutex);
if( thr ) if( thr )
return true; return true;
...@@ -235,7 +236,7 @@ namespace uniset ...@@ -235,7 +236,7 @@ namespace uniset
{ {
if( EV_ERROR & revents ) if( EV_ERROR & revents )
{ {
// cerr << myname << "(CommonEventLoop::onStop): invalid event" << endl; // cerr << myname << "(CommonEventLoop::onStop): invalid event" << endl;
return; return;
} }
......
...@@ -98,7 +98,7 @@ IOController::InitSignal IOController::signal_init() ...@@ -98,7 +98,7 @@ IOController::InitSignal IOController::signal_init()
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void IOController::activateInit() void IOController::activateInit()
{ {
for( auto&& io: ioList ) for( auto && io : ioList )
{ {
try try
{ {
...@@ -473,9 +473,10 @@ void IOController::dumpToDB() ...@@ -473,9 +473,10 @@ void IOController::dumpToDB()
{ {
// lock // lock
// uniset_mutex_lock lock(ioMutex, 100); // uniset_mutex_lock lock(ioMutex, 100);
for( auto&& usi: ioList ) for( auto && usi : ioList )
{ {
auto& s = usi.second; auto& s = usi.second;
if ( !s->dbignore ) if ( !s->dbignore )
{ {
SensorMessage sm( std::move(s->makeSensorMessage()) ); SensorMessage sm( std::move(s->makeSensorMessage()) );
...@@ -868,7 +869,7 @@ Poco::JSON::Object::Ptr IOController::httpHelp( const Poco::URI::QueryParameters ...@@ -868,7 +869,7 @@ Poco::JSON::Object::Ptr IOController::httpHelp( const Poco::URI::QueryParameters
{ {
// 'get' // 'get'
uniset::json::help::item cmd("get","get value for sensor"); uniset::json::help::item cmd("get", "get value for sensor");
cmd.param("id1,name2,id3", "get value for id1,name2,id3 sensors"); cmd.param("id1,name2,id3", "get value for id1,name2,id3 sensors");
cmd.param("shortInfo", "get short information for sensors"); cmd.param("shortInfo", "get short information for sensors");
myhelp.add(cmd); myhelp.add(cmd);
...@@ -1044,7 +1045,7 @@ Poco::JSON::Object::Ptr IOController::request_sensors( const string& req, const ...@@ -1044,7 +1045,7 @@ Poco::JSON::Object::Ptr IOController::request_sensors( const string& req, const
} }
jdata->set("count", count); jdata->set("count", count);
jdata->set("size",ioCount()); jdata->set("size", ioCount());
return jdata; return jdata;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -79,6 +79,7 @@ IONotifyController::~IONotifyController() ...@@ -79,6 +79,7 @@ IONotifyController::~IONotifyController()
void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const std::string& consumer ) void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const std::string& consumer )
{ {
ObjectId consumer_id = uniset_conf()->getObjectID(consumer); ObjectId consumer_id = uniset_conf()->getObjectID(consumer);
if( consumer_id == DefaultObjectId ) if( consumer_id == DefaultObjectId )
consumer_id = uniset_conf()->getControllerID(consumer); consumer_id = uniset_conf()->getControllerID(consumer);
...@@ -94,7 +95,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st ...@@ -94,7 +95,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// Формируем статистику по каждому датчику.. // Формируем статистику по каждому датчику..
struct StatInfo struct StatInfo
{ {
StatInfo( ObjectId id, const ConsumerInfoExt& c ):inf(c),sid(id){} StatInfo( ObjectId id, const ConsumerInfoExt& c ): inf(c), sid(id) {}
const ConsumerInfoExt inf; const ConsumerInfoExt inf;
ObjectId sid; ObjectId sid;
...@@ -105,12 +106,13 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st ...@@ -105,12 +106,13 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// общее количество SensorMessage полученное этим заказчиком // общее количество SensorMessage полученное этим заказчиком
size_t smCount = 0; size_t smCount = 0;
{ // lock askIOMutex {
// lock askIOMutex
// выводим информацию по конкретному объекту // выводим информацию по конкретному объекту
uniset_rwmutex_rlock lock(askIOMutex); uniset_rwmutex_rlock lock(askIOMutex);
for( auto&& a : askIOList ) for( auto && a : askIOList )
{ {
auto& i = a.second; auto& i = a.second;
...@@ -124,7 +126,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st ...@@ -124,7 +126,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
{ {
if( c.id == consumer_id ) if( c.id == consumer_id )
{ {
stat.emplace_back(a.first,c); stat.emplace_back(a.first, c);
smCount += c.smCount; smCount += c.smCount;
break; break;
} }
...@@ -136,20 +138,22 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st ...@@ -136,20 +138,22 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// выводим информацию по конкретному объекту // выводим информацию по конкретному объекту
uniset_rwmutex_rlock lock(trshMutex); uniset_rwmutex_rlock lock(trshMutex);
for( auto&& a: askTMap ) for( auto && a : askTMap )
{ {
uniset_rwmutex_rlock lock2(a.second.mut); uniset_rwmutex_rlock lock2(a.second.mut);
for( auto&& t: a.second.list )
for( auto && t : a.second.list )
{ {
uniset_rwmutex_rlock lock3(t.clst.mut); uniset_rwmutex_rlock lock3(t.clst.mut);
for( const auto& c: t.clst.clst )
for( const auto& c : t.clst.clst )
{ {
if( c.id == consumer_id ) if( c.id == consumer_id )
{ {
if( t.sid != DefaultObjectId ) if( t.sid != DefaultObjectId )
stat.emplace_back(t.sid,c); stat.emplace_back(t.sid, c);
else else
stat.emplace_back(a.first,c); stat.emplace_back(a.first, c);
smCount += c.smCount; smCount += c.smCount;
break; break;
...@@ -175,7 +179,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st ...@@ -175,7 +179,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
for( const auto& s: stat ) for( const auto& s : stat )
{ {
inf << " " << "(" << setw(6) << s.sid << ") " inf << " " << "(" << setw(6) << s.sid << ") "
<< setw(35) << ORepHelpers::getShortName(oind->getMapName(s.sid)) << setw(35) << ORepHelpers::getShortName(oind->getMapName(s.sid))
...@@ -208,6 +212,7 @@ void IONotifyController::showStatisticsForLostConsumers( ostringstream& inf ) ...@@ -208,6 +212,7 @@ void IONotifyController::showStatisticsForLostConsumers( ostringstream& inf )
<< endl; << endl;
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
for( const auto& l : lostConsumers ) for( const auto& l : lostConsumers )
{ {
inf << " " << "(" << setw(6) << l.first << ") " inf << " " << "(" << setw(6) << l.first << ") "
...@@ -223,7 +228,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf ) ...@@ -223,7 +228,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf )
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
for( auto&& a : askIOList ) for( auto && a : askIOList )
{ {
auto& i = a.second; auto& i = a.second;
...@@ -234,6 +239,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf ) ...@@ -234,6 +239,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf )
continue; continue;
inf << "(" << setw(6) << a.first << ")[" << oind->getMapName(a.first) << "]" << endl; inf << "(" << setw(6) << a.first << ")[" << oind->getMapName(a.first) << "]" << endl;
for( const auto& c : i.clst ) for( const auto& c : i.clst )
{ {
inf << " " << "(" << setw(6) << c.id << ")" inf << " " << "(" << setw(6) << c.id << ")"
...@@ -255,7 +261,7 @@ void IONotifyController::showStatisticsForConsumersWithLostEvent( ostringstream& ...@@ -255,7 +261,7 @@ void IONotifyController::showStatisticsForConsumersWithLostEvent( ostringstream&
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
bool empty = true; bool empty = true;
for( auto&& a : askIOList ) for( auto && a : askIOList )
{ {
auto& i = a.second; auto& i = a.second;
...@@ -316,6 +322,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri ...@@ -316,6 +322,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
auto oind = conf->oind; auto oind = conf->oind;
ObjectId sid = conf->getSensorID(name); ObjectId sid = conf->getSensorID(name);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
inf << "..not found ID for sensor '" << name << "'" << endl; inf << "..not found ID for sensor '" << name << "'" << endl;
...@@ -327,6 +334,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri ...@@ -327,6 +334,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
{ {
uniset_rwmutex_rlock lock(askIOMutex); uniset_rwmutex_rlock lock(askIOMutex);
auto s = askIOList.find(sid); auto s = askIOList.find(sid);
if( s == askIOList.end() ) if( s == askIOList.end() )
{ {
inf << "..not found consumers for sensor '" << name << "'" << endl; inf << "..not found consumers for sensor '" << name << "'" << endl;
...@@ -341,7 +349,8 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri ...@@ -341,7 +349,8 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
<< "--------------------------------------------------------------------" << endl; << "--------------------------------------------------------------------" << endl;
uniset_rwmutex_rlock lock2(clist->mut); uniset_rwmutex_rlock lock2(clist->mut);
for( const auto& c: clist->clst )
for( const auto& c : clist->clst )
{ {
inf << " (" << setw(6) << c.id << ")" inf << " (" << setw(6) << c.id << ")"
<< setw(35) << ORepHelpers::getShortName(oind->getMapName(c.id)) << setw(35) << ORepHelpers::getShortName(oind->getMapName(c.id))
...@@ -391,7 +400,8 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -391,7 +400,8 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
} }
else if( !param.empty() ) else if( !param.empty() )
{ {
auto query = uniset::explode_str(param,':'); auto query = uniset::explode_str(param, ':');
if( query.empty() || query.size() == 1 ) if( query.empty() || query.size() == 1 )
showStatisticsForConsumer(inf, param); showStatisticsForConsumer(inf, param);
else if( query.size() > 1 ) else if( query.size() > 1 )
...@@ -524,11 +534,12 @@ void IONotifyController::askSensor(const uniset::ObjectId sid, ...@@ -524,11 +534,12 @@ void IONotifyController::askSensor(const uniset::ObjectId sid,
if( cmd == UniversalIO::UIONotify || (cmd == UIONotifyFirstNotNull && usi->value) ) if( cmd == UniversalIO::UIONotify || (cmd == UIONotifyFirstNotNull && usi->value) )
{ {
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList)); ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst ) if( lst )
{ {
uniset::uniset_rwmutex_rlock lock(usi->val_lock); uniset::uniset_rwmutex_rlock lock(usi->val_lock);
SensorMessage smsg( std::move(usi->makeSensorMessage(false)) ); SensorMessage smsg( std::move(usi->makeSensorMessage(false)) );
send(*lst,smsg,&ci); send(*lst, smsg, &ci);
} }
} }
} }
...@@ -554,6 +565,7 @@ void IONotifyController::ask( AskMap& askLst, const uniset::ObjectId sid, ...@@ -554,6 +565,7 @@ void IONotifyController::ask( AskMap& askLst, const uniset::ObjectId sid,
// т.к. мы делали move // т.к. мы делали move
// то теперь надо достучаться до списка.. // то теперь надо достучаться до списка..
auto i = askLst.find(sid); auto i = askLst.find(sid);
if( i != askLst.end() ) if( i != askLst.end() )
{ {
try try
...@@ -633,10 +645,11 @@ void IONotifyController::ask( AskMap& askLst, const uniset::ObjectId sid, ...@@ -633,10 +645,11 @@ void IONotifyController::ask( AskMap& askLst, const uniset::ObjectId sid,
if( askIterator != askLst.end() ) if( askIterator != askLst.end() )
{ {
auto s = myiofind(sid); auto s = myiofind(sid);
if( s != myioEnd() ) if( s != myioEnd() )
s->second->setUserData(udataConsumerList,&(askIterator->second)); s->second->setUserData(udataConsumerList, &(askIterator->second));
else else
s->second->setUserData(udataConsumerList,nullptr); s->second->setUserData(udataConsumerList, nullptr);
} }
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -677,6 +690,7 @@ long IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf ...@@ -677,6 +690,7 @@ long IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
catch(...) {} catch(...) {}
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList)); ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst ) if( lst )
send(*lst, sm); send(*lst, sm);
} }
...@@ -943,6 +957,7 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum ...@@ -943,6 +957,7 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum
SensorMessage sm(std::move(li->second->makeSensorMessage())); SensorMessage sm(std::move(li->second->makeSensorMessage()));
sm.consumer = ci.id; sm.consumer = ci.id;
sm.tid = tid; sm.tid = tid;
// Проверка нижнего предела // Проверка нижнего предела
if( val <= lowLimit ) if( val <= lowLimit )
sm.threshold = false; sm.threshold = false;
...@@ -953,11 +968,12 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum ...@@ -953,11 +968,12 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum
if( it != askTMap.end() ) if( it != askTMap.end() )
{ {
uniset_rwmutex_rlock l(it->second.mut); uniset_rwmutex_rlock l(it->second.mut);
for( auto i = it->second.list.begin(); i != it->second.list.end(); ++i ) for( auto i = it->second.list.begin(); i != it->second.list.end(); ++i )
{ {
if( i->id == tid ) if( i->id == tid )
{ {
send(i->clst,sm,&ci); send(i->clst, sm, &ci);
break; break;
} }
} }
...@@ -1063,6 +1079,7 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn ...@@ -1063,6 +1079,7 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn
uniset_rwmutex_rlock lock(trshMutex); uniset_rwmutex_rlock lock(trshMutex);
ThresholdsListInfo* ti = static_cast<ThresholdsListInfo*>(usi->getUserData(udataThresholdList)); ThresholdsListInfo* ti = static_cast<ThresholdsListInfo*>(usi->getUserData(udataThresholdList));
if( !ti || ti->list.empty() ) if( !ti || ti->list.empty() )
return; return;
...@@ -1316,6 +1333,7 @@ void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& u ...@@ -1316,6 +1333,7 @@ void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& u
catch(...) {} catch(...) {}
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList)); ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst ) if( lst )
send(*lst, sm); send(*lst, sm);
} }
......
...@@ -153,6 +153,7 @@ NCRestorer::SInfo& NCRestorer::SInfo::operator=( const IOController_i::SensorIOI ...@@ -153,6 +153,7 @@ NCRestorer::SInfo& NCRestorer::SInfo::operator=( const IOController_i::SensorIOI
{ {
uniset_rwmutex_wrlock l(this->userdata_lock); uniset_rwmutex_wrlock l(this->userdata_lock);
for( size_t i = 0; i < IOController::USensorInfo::MaxUserData; i++ ) for( size_t i = 0; i < IOController::USensorInfo::MaxUserData; i++ )
this->userdata[i] = nullptr; this->userdata[i] = nullptr;
} }
......
...@@ -122,6 +122,7 @@ namespace uniset ...@@ -122,6 +122,7 @@ namespace uniset
int DBResult::getColIndex( const std::string& name ) int DBResult::getColIndex( const std::string& name )
{ {
auto i = colname.find(name); auto i = colname.find(name);
if( i == colname.end() ) if( i == colname.end() )
throw std::runtime_error("(DBInterface): Unknown field ='" + name + "'"); throw std::runtime_error("(DBInterface): Unknown field ='" + name + "'");
...@@ -130,7 +131,7 @@ namespace uniset ...@@ -130,7 +131,7 @@ namespace uniset
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string DBResult::getColName( int index ) std::string DBResult::getColName( int index )
{ {
for( auto&& c: colname ) for( auto && c : colname )
{ {
if( c.second == index ) if( c.second == index )
return c.first; return c.first;
...@@ -155,13 +156,13 @@ namespace uniset ...@@ -155,13 +156,13 @@ namespace uniset
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
DBRowIterator::DBRowIterator( DBResult& _dbres, const DBResult::ROW::iterator& _it ): DBRowIterator::DBRowIterator( DBResult& _dbres, const DBResult::ROW::iterator& _it ):
dbres(_dbres),it(_it) dbres(_dbres), it(_it)
{ {
} }
DBRowIterator::DBRowIterator( const DBRowIterator& i ): DBRowIterator::DBRowIterator( const DBRowIterator& i ):
dbres(i.dbres),it(i.it) dbres(i.dbres), it(i.it)
{ {
} }
......
...@@ -723,13 +723,16 @@ namespace uniset ...@@ -723,13 +723,16 @@ namespace uniset
{ {
// проверяем доступность endPoint попыткой создать соединение // проверяем доступность endPoint попыткой создать соединение
auto ep = omni::giopEndpoint::str2Endpoint( endPoint.c_str() ); auto ep = omni::giopEndpoint::str2Endpoint( endPoint.c_str() );
if( !ep ) if( !ep )
return false; return false;
bool ret = false; bool ret = false;
try try
{ {
ret = ep->Bind(); ret = ep->Bind();
if( ret ) if( ret )
ep->Shutdown(); ep->Shutdown();
} }
...@@ -1240,6 +1243,7 @@ namespace uniset ...@@ -1240,6 +1243,7 @@ namespace uniset
ObjectId Configuration::getAnyID( const string& name ) const noexcept ObjectId Configuration::getAnyID( const string& name ) const noexcept
{ {
ObjectId id = DefaultObjectId; ObjectId id = DefaultObjectId;
if( uniset::is_digit(name) ) if( uniset::is_digit(name) )
return uni_atoi(name); return uni_atoi(name);
......
...@@ -74,13 +74,13 @@ void SMonitor::sysCommand( const SystemMessage* sm ) ...@@ -74,13 +74,13 @@ void SMonitor::sysCommand( const SystemMessage* sm )
catch( const uniset::Exception& ex ) catch( const uniset::Exception& ex )
{ {
cerr << myname << ":(askSensor): " << ex << endl; cerr << myname << ":(askSensor): " << ex << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); std::terminate();
} }
catch(...) catch(...)
{ {
cerr << myname << ": НЕ СМОГ ЗАКАЗТЬ датчики " << endl; cerr << myname << ": НЕ СМОГ ЗАКАЗТЬ датчики " << endl;
// raise(SIGTERM); // raise(SIGTERM);
std::terminate(); std::terminate();
} }
} }
......
...@@ -213,16 +213,18 @@ void UniXML::setProp(xmlNode* node, const string& name, const string& text ) ...@@ -213,16 +213,18 @@ void UniXML::setProp(xmlNode* node, const string& name, const string& text )
UniXMLPropList UniXML::getPropList( xmlNode* node ) UniXMLPropList UniXML::getPropList( xmlNode* node )
{ {
UniXMLPropList lst; UniXMLPropList lst;
if( !node ) if( !node )
return lst; return lst;
xmlAttr* attribute = node->properties; xmlAttr* attribute = node->properties;
while( attribute ) while( attribute )
{ {
xmlChar* value = ::xmlNodeListGetString(node->doc, attribute->children, 1); xmlChar* value = ::xmlNodeListGetString(node->doc, attribute->children, 1);
const std::string nm( (const char*)attribute->name ); const std::string nm( (const char*)attribute->name );
const std::string val( (const char*)value ); const std::string val( (const char*)value );
lst.push_back( {nm,val} ); lst.push_back( {nm, val} );
xmlFree(value); xmlFree(value);
attribute = attribute->next; attribute = attribute->next;
} }
...@@ -651,7 +653,7 @@ UniXML_iterator& UniXML_iterator::operator++() noexcept ...@@ -651,7 +653,7 @@ UniXML_iterator& UniXML_iterator::operator++() noexcept
UniXML_iterator UniXML_iterator::operator++(int) noexcept UniXML_iterator UniXML_iterator::operator++(int) noexcept
{ {
UniXML_iterator temp(*this); UniXML_iterator temp(*this);
(*this) = (*this)+1; (*this) = (*this) + 1;
return temp; return temp;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -683,7 +685,7 @@ UniXML_iterator& UniXML_iterator::operator+(int step) noexcept ...@@ -683,7 +685,7 @@ UniXML_iterator& UniXML_iterator::operator+(int step) noexcept
UniXML_iterator UniXML_iterator::operator--(int) noexcept UniXML_iterator UniXML_iterator::operator--(int) noexcept
{ {
UniXML_iterator temp(*this); UniXML_iterator temp(*this);
(*this) = (*this)-1; (*this) = (*this) - 1;
return temp; return temp;
} }
......
...@@ -179,13 +179,13 @@ TEST_CASE("UniXML::iterator::getPropList", "[unixml][iterator-proplist][basic]" ...@@ -179,13 +179,13 @@ TEST_CASE("UniXML::iterator::getPropList", "[unixml][iterator-proplist][basic]"
std::ostringstream n; std::ostringstream n;
std::ostringstream v; std::ostringstream v;
for( size_t i=0; i<5; i++ ) for( size_t i = 0; i < 5; i++ )
{ {
n.str(""); n.str("");
n << "prop" << (i+1); n << "prop" << (i + 1);
v.str(""); v.str("");
v << "val" << (i+1); v << "val" << (i + 1);
REQUIRE( lst[i].first == n.str() ); REQUIRE( lst[i].first == n.str() );
REQUIRE( lst[i].second == v.str() ); REQUIRE( lst[i].second == v.str() );
......
...@@ -193,51 +193,51 @@ TEST_CASE("UniSetTypes: fcalibrate", "[utypes][fcalibrate]" ) ...@@ -193,51 +193,51 @@ TEST_CASE("UniSetTypes: fcalibrate", "[utypes][fcalibrate]" )
{ {
// float fcalibrate(float raw, float rawMin, float rawMax, float calMin, float calMax, bool limit = true ); // float fcalibrate(float raw, float rawMin, float rawMax, float calMin, float calMax, bool limit = true );
REQUIRE( fcalibrate(0.5,0.1,1.0,100.0,1000.0,true) == 500.0 ); REQUIRE( fcalibrate(0.5, 0.1, 1.0, 100.0, 1000.0, true) == 500.0 );
REQUIRE( fcalibrate(10.0,0.1,1.0,100.0,1000.0,true) == 1000.0 ); REQUIRE( fcalibrate(10.0, 0.1, 1.0, 100.0, 1000.0, true) == 1000.0 );
REQUIRE( fcalibrate(10.0,0.1,1.0,100.0,1000.0,false) == 10000.0 ); REQUIRE( fcalibrate(10.0, 0.1, 1.0, 100.0, 1000.0, false) == 10000.0 );
REQUIRE( fcalibrate(0.0,0.1,1.0,100.0,1000.0,true) == 100.0 ); REQUIRE( fcalibrate(0.0, 0.1, 1.0, 100.0, 1000.0, true) == 100.0 );
REQUIRE( fcalibrate(0.0,0.1,1.0,100.0,1000.0,false) == 0.0 ); REQUIRE( fcalibrate(0.0, 0.1, 1.0, 100.0, 1000.0, false) == 0.0 );
REQUIRE( fcalibrate(-10.0,0.1,1.0,100.0,1000.0,true) == 100.0 ); REQUIRE( fcalibrate(-10.0, 0.1, 1.0, 100.0, 1000.0, true) == 100.0 );
REQUIRE( fcalibrate(-10.0,0.1,1.0,100.0,1000.0,false) == -10000.0 ); REQUIRE( fcalibrate(-10.0, 0.1, 1.0, 100.0, 1000.0, false) == -10000.0 );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: lcalibrate", "[utypes][lcalibrate]" ) TEST_CASE("UniSetTypes: lcalibrate", "[utypes][lcalibrate]" )
{ {
// long lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit = true ); // long lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit = true );
REQUIRE( lcalibrate(5,1,10,100,1000,true) == 500 ); REQUIRE( lcalibrate(5, 1, 10, 100, 1000, true) == 500 );
REQUIRE( lcalibrate(5,1,10,100,1000,false) == 500 ); REQUIRE( lcalibrate(5, 1, 10, 100, 1000, false) == 500 );
REQUIRE( lcalibrate(0,1,10,100,1000,true) == 100 ); REQUIRE( lcalibrate(0, 1, 10, 100, 1000, true) == 100 );
REQUIRE( lcalibrate(0,1,10,100,1000,false) == 0 ); REQUIRE( lcalibrate(0, 1, 10, 100, 1000, false) == 0 );
REQUIRE( lcalibrate(100,1,10,100,1000,true) == 1000 ); REQUIRE( lcalibrate(100, 1, 10, 100, 1000, true) == 1000 );
REQUIRE( lcalibrate(100,1,10,100,1000,false) == 10000 ); REQUIRE( lcalibrate(100, 1, 10, 100, 1000, false) == 10000 );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: setinregion", "[utypes][setinregion]" ) TEST_CASE("UniSetTypes: setinregion", "[utypes][setinregion]" )
{ {
// long setinregion(long raw, long rawMin, long rawMax); // long setinregion(long raw, long rawMin, long rawMax);
REQUIRE( setinregion(5,1,10) == 5 ); REQUIRE( setinregion(5, 1, 10) == 5 );
REQUIRE( setinregion(1,1,10) == 1 ); REQUIRE( setinregion(1, 1, 10) == 1 );
REQUIRE( setinregion(10,1,10) == 10 ); REQUIRE( setinregion(10, 1, 10) == 10 );
REQUIRE( setinregion(0,1,10) == 1 ); REQUIRE( setinregion(0, 1, 10) == 1 );
REQUIRE( setinregion(100,1,10) == 10 ); REQUIRE( setinregion(100, 1, 10) == 10 );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: setoutregion", "[utypes][setoutregion]" ) TEST_CASE("UniSetTypes: setoutregion", "[utypes][setoutregion]" )
{ {
// long setoutregion(long raw, long calMin, long calMax); // long setoutregion(long raw, long calMin, long calMax);
REQUIRE( setoutregion(5,1,10) == 1 ); REQUIRE( setoutregion(5, 1, 10) == 1 );
REQUIRE( setoutregion(1,1,10) == 1 ); REQUIRE( setoutregion(1, 1, 10) == 1 );
REQUIRE( setoutregion(10,1,10) == 10 ); REQUIRE( setoutregion(10, 1, 10) == 10 );
REQUIRE( setoutregion(100,1,10) == 100 ); REQUIRE( setoutregion(100, 1, 10) == 100 );
REQUIRE( setoutregion(0,1,10) == 0 ); REQUIRE( setoutregion(0, 1, 10) == 0 );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: file_exist", "[utypes][file_exist]" ) TEST_CASE("UniSetTypes: file_exist", "[utypes][file_exist]" )
...@@ -254,7 +254,7 @@ TEST_CASE("UniSetTypes: check_filter", "[utypes][check_filter]" ) ...@@ -254,7 +254,7 @@ TEST_CASE("UniSetTypes: check_filter", "[utypes][check_filter]" )
// bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept; // bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
auto xml = uniset_conf()->getConfXML(); auto xml = uniset_conf()->getConfXML();
xmlNode* xnode = xml->findNode(xml->getFirstNode(),"test_check_filter"); xmlNode* xnode = xml->findNode(xml->getFirstNode(), "test_check_filter");
REQUIRE(xnode); REQUIRE(xnode);
UniXML::iterator it(xnode); UniXML::iterator it(xnode);
...@@ -278,9 +278,9 @@ TEST_CASE("UniSetTypes: findArgParam", "[utypes][findArgParam]" ) ...@@ -278,9 +278,9 @@ TEST_CASE("UniSetTypes: findArgParam", "[utypes][findArgParam]" )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" ) TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" )
{ {
// getArgParam( const std::string& name, // getArgParam( const std::string& name,
// int _argc, const char* const* _argv, // int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept // const std::string& defval = "" ) noexcept
int argc = 5; int argc = 5;
char* argv[] = {"progname", "--param1", "val", "--param2", "val2"}; char* argv[] = {"progname", "--param1", "val", "--param2", "val2"};
...@@ -292,9 +292,9 @@ TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" ) ...@@ -292,9 +292,9 @@ TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: getArgInt", "[utypes][getArgInt]" ) TEST_CASE("UniSetTypes: getArgInt", "[utypes][getArgInt]" )
{ {
// inline int getArgInt( const std::string& name, // inline int getArgInt( const std::string& name,
// int _argc, const char* const* _argv, // int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept // const std::string& defval = "" ) noexcept
int argc = 5; int argc = 5;
char* argv[] = {"progname", "--param1", "1", "--param2", "text"}; char* argv[] = {"progname", "--param1", "1", "--param2", "text"};
......
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