Commit afa98d71 authored by Pavel Vainerman's avatar Pavel Vainerman

make style

parent 1dabf74a
......@@ -177,7 +177,7 @@ int main( int argc, char** argv )
case 'g':
ignoreErrors = true;
break;
break;
case 'e':
{
......
......@@ -183,11 +183,11 @@ int main( int argc, char** argv )
dlog4->addLevel(Debug::ANY);
ls.async_run( addr, port );
if( verb )
ls.setSessionLog(Debug::ANY);
if( !ls.isRunning() )
{
cerr << "LOG SERVER NOT RUNNING!!" << endl;
......
......@@ -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);
}
......
......@@ -38,11 +38,11 @@ int main(int argc, char** argv)
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
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;
}
......
......@@ -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);
......
......@@ -160,7 +160,7 @@ int main( int argc, char** argv )
case 'g':
ignoreErrors = true;
break;
break;
case 'n':
{
......@@ -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;
}
......
......@@ -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;
......@@ -557,7 +559,7 @@ namespace uniset
}
// ------------------------------------------------------------------------------------------
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);
......
......@@ -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");
......
......@@ -112,10 +112,10 @@ namespace uniset
// ----------------------------------------------------------------------------------
class DBRowIterator:
public std::iterator<std::bidirectional_iterator_tag,
DBResult::ROW::value_type,
DBResult::ROW::difference_type,
DBResult::ROW::pointer,
DBResult::ROW::reference>
DBResult::ROW::value_type,
DBResult::ROW::difference_type,
DBResult::ROW::pointer,
DBResult::ROW::reference>
{
public:
......
......@@ -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,148 +27,148 @@ namespace uniset
{
using namespace UHttp;
// -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
registry(_registry)
{
log = make_shared<DebugStream>();
}
// -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
{
if( !registry )
// -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
registry(_registry)
{
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
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;
log = make_shared<DebugStream>();
}
// В этой версии API поддерживается только GET
if( req.getMethod() != "GET" )
// -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
{
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;
}
Poco::URI uri(req.getURI());
if( !registry )
{
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
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;
}
if( log->is_info() )
log->info() << req.getHost() << ": query: " << uri.getQuery() << endl;
// В этой версии API поддерживается только GET
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;
uri.getPathSegments(seg);
Poco::URI uri(req.getURI());
// example: http://host:port/api/version/ObjectName
if( seg.size() < 3
|| 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();
if( log->is_info() )
log->info() << req.getHost() << ": query: " << uri.getQuery() << endl;
resp.setStatus(HTTPResponse::HTTP_OK);
resp.setContentType("text/json");
std::ostream& out = resp.send();
std::vector<std::string> seg;
uri.getPathSegments(seg);
try
{
if( objectName == "help" )
{
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" )
// example: http://host:port/api/version/ObjectName
if( seg.size() < 3
|| seg[0] != "api"
|| seg[1] != UHTTP_API_VERSION
|| seg[2].empty() )
{
auto json = registry->httpGetObjectsList(qp);
json->stringify(out);
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;
}
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..
const std::string objectName(seg[2]);
auto qp = uri.getQueryParameters();
resp.setStatus(HTTPResponse::HTTP_OK);
resp.setContentType("text/json");
std::ostream& out = resp.send();
try
{
auto json = registry->httpRequestByName(objectName, seg[3], qp);
json->stringify(out);
if( objectName == "help" )
{
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);
json->stringify(out);
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);
}
}
// 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 ):
registry(_registry)
{
UHttpRequestHandlerFactory::UHttpRequestHandlerFactory(std::shared_ptr<IHttpRequestRegistry>& _registry ):
registry(_registry)
{
}
// -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{
return new UHttpRequestHandler(registry);
}
// -------------------------------------------------------------------------
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());
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{
return new UHttpRequestHandler(registry);
}
// -------------------------------------------------------------------------
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,59 +25,59 @@ using namespace Poco::Net;
namespace uniset
{
using namespace UHttp;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host, _port)
{
try
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host, _port)
{
mylog = std::make_shared<DebugStream>();
try
{
mylog = std::make_shared<DebugStream>();
/*! \FIXME: доделать конфигурирование параметров */
HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1);
/*! \FIXME: доделать конфигурирование параметров */
HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1);
reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier);
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;
err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what();
throw uniset::SystemError(err.str());
if( http )
http->stop();
}
mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl;
}
// -------------------------------------------------------------------------
UHttpServer::~UHttpServer()
{
if( http )
// -------------------------------------------------------------------------
void UHttpServer::start()
{
http->start();
}
// -------------------------------------------------------------------------
void UHttpServer::stop()
{
http->stop();
}
// -------------------------------------------------------------------------
void UHttpServer::start()
{
http->start();
}
// -------------------------------------------------------------------------
void UHttpServer::stop()
{
http->stop();
}
// -------------------------------------------------------------------------
UHttpServer::UHttpServer()
{
}
// -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log()
{
return mylog;
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
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