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;
} }
......
...@@ -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);
......
...@@ -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