Commit afa98d71 authored by Pavel Vainerman's avatar Pavel Vainerman

make style

parent 1dabf74a
......@@ -45,16 +45,17 @@ int main(int argc, char** argv)
for( DBResult::iterator it = r.begin(); it != r.end(); it++ )
{
cout << "ROW: ";
// DBResult::COL col(*it);
// for( DBResult::COL::iterator cit = col.begin(); cit != col.end(); cit++ )
// cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
// cout << endl;
// DBResult::COL col(*it);
// for( DBResult::COL::iterator cit = col.begin(); cit != col.end(); cit++ )
// cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
// cout << endl;
for( DBResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
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;
}
......
......@@ -230,7 +230,7 @@ DBResult PostgreSQLInterface::makeResult( const pqxx::result& res )
col.push_back("");
else
{
result.setColName(i.num(),i.name());
result.setColName(i.num(), i.name());
col.push_back( i.as<string>() );
}
}
......
......@@ -225,6 +225,7 @@ bool SQLiteInterface::isConnection() const
DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize )
{
DBResult result;
if( !s )
{
if( finalize )
......@@ -253,9 +254,10 @@ DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize )
if( p )
{
const char* cname = (const char*)sqlite3_column_name(s,i);
const char* cname = (const char*)sqlite3_column_name(s, i);
if( cname )
result.setColName(i,cname);
result.setColName(i, cname);
c.emplace_back(p);
}
......
......@@ -39,10 +39,10 @@ int main(int argc, char** argv)
cout << endl;
// for( int i=0; i<col.size(); i++ )
// cerr << "[" << i << "]: " << r.getColName(i) << endl;
// for( int i=0; i<col.size(); i++ )
// cerr << "[" << i << "]: " << r.getColName(i) << endl;
cout << "ID: " << r.as_string(it,"id") << endl;
cout << "ID: " << r.as_string(it, "id") << endl;
cout << "date: " << it.as_string("date") << endl;
}
......
......@@ -76,7 +76,7 @@ namespace uniset
{
long _myout = getOut();
for( auto&& it: outs )
for( auto && it : outs )
it.el->setIn(it.num, _myout);
}
// -------------------------------------------------------------------------
......@@ -95,7 +95,7 @@ namespace uniset
// -------------------------------------------------------------------------
void Element::addInput(size_t num, long value )
{
for( auto&& it : ins )
for( auto && it : ins )
{
if( it.num == num )
{
......
......@@ -153,7 +153,7 @@ void LProcessor::build( const string& lfile )
*/
void LProcessor::getInputs()
{
for( auto&& it : extInputs )
for( auto && it : extInputs )
{
// try
// {
......
......@@ -30,7 +30,7 @@ namespace uniset
{
public:
TA2D( Element::ElementID id, long filterValue=1 );
TA2D( Element::ElementID id, long filterValue = 1 );
virtual ~TA2D();
/*! num игнорируется, т.к. элемент с одним входом */
......
......@@ -36,7 +36,7 @@ namespace uniset
void TAND::setIn( size_t num, long value )
{
// cout << this << ": input " << num << " set " << state << endl;
for( auto&& it : ins )
for( auto && it : ins )
{
if( it.num == num )
{
......@@ -53,7 +53,7 @@ namespace uniset
// проверяем изменился ли выход
// для тригера 'AND' проверка до первого 0
for( auto&& it : ins )
for( auto && it : ins )
{
if( !it.value )
{
......
......@@ -50,7 +50,7 @@ namespace uniset
{
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto&& it : ins )
for( auto && it : ins )
{
if( it.num == num )
{
......@@ -67,7 +67,7 @@ namespace uniset
// проверяем изменился ли выход
// для тригера 'OR' проверка до первой единицы
for( auto&& it : ins )
for( auto && it : ins )
{
if( it.value )
{
......
......@@ -144,7 +144,7 @@ TEST_CASE("Logic processor: elements", "[LogicProcessor][elements]")
SECTION( "TA2D" )
{
TA2D e("1",10);
TA2D e("1", 10);
REQUIRE_FALSE( e.getOut() );
e.setIn(1, 5);
......
......@@ -221,7 +221,7 @@ int main( int argc, char** argv )
{
auto mbtcp = new ModbusTCPMaster();
mbtcp->connect(iaddr, port);
// mbtcp->setForceDisconnect(!persist);
// mbtcp->setForceDisconnect(!persist);
mb = mbtcp;
}
else
......
......@@ -278,7 +278,7 @@ int main( int argc, char** argv )
{
auto mbtcp = new ModbusTCPMaster();
mbtcp->connect(iaddr, port);
// mbtcp->setForceDisconnect(!persist);
// mbtcp->setForceDisconnect(!persist);
mb = mbtcp;
}
else
......@@ -323,6 +323,7 @@ int main( int argc, char** argv )
cout << "(mtr-setup): save: autodetect speed... (addr=" << ModbusRTU::addr2str(slaveaddr) << ")" << endl;
auto mbrtu = dynamic_cast<ModbusRTUMaster*>(mb);
if( mbrtu )
{
mb->setTimeout(50);
......
......@@ -671,6 +671,7 @@ namespace uniset
mbcrit << myname << "(execute_tcp): catch exception: "
<< tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort() << " err: " << ex << endl;
if( tcpBreakIfFailRun )
throw ex;
}
......@@ -680,6 +681,7 @@ namespace uniset
<< tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort()
<< " err: " << e.displayText() << endl;
if( tcpBreakIfFailRun )
throw e;
}
......@@ -689,6 +691,7 @@ namespace uniset
<< tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort()
<< " err: " << e.what() << endl;
if( tcpBreakIfFailRun )
throw e;
}
......@@ -698,6 +701,7 @@ namespace uniset
<< tcpserver->getInetAddress()
<< ":" << tcpserver->getInetPort()
<< endl;
if( tcpBreakIfFailRun )
throw;
}
......@@ -2074,7 +2078,7 @@ namespace uniset
if( !params.empty() )
{
for( const auto& p: params )
for( const auto& p : params )
{
if( p.first == "regs" )
q_regs = uniset::explode_str(p.second, ',');
......@@ -2095,22 +2099,23 @@ namespace uniset
// Проход по списку заданных addr..
if( !q_addr.empty() )
{
for( const auto& a: q_addr )
for( const auto& a : q_addr )
{
ModbusRTU::ModbusAddr mbaddr = ModbusRTU::str2mbAddr(a);
auto i = iomap.find(mbaddr);
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);
}
}
}
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);
}
}
......@@ -2126,7 +2131,7 @@ namespace uniset
if( q_regs.empty() )
{
for( const auto& r: rmap )
for( const auto& r : rmap )
{
Poco::JSON::Object::Ptr reginfo = get_reginfo(r.second);
regs->add(reginfo);
......@@ -2138,6 +2143,7 @@ namespace uniset
{
auto reg = genRegID( ModbusRTU::str2mbData(s), default_mbfunc);
auto r = rmap.find(reg);
if( r != rmap.end() )
{
Poco::JSON::Object::Ptr reginfo = get_reginfo(r->second);
......
......@@ -27,7 +27,7 @@ int main( int argc, const char** argv )
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;
s << "MBTCP" << i;
......@@ -36,7 +36,7 @@ int main( int argc, const char** argv )
ostringstream p;
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 )
{
......
......@@ -763,6 +763,7 @@ namespace uniset
return;
HistoryItList* lst = static_cast<HistoryItList*>(usi->getUserData(udataHistory));
if( !lst )
return;
......@@ -781,7 +782,7 @@ namespace uniset
<< " value=" << value
<< endl;
for( auto&& it1 : (*lst) )
for( auto && it1 : (*lst) )
{
History::iterator it = it1;
......
......@@ -49,7 +49,7 @@ void TestObject::sensorInfo( const SensorMessage* sm )
<< " lost: " << (sm->value - lastValue)
<< endl;
lostMessages += (sm->value - lastValue -1);
lostMessages += (sm->value - lastValue - 1);
}
lastValue = sm->value;
......
......@@ -270,13 +270,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
// Для проверки этого датчик монотонно увеличивается на +1
// сама проверка см. TestObject::sensorInfo()
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]
{
try
{
for( long val=0; val<=max; val++ )
for( long val = 0; val <= max; val++ )
ui->setValue(516, val);
}
catch( std::exception& ex )
......@@ -291,12 +291,13 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
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();
REQUIRE( ret.get() );
DelayTimer dt(2000,0);
DelayTimer dt(2000, 0);
while( !dt.check(obj->isEmptyQueue()) )
msleep(500);
......@@ -306,7 +307,7 @@ TEST_CASE("[SM]: monitonic sensor message", "[sm][monitonic]")
REQUIRE( obj->getLastValue() == max );
// print statistic
// uniset::SimpleInfo_var si = obj->getInfo(0);
// cerr << std::string(si->info) << endl;
// uniset::SimpleInfo_var si = obj->getInfo(0);
// cerr << std::string(si->info) << endl;
}
// -----------------------------------------------------------------------------
......@@ -475,7 +475,7 @@ void UNetExchange::startReceivers()
void UNetExchange::waitSMReady()
{
// 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();
......
......@@ -229,6 +229,7 @@ void UNetReceiver::start()
if( !activated )
{
activated = true;
if( !loop.async_evrun(this, evrunTimeout) )
{
unetcrit << myname << "(start): evrun FAILED! (timeout=" << evrunTimeout << " msec)" << endl;
......
......@@ -442,7 +442,7 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP DIGITAL DATA LIMIT! max="
<< UniSetUDP::MaxDCount << endl;
// raise(SIGTERM);
// raise(SIGTERM);
std::terminate();
return false;
}
......@@ -481,7 +481,7 @@ namespace uniset
<< "(readItem): OVERFLOW! MAX UDP ANALOG DATA LIMIT! max="
<< UniSetUDP::MaxACount << endl;
// raise(SIGTERM);
// raise(SIGTERM);
std::terminate();
return false;
}
......@@ -494,7 +494,7 @@ namespace uniset
{
unetcrit << myname
<< "(readItem): Sensor (" << p.id << ")" << sname << " ALREADY ADDED!! ABORT!" << endl;
// raise(SIGTERM);
// raise(SIGTERM);
std::terminate();
return false;
}
......
......@@ -29,7 +29,7 @@ class UObject_SK:
public uniset::UniSetObject
{
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();
virtual ~UObject_SK();
......@@ -43,54 +43,60 @@ class UObject_SK:
virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept;
inline std::shared_ptr<DebugStream> log() noexcept { return mylog; }
inline std::shared_ptr<uniset::LogAgregator> logAgregator() noexcept { return loga; }
inline std::shared_ptr<DebugStream> log() noexcept
{
return mylog;
}
inline std::shared_ptr<uniset::LogAgregator> logAgregator() noexcept
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ) noexcept;
// "синтаксический сахар"..для логов
#ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif
#ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif
#ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif
#ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif
#ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif
#ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif
#ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif
#ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif
#ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif
#ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif
#ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif
#ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif
#ifndef mylogany
#define mylogany log()->any()
#endif
#ifndef vmonit
#define vmonit( var ) vmon.add( #var, var )
#endif
#ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif
#ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif
#ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif
#ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif
#ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif
#ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif
#ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif
#ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif
#ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif
#ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif
#ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif
#ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif
#ifndef mylogany
#define mylogany log()->any()
#endif
#ifndef vmonit
#define vmonit( var ) vmon.add( #var, var )
#endif
// Вспомогательные функции для удобства логирования
// ------------------------------------------------------------
......@@ -107,16 +113,19 @@ class UObject_SK:
\param id - идентификатор датчика
\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
\param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/
std::string strval( uniset::ObjectId id, bool showLinkName=true ) const;
std::string strval( uniset::ObjectId id, bool showLinkName = true ) const;
/*! Вывод состояния внутренних переменных */
inline std::string dumpVars(){ return vmon.pretty_str(); }
inline std::string dumpVars()
{
return vmon.pretty_str();
}
// ------------------------------------------------------------
std::string help() noexcept;
......@@ -152,23 +161,29 @@ class UObject_SK:
virtual void callback() noexcept override;
virtual void processingMessage( const uniset::VoidMessage* msg ) override;
virtual void sysCommand( const uniset::SystemMessage* sm ){};
virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const uniset::SensorMessage* sm ) override{}
virtual void timerInfo( const uniset::TimerMessage* tm ) override{}
virtual void sysCommand( const uniset::SystemMessage* sm ) {};
virtual void askSensors( UniversalIO::UIOCommand cmd ) {}
virtual void sensorInfo( const uniset::SensorMessage* sm ) override {}
virtual void timerInfo( const uniset::TimerMessage* tm ) override {}
virtual void sigterm( int signo ) override;
virtual bool activateObject() override;
virtual std::string getMonitInfo(){ return ""; } /*!< пользовательская информация выводимая в getInfo() */
virtual std::string getTypeOfMessage( int t ){ return uniset::strTypeOfMessage(t); } /*!< получение названия типа сообщения. Используется в getInfo() */
virtual std::string getMonitInfo()
{
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
virtual std::string getTypeOfMessage( int t )
{
return uniset::strTypeOfMessage(t); /*!< получение названия типа сообщения. Используется в getInfo() */
}
#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 httpRequestLog( const Poco::URI::QueryParameters& p );
#endif
// Выполнение очередного шага программы
virtual void step(){}
virtual void step() {}
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const uniset::SystemMessage* sm );
......@@ -197,9 +212,15 @@ class UObject_SK:
xmlNode* 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 */
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 */
std::atomic_bool activated;
......@@ -250,10 +271,10 @@ class UObject_SK:
}
};
std::unordered_map<const uniset::ObjectId,size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */
std::unordered_map<const uniset::ObjectId, size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */
size_t processingMessageCatchCount = { 0 }; /*!< количество исключений пойманных в processingMessage */
std::unordered_map<long,size_t> msgTypeStat; /*!< количество сообщений по типам */
std::unordered_map<long, size_t> msgTypeStat; /*!< количество сообщений по типам */
std::string ostate = { "" }; /*!< состояние процесса (выводится в getInfo()) */
......
......@@ -247,7 +247,7 @@ namespace uniset
}
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'
......
......@@ -430,6 +430,7 @@ namespace uniset
if( mbrtu )
{
mbrtu->setSpeed(speed);
if( verb )
cout << "(mtr-setup): speed is set to "
<< ComPort::getSpeed(speed) << endl;
......@@ -459,6 +460,7 @@ namespace uniset
if( mbrtu )
{
mbrtu->setParity(get_parity(data));
if( verb )
cout << "(mtr-setup): parity is set to "
<< (data ? ((data == 1) ? "odd" : "even") : "no") << endl;
......
......@@ -32,28 +32,28 @@ using namespace uniset;
// -----------------------------------------------------------------------------
UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла)
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables (public and proteced)
// variables (public and proteced)
// ------------------
active(false),
// ------------------
active(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
end_private(false)
end_private(false)
{
mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception( string(myname+": init failed!!!") );
throw uniset::Exception( string(myname + ": init failed!!!") );
}
// -----------------------------------------------------------------------------
// ( val, confval, default val )
......@@ -61,6 +61,7 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{
if( !s1.empty() )
return s1;
if( !s2.empty() )
return s2;
......@@ -74,41 +75,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
auto conf = uniset_conf();
if( conf->getProp(cnode,prop).empty() )
if( conf->getProp(cnode, prop).empty() )
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 ):
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables
// variables
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ),
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
forceOut(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)),
forceOut(false),
end_private(false)
end_private(false)
{
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();
}
......@@ -124,10 +125,10 @@ end_private(false)
{
ostringstream s;
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(ulog());
......@@ -145,12 +146,14 @@ end_private(false)
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
}
forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false);
forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() )
{
idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId )
{
ostringstream err;
......@@ -158,13 +161,14 @@ end_private(false)
throw uniset::SystemError(err.str());
}
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime>0 )
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime());
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime);
else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10);
}
// Инициализация значений
......@@ -173,16 +177,18 @@ end_private(false)
si.id = uniset::DefaultObjectId;
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("");
if( s_resetTime.empty() )
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);
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout","");
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", "");
if( sm_tout == 0 )
smReadyTimeout = conf->getNCReadyTimeout();
else if( sm_tout < 0 )
......@@ -190,7 +196,7 @@ end_private(false)
else
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 )
......@@ -217,7 +223,7 @@ end_private(false)
// 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;
}
......@@ -269,7 +275,7 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
void UObject_SK::resetMsg()
{
mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages
// reset messages
}
// -----------------------------------------------------------------------------
......@@ -298,11 +304,11 @@ Poco::JSON::Object::Ptr UObject_SK::httpDumpIO()
{
Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata,"in");
Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata, "in");
Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata,"out");
Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata, "out");
......@@ -327,19 +333,23 @@ std::string UObject_SK::dumpIO()
s << endl;
int n = 0;
for( const auto& e: v_in )
for( const auto& e : v_in )
{
s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl;
}
s << endl;
n = 0;
for( const auto& e: v_out )
for( const auto& e : v_out )
{
s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl;
}
......@@ -415,14 +425,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{
case SystemMessage::WatchDog:
myinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() )
{
mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break;
}
case SystemMessage::StartUp:
{
ostate = "StartUp...";
try
{
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
......@@ -472,9 +485,10 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
// переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() );
if( !fname.empty() )
{
mylog->logFile(fname.c_str(),true);
mylog->logFile(fname.c_str(), true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
}
......@@ -529,8 +543,10 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << "statistics: " << endl
<< " processingMessageCatchCount: " << processingMessageCatchCount << 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 << endl;
......@@ -538,14 +554,16 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << endl;
auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t: timers )
for( const auto& t : timers )
{
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 )
<< " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 )
<< endl;
}
inf << endl;
inf << vmon.pretty_str() << endl;
inf << endl;
......@@ -563,49 +581,53 @@ Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& p
Poco::JSON::Object::Ptr json = UniSetObject::httpGet(params);
Poco::JSON::Object::Ptr jdata = json->getObject(myname);
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 )
{
jserv->set("host",logserv_host);
jserv->set("port",logserv_port);
jserv->set("state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" ));
jserv->set("host", logserv_host);
jserv->set("port", logserv_port);
jserv->set("state", ( logserv->isRunning() ? "RUNNIG" : "STOPPED" ));
jserv->set("info", logserv->httpGetShortInfo());
}
jdata->set("io", httpDumpIO());
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("name", getTimerName(t.id));
jt->set("msec", t.tmr.getInterval());
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 jvmon = uniset::json::make_child(jdata,"Variables");
auto jvmon = uniset::json::make_child(jdata, "Variables");
for( const auto& v: vlist )
jvmon->set(v.first,v.second);
for( const auto& v : vlist )
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);
auto jsens = uniset::json::make_child(jstat,"sensors");
for( const auto& s: smStat )
auto jsens = uniset::json::make_child(jstat, "sensors");
for( const auto& s : smStat )
{
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("name", sname);
js->set("count", s.second);
......@@ -622,7 +644,7 @@ Poco::JSON::Object::Ptr UObject_SK::httpHelp( const Poco::URI::QueryParameters&
uniset::json::help::object myhelp(myname, UniSetObject::httpGet(params));
// 'log'
uniset::json::help::item cmd("log","show log level");
uniset::json::help::item cmd("log", "show log level");
myhelp.add(cmd);
return myhelp;
......@@ -633,13 +655,13 @@ Poco::JSON::Object::Ptr UObject_SK::httpRequest( const std::string& req, const P
if( req == "log" )
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 jret = new Poco::JSON::Object();
jret->set("log",Debug::str(mylog->level()));
jret->set("log", Debug::str(mylog->level()));
return jret;
}
// -----------------------------------------------------------------------------
......@@ -689,7 +711,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID,wait_msec) )
if( !ui->waitReady(_testID, wait_msec) )
{
ostringstream err;
err << myname
......@@ -698,10 +720,10 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit << err.str() << endl;
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;
err << myname
......@@ -710,7 +732,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit << err.str() << endl;
std::abort();
// throw uniset::SystemError(err.str());
// throw uniset::SystemError(err.str());
}
}
// ----------------------------------------------------------------------------
......@@ -746,39 +768,42 @@ void UObject_SK::callback() noexcept
{
if( !active )
return;
try
{
// проверка таймеров
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();
}
// обработка сообщений (таймеров и т.п.)
for( unsigned int i=0; i<20; i++ )
for( unsigned int i = 0; i < 20; i++ )
{
auto m = receiveMessage();
if( !m )
break;
processingMessage(m.get());
updateOutputs(forceOut);
// updatePreviousValues();
// updatePreviousValues();
}
// Выполнение шага программы
step();
// "сердцебиение"
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() )
if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
{
try
{
ui->setValue(idHeartBeat,maxHeartBeat);
ui->setValue(idHeartBeat, maxHeartBeat);
ptHeartBeat.reset();
}
catch( const uniset::Exception& ex )
......@@ -818,7 +843,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
ui->setValue(_sid,_val);
ui->setValue(_sid, _val);
}
// -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force )
......@@ -840,7 +865,7 @@ void UObject_SK::initFromSM()
// -----------------------------------------------------------------------------
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 )
......@@ -862,10 +887,12 @@ long UObject_SK::getValue( uniset::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{
PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() )
{
cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300);
if( activated )
break;
}
......@@ -885,7 +912,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{
mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception&ex )
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
......
......@@ -20,7 +20,7 @@ static void init_test()
// -----------------------------------------------------------------------------
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 )
......
......@@ -32,12 +32,12 @@ TEST_CASE("[REST API: conf]", "[restapi][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"}
// ],
// "object":
// {"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}
// }
//
// {"id":"2","iotype":"DI","mbaddr":"0x01","mbfunc":"0x06","mbreg":"0x02","mbtype":"rtu","name":"Input2_S","nbit":"11","priority":"Medium","rs":"4","textname":"Команда 2"}
// ],
// "object":
// {"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>();
REQUIRE(json);
......@@ -155,8 +155,8 @@ TEST_CASE("[REST API: /get]", "[restapi][get]")
{
// QUERY: /get?dummy
// Ожидаемый формат ответа:
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[{"error":"Sensor not found","name":"dummy"}]}
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[{"error":"Sensor not found","name":"dummy"}]}
std::string s = shm->apiRequest("/get?dummy");
Poco::JSON::Parser parser;
......@@ -245,17 +245,17 @@ TEST_CASE("[REST API: /consumers]", "[restapi][consumers]")
// QUERY: /consumers
// Ожидаемый формат ответа:
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[
// {"consumers":[
// {"attempt":10,"id":6000,"lostEvents":0,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ],
// "sensor":{"id":1,"name":"Input1_S"}},
// {"consumers":[
// {"attempt":4,"id":6000,"lostEvents":4,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ],
// "sensor":{"id":10,"name":"AI_AS"}}
// ]}
// {"object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"},
// "sensors":[
// {"consumers":[
// {"attempt":10,"id":6000,"lostEvents":0,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ],
// "sensor":{"id":1,"name":"Input1_S"}},
// {"consumers":[
// {"attempt":4,"id":6000,"lostEvents":4,"name":"TestProc","node":3000,"node_name":"localhost","smCount":0}
// ],
// "sensor":{"id":10,"name":"AI_AS"}}
// ]}
std::string s = shm->apiRequest("/consumers");
......@@ -287,11 +287,11 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]")
// QUERY: /lost
// Ожидаемый формат ответа:
// {"lost consumers":[
// ...
// ],
// "object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}
// }
// {"lost consumers":[
// ...
// ],
// "object":{"id":5003,"isActive":true,"lostMessages":0,"maxSizeOfMessageQueue":1000,"msgCount":0,"name":"SharedMemory","objectType":"IONotifyController"}
// }
// Сперва имитируем зазачика (который "исчезнет").
const ObjectId myID = 6013; // TestProc2
......@@ -300,8 +300,8 @@ TEST_CASE("[REST API: /lost]", "[restapi][lost]")
shm->askSensor(sid, UniversalIO::UIONotify, myID );
// имитируем изменения
for( size_t i=200; i<220; i++ )
shm->setValue(sid,i);
for( size_t i = 200; i < 220; i++ )
shm->setValue(sid, i);
// проверяем список "потерянных"
std::string s = shm->apiRequest("/lost");
......
......@@ -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 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:
......
......@@ -75,7 +75,7 @@ namespace uniset
namespace UHttp
{
// текущая версия API
const std::string UHTTP_API_VERSION="v01";
const std::string UHTTP_API_VERSION = "v01";
/*! интерфейс для объекта выдающего json-данные */
class IHttpRequest
......
......@@ -27,15 +27,15 @@ namespace uniset
{
using namespace UHttp;
// -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
// -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
registry(_registry)
{
{
log = make_shared<DebugStream>();
}
// -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
{
}
// -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
{
if( !registry )
{
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
......@@ -148,27 +148,27 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
}
out.flush();
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
UHttpRequestHandlerFactory::UHttpRequestHandlerFactory(std::shared_ptr<IHttpRequestRegistry>& _registry ):
UHttpRequestHandlerFactory::UHttpRequestHandlerFactory(std::shared_ptr<IHttpRequestRegistry>& _registry ):
registry(_registry)
{
{
}
// -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{
}
// -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{
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;
err << "(IHttpRequest::Request): " << req << " not supported";
throw uniset::SystemError(err.str());
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
// -------------------------------------------------------------------------
#endif
......@@ -25,11 +25,11 @@ using namespace Poco::Net;
namespace uniset
{
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)
{
{
try
{
mylog = std::make_shared<DebugStream>();
......@@ -51,33 +51,33 @@ UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const
}
mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl;
}
// -------------------------------------------------------------------------
UHttpServer::~UHttpServer()
{
}
// -------------------------------------------------------------------------
UHttpServer::~UHttpServer()
{
if( http )
http->stop();
}
// -------------------------------------------------------------------------
void UHttpServer::start()
{
}
// -------------------------------------------------------------------------
void UHttpServer::start()
{
http->start();
}
// -------------------------------------------------------------------------
void UHttpServer::stop()
{
}
// -------------------------------------------------------------------------
void UHttpServer::stop()
{
http->stop();
}
// -------------------------------------------------------------------------
UHttpServer::UHttpServer()
{
}
// -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log()
{
}
// -------------------------------------------------------------------------
UHttpServer::UHttpServer()
{
}
// -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log()
{
return mylog;
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
// -------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API
......@@ -125,6 +125,7 @@ namespace uniset
io.start(sock->getSocket(), ev::READ);
ioTimeout.set(loop);
if( sessTimeout > 0 )
ioTimeout.start(sessTimeout);
}
......
......@@ -50,10 +50,11 @@ namespace uniset
{
try
{
std::future<bool> future = std::async(std::launch::async, [=]()
std::future<bool> future = std::async(std::launch::async, [ = ]()
{
// Сама проверка...
bool result = false;
try
{
UTCPStream t;
......@@ -68,9 +69,11 @@ namespace uniset
});
std::future_status status;
do
{
status = future.wait_for(std::chrono::milliseconds(tout_msec));
if( status == std::future_status::timeout )
return false;
}
......@@ -82,6 +85,7 @@ namespace uniset
{
}
return false;
}
// -----------------------------------------------------------------------------
......@@ -89,7 +93,7 @@ namespace uniset
{
try
{
std::future<bool> future = std::async(std::launch::async, [=]()
std::future<bool> future = std::async(std::launch::async, [ = ]()
{
// Сама проверка...
ostringstream cmd;
......@@ -101,9 +105,11 @@ namespace uniset
});
std::future_status status;
do
{
status = future.wait_for(std::chrono::milliseconds(tout_msec));
if( status == std::future_status::timeout )
return false;
}
......
......@@ -438,7 +438,8 @@ namespace uniset
throw uniset::SystemError(err.str());
}
auto idlist = uniset::explode_str(params[0].first,',');
auto idlist = uniset::explode_str(params[0].first, ',');
if( idlist.empty() )
{
ostringstream err;
......@@ -447,7 +448,8 @@ namespace uniset
}
string props = {""};
for( const auto& p: params )
for( const auto& p : params )
{
if( p.first == "props" )
{
......@@ -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 )
jdata->add(j);
}
......@@ -477,8 +480,8 @@ namespace uniset
{
ostringstream err;
err << name << " not found..";
jdata->set(name,"");
jdata->set("error",err.str());
jdata->set(name, "");
jdata->set("error", err.str());
return jdata;
}
......@@ -488,27 +491,29 @@ namespace uniset
{
ostringstream err;
err << name << " not found confnode..";
jdata->set(name,"");
jdata->set("error",err.str());
jdata->set(name, "");
jdata->set("error", err.str());
return jdata;
}
UniXML::iterator it(xmlnode);
jdata->set("name",it.getProp("name"));
jdata->set("id",it.getProp("id"));
jdata->set("name", it.getProp("name"));
jdata->set("id", it.getProp("id"));
if( !props.empty() )
{
auto lst = uniset::explode_str(props,',');
for( const auto& p: lst )
jdata->set(p,it.getProp(p));
auto lst = uniset::explode_str(props, ',');
for( const auto& p : lst )
jdata->set(p, it.getProp(p));
}
else
{
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;
......@@ -682,6 +687,7 @@ namespace uniset
bool actOK = false;
auto conf = uniset_conf();
for( size_t i = 0; i < conf->getRepeatCount(); i++ )
{
try
......@@ -982,7 +988,7 @@ namespace uniset
else if( query == "conf" )
{
// запрос вида: /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());
reply->stringify(out);
}
......@@ -1018,7 +1024,7 @@ namespace uniset
Poco::JSON::Object jdata;
jdata.set("error", err.str());
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;
jdata.stringify(out);
......
......@@ -38,6 +38,7 @@ namespace uniset
bool CommonEventLoop::runDefaultLoop( size_t waitTimeout_msec )
{
std::lock_guard<std::mutex> lock(thr_mutex);
if( thr )
return true;
......@@ -235,7 +236,7 @@ namespace uniset
{
if( EV_ERROR & revents )
{
// cerr << myname << "(CommonEventLoop::onStop): invalid event" << endl;
// cerr << myname << "(CommonEventLoop::onStop): invalid event" << endl;
return;
}
......
......@@ -98,7 +98,7 @@ IOController::InitSignal IOController::signal_init()
// ------------------------------------------------------------------------------------------
void IOController::activateInit()
{
for( auto&& io: ioList )
for( auto && io : ioList )
{
try
{
......@@ -473,9 +473,10 @@ void IOController::dumpToDB()
{
// lock
// uniset_mutex_lock lock(ioMutex, 100);
for( auto&& usi: ioList )
for( auto && usi : ioList )
{
auto& s = usi.second;
if ( !s->dbignore )
{
SensorMessage sm( std::move(s->makeSensorMessage()) );
......@@ -868,7 +869,7 @@ Poco::JSON::Object::Ptr IOController::httpHelp( const Poco::URI::QueryParameters
{
// '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("shortInfo", "get short information for sensors");
myhelp.add(cmd);
......@@ -1044,7 +1045,7 @@ Poco::JSON::Object::Ptr IOController::request_sensors( const string& req, const
}
jdata->set("count", count);
jdata->set("size",ioCount());
jdata->set("size", ioCount());
return jdata;
}
// -----------------------------------------------------------------------------
......
......@@ -79,6 +79,7 @@ IONotifyController::~IONotifyController()
void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const std::string& consumer )
{
ObjectId consumer_id = uniset_conf()->getObjectID(consumer);
if( consumer_id == DefaultObjectId )
consumer_id = uniset_conf()->getControllerID(consumer);
......@@ -94,7 +95,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// Формируем статистику по каждому датчику..
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;
ObjectId sid;
......@@ -105,12 +106,13 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// общее количество SensorMessage полученное этим заказчиком
size_t smCount = 0;
{ // lock askIOMutex
{
// lock askIOMutex
// выводим информацию по конкретному объекту
uniset_rwmutex_rlock lock(askIOMutex);
for( auto&& a : askIOList )
for( auto && a : askIOList )
{
auto& i = a.second;
......@@ -124,7 +126,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
{
if( c.id == consumer_id )
{
stat.emplace_back(a.first,c);
stat.emplace_back(a.first, c);
smCount += c.smCount;
break;
}
......@@ -136,20 +138,22 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
// выводим информацию по конкретному объекту
uniset_rwmutex_rlock lock(trshMutex);
for( auto&& a: askTMap )
for( auto && a : askTMap )
{
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);
for( const auto& c: t.clst.clst )
for( const auto& c : t.clst.clst )
{
if( c.id == consumer_id )
{
if( t.sid != DefaultObjectId )
stat.emplace_back(t.sid,c);
stat.emplace_back(t.sid, c);
else
stat.emplace_back(a.first,c);
stat.emplace_back(a.first, c);
smCount += c.smCount;
break;
......@@ -175,7 +179,7 @@ void IONotifyController::showStatisticsForConsumer( ostringstream& inf, const st
auto oind = uniset_conf()->oind;
for( const auto& s: stat )
for( const auto& s : stat )
{
inf << " " << "(" << setw(6) << s.sid << ") "
<< setw(35) << ORepHelpers::getShortName(oind->getMapName(s.sid))
......@@ -208,6 +212,7 @@ void IONotifyController::showStatisticsForLostConsumers( ostringstream& inf )
<< endl;
auto oind = uniset_conf()->oind;
for( const auto& l : lostConsumers )
{
inf << " " << "(" << setw(6) << l.first << ") "
......@@ -223,7 +228,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf )
auto oind = uniset_conf()->oind;
for( auto&& a : askIOList )
for( auto && a : askIOList )
{
auto& i = a.second;
......@@ -234,6 +239,7 @@ void IONotifyController::showStatisticsForConsusmers( ostringstream& inf )
continue;
inf << "(" << setw(6) << a.first << ")[" << oind->getMapName(a.first) << "]" << endl;
for( const auto& c : i.clst )
{
inf << " " << "(" << setw(6) << c.id << ")"
......@@ -255,7 +261,7 @@ void IONotifyController::showStatisticsForConsumersWithLostEvent( ostringstream&
auto oind = uniset_conf()->oind;
bool empty = true;
for( auto&& a : askIOList )
for( auto && a : askIOList )
{
auto& i = a.second;
......@@ -316,6 +322,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
auto oind = conf->oind;
ObjectId sid = conf->getSensorID(name);
if( sid == DefaultObjectId )
{
inf << "..not found ID for sensor '" << name << "'" << endl;
......@@ -327,6 +334,7 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
{
uniset_rwmutex_rlock lock(askIOMutex);
auto s = askIOList.find(sid);
if( s == askIOList.end() )
{
inf << "..not found consumers for sensor '" << name << "'" << endl;
......@@ -341,7 +349,8 @@ void IONotifyController::showStatisticsForSensor( ostringstream& inf, const stri
<< "--------------------------------------------------------------------" << endl;
uniset_rwmutex_rlock lock2(clist->mut);
for( const auto& c: clist->clst )
for( const auto& c : clist->clst )
{
inf << " (" << setw(6) << c.id << ")"
<< setw(35) << ORepHelpers::getShortName(oind->getMapName(c.id))
......@@ -391,7 +400,8 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
}
else if( !param.empty() )
{
auto query = uniset::explode_str(param,':');
auto query = uniset::explode_str(param, ':');
if( query.empty() || query.size() == 1 )
showStatisticsForConsumer(inf, param);
else if( query.size() > 1 )
......@@ -524,11 +534,12 @@ void IONotifyController::askSensor(const uniset::ObjectId sid,
if( cmd == UniversalIO::UIONotify || (cmd == UIONotifyFirstNotNull && usi->value) )
{
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst )
{
uniset::uniset_rwmutex_rlock lock(usi->val_lock);
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,
// т.к. мы делали move
// то теперь надо достучаться до списка..
auto i = askLst.find(sid);
if( i != askLst.end() )
{
try
......@@ -633,10 +645,11 @@ void IONotifyController::ask( AskMap& askLst, const uniset::ObjectId sid,
if( askIterator != askLst.end() )
{
auto s = myiofind(sid);
if( s != myioEnd() )
s->second->setUserData(udataConsumerList,&(askIterator->second));
s->second->setUserData(udataConsumerList, &(askIterator->second));
else
s->second->setUserData(udataConsumerList,nullptr);
s->second->setUserData(udataConsumerList, nullptr);
}
}
// ------------------------------------------------------------------------------------------
......@@ -677,6 +690,7 @@ long IONotifyController::localSetValue( std::shared_ptr<IOController::USensorInf
catch(...) {}
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst )
send(*lst, sm);
}
......@@ -943,6 +957,7 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum
SensorMessage sm(std::move(li->second->makeSensorMessage()));
sm.consumer = ci.id;
sm.tid = tid;
// Проверка нижнего предела
if( val <= lowLimit )
sm.threshold = false;
......@@ -953,11 +968,12 @@ void IONotifyController::askThreshold(uniset::ObjectId sid, const uniset::Consum
if( it != askTMap.end() )
{
uniset_rwmutex_rlock l(it->second.mut);
for( auto i = it->second.list.begin(); i != it->second.list.end(); ++i )
{
if( i->id == tid )
{
send(i->clst,sm,&ci);
send(i->clst, sm, &ci);
break;
}
}
......@@ -1063,6 +1079,7 @@ void IONotifyController::checkThreshold( std::shared_ptr<IOController::USensorIn
uniset_rwmutex_rlock lock(trshMutex);
ThresholdsListInfo* ti = static_cast<ThresholdsListInfo*>(usi->getUserData(udataThresholdList));
if( !ti || ti->list.empty() )
return;
......@@ -1316,6 +1333,7 @@ void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& u
catch(...) {}
ConsumerListInfo* lst = static_cast<ConsumerListInfo*>(usi->getUserData(udataConsumerList));
if( lst )
send(*lst, sm);
}
......
......@@ -153,6 +153,7 @@ NCRestorer::SInfo& NCRestorer::SInfo::operator=( const IOController_i::SensorIOI
{
uniset_rwmutex_wrlock l(this->userdata_lock);
for( size_t i = 0; i < IOController::USensorInfo::MaxUserData; i++ )
this->userdata[i] = nullptr;
}
......
......@@ -122,6 +122,7 @@ namespace uniset
int DBResult::getColIndex( const std::string& name )
{
auto i = colname.find(name);
if( i == colname.end() )
throw std::runtime_error("(DBInterface): Unknown field ='" + name + "'");
......@@ -130,7 +131,7 @@ namespace uniset
// ----------------------------------------------------------------------------
std::string DBResult::getColName( int index )
{
for( auto&& c: colname )
for( auto && c : colname )
{
if( c.second == index )
return c.first;
......@@ -155,13 +156,13 @@ namespace uniset
}
// ----------------------------------------------------------------------------
DBRowIterator::DBRowIterator( DBResult& _dbres, const DBResult::ROW::iterator& _it ):
dbres(_dbres),it(_it)
dbres(_dbres), it(_it)
{
}
DBRowIterator::DBRowIterator( const DBRowIterator& i ):
dbres(i.dbres),it(i.it)
dbres(i.dbres), it(i.it)
{
}
......
......@@ -723,13 +723,16 @@ namespace uniset
{
// проверяем доступность endPoint попыткой создать соединение
auto ep = omni::giopEndpoint::str2Endpoint( endPoint.c_str() );
if( !ep )
return false;
bool ret = false;
try
{
ret = ep->Bind();
if( ret )
ep->Shutdown();
}
......@@ -1240,6 +1243,7 @@ namespace uniset
ObjectId Configuration::getAnyID( const string& name ) const noexcept
{
ObjectId id = DefaultObjectId;
if( uniset::is_digit(name) )
return uni_atoi(name);
......
......@@ -74,13 +74,13 @@ void SMonitor::sysCommand( const SystemMessage* sm )
catch( const uniset::Exception& ex )
{
cerr << myname << ":(askSensor): " << ex << endl;
// raise(SIGTERM);
// raise(SIGTERM);
std::terminate();
}
catch(...)
{
cerr << myname << ": НЕ СМОГ ЗАКАЗТЬ датчики " << endl;
// raise(SIGTERM);
// raise(SIGTERM);
std::terminate();
}
}
......
......@@ -213,16 +213,18 @@ void UniXML::setProp(xmlNode* node, const string& name, const string& text )
UniXMLPropList UniXML::getPropList( xmlNode* node )
{
UniXMLPropList lst;
if( !node )
return lst;
xmlAttr* attribute = node->properties;
while( attribute )
{
xmlChar* value = ::xmlNodeListGetString(node->doc, attribute->children, 1);
const std::string nm( (const char*)attribute->name );
const std::string val( (const char*)value );
lst.push_back( {nm,val} );
lst.push_back( {nm, val} );
xmlFree(value);
attribute = attribute->next;
}
......@@ -651,7 +653,7 @@ UniXML_iterator& UniXML_iterator::operator++() noexcept
UniXML_iterator UniXML_iterator::operator++(int) noexcept
{
UniXML_iterator temp(*this);
(*this) = (*this)+1;
(*this) = (*this) + 1;
return temp;
}
// -------------------------------------------------------------------------
......@@ -683,7 +685,7 @@ UniXML_iterator& UniXML_iterator::operator+(int step) noexcept
UniXML_iterator UniXML_iterator::operator--(int) noexcept
{
UniXML_iterator temp(*this);
(*this) = (*this)-1;
(*this) = (*this) - 1;
return temp;
}
......
......@@ -179,13 +179,13 @@ TEST_CASE("UniXML::iterator::getPropList", "[unixml][iterator-proplist][basic]"
std::ostringstream n;
std::ostringstream v;
for( size_t i=0; i<5; i++ )
for( size_t i = 0; i < 5; i++ )
{
n.str("");
n << "prop" << (i+1);
n << "prop" << (i + 1);
v.str("");
v << "val" << (i+1);
v << "val" << (i + 1);
REQUIRE( lst[i].first == n.str() );
REQUIRE( lst[i].second == v.str() );
......
......@@ -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 );
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,false) == 10000.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, 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,false) == 0.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(-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, true) == 100.0 );
REQUIRE( fcalibrate(-10.0, 0.1, 1.0, 100.0, 1000.0, false) == -10000.0 );
}
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: lcalibrate", "[utypes][lcalibrate]" )
{
// 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,false) == 500 );
REQUIRE( lcalibrate(5, 1, 10, 100, 1000, true) == 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,false) == 0 );
REQUIRE( lcalibrate(0, 1, 10, 100, 1000, true) == 100 );
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,false) == 10000 );
REQUIRE( lcalibrate(100, 1, 10, 100, 1000, true) == 1000 );
REQUIRE( lcalibrate(100, 1, 10, 100, 1000, false) == 10000 );
}
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: setinregion", "[utypes][setinregion]" )
{
// long setinregion(long raw, long rawMin, long rawMax);
REQUIRE( setinregion(5,1,10) == 5 );
REQUIRE( setinregion(1,1,10) == 1 );
REQUIRE( setinregion(10,1,10) == 10 );
REQUIRE( setinregion(0,1,10) == 1 );
REQUIRE( setinregion(100,1,10) == 10 );
REQUIRE( setinregion(5, 1, 10) == 5 );
REQUIRE( setinregion(1, 1, 10) == 1 );
REQUIRE( setinregion(10, 1, 10) == 10 );
REQUIRE( setinregion(0, 1, 10) == 1 );
REQUIRE( setinregion(100, 1, 10) == 10 );
}
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: setoutregion", "[utypes][setoutregion]" )
{
// long setoutregion(long raw, long calMin, long calMax);
REQUIRE( setoutregion(5,1,10) == 1 );
REQUIRE( setoutregion(1,1,10) == 1 );
REQUIRE( setoutregion(10,1,10) == 10 );
REQUIRE( setoutregion(100,1,10) == 100 );
REQUIRE( setoutregion(0,1,10) == 0 );
REQUIRE( setoutregion(5, 1, 10) == 1 );
REQUIRE( setoutregion(1, 1, 10) == 1 );
REQUIRE( setoutregion(10, 1, 10) == 10 );
REQUIRE( setoutregion(100, 1, 10) == 100 );
REQUIRE( setoutregion(0, 1, 10) == 0 );
}
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: file_exist", "[utypes][file_exist]" )
......@@ -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;
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);
UniXML::iterator it(xnode);
......@@ -278,9 +278,9 @@ TEST_CASE("UniSetTypes: findArgParam", "[utypes][findArgParam]" )
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" )
{
// getArgParam( const std::string& name,
// int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept
// getArgParam( const std::string& name,
// int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept
int argc = 5;
char* argv[] = {"progname", "--param1", "val", "--param2", "val2"};
......@@ -292,9 +292,9 @@ TEST_CASE("UniSetTypes: getArgParam", "[utypes][getArgParam]" )
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: getArgInt", "[utypes][getArgInt]" )
{
// inline int getArgInt( const std::string& name,
// int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept
// inline int getArgInt( const std::string& name,
// int _argc, const char* const* _argv,
// const std::string& defval = "" ) noexcept
int argc = 5;
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