Commit 1d66bfef authored by Pavel Vainerman's avatar Pavel Vainerman Committed by Pavel Vainerman

[conf]: check directory exists

parent 603b7219
...@@ -323,6 +323,7 @@ namespace uniset ...@@ -323,6 +323,7 @@ namespace uniset
// Всякие helper-ы // Всякие helper-ы
bool file_exist( const std::string& filename ); bool file_exist( const std::string& filename );
bool directory_exist( const std::string& path );
// Проверка xml-узла на соответствие <...f_prop="f_val">, // Проверка xml-узла на соответствие <...f_prop="f_val">,
// если не задано f_val, то проверяется, что просто f_prop!="" // если не задано f_val, то проверяется, что просто f_prop!=""
......
...@@ -611,7 +611,7 @@ namespace uniset ...@@ -611,7 +611,7 @@ namespace uniset
{ {
repeatCount = it.getPIntProp("name", 1); repeatCount = it.getPIntProp("name", 1);
} }
else if( name == "ImagesPath" ) else if( name == "ImagesPath" ) // DEPRECATED
{ {
imagesDir = dataDir + it.getProp("name") + "/"; // ???????? imagesDir = dataDir + it.getProp("name") + "/"; // ????????
} }
...@@ -633,6 +633,13 @@ namespace uniset ...@@ -633,6 +633,13 @@ namespace uniset
if( dataDir.empty() ) if( dataDir.empty() )
dataDir = getRootDir(); dataDir = getRootDir();
if( !directory_exist(dataDir) )
{
ostringstream err;
err << "Configuration: DataDir=" << dataDir << " NOT EXISTS";
throw uniset::SystemError(err.str());
}
} }
else if( name == "BinDir" ) else if( name == "BinDir" )
{ {
...@@ -640,6 +647,13 @@ namespace uniset ...@@ -640,6 +647,13 @@ namespace uniset
if( binDir.empty() ) if( binDir.empty() )
binDir = getRootDir(); binDir = getRootDir();
if( !directory_exist(binDir) )
{
ostringstream err;
err << "Configuration: BinDir=" << binDir << " NOT EXISTS";
throw uniset::SystemError(err.str());
}
} }
else if( name == "LogDir" ) else if( name == "LogDir" )
{ {
...@@ -647,6 +661,13 @@ namespace uniset ...@@ -647,6 +661,13 @@ namespace uniset
if( logDir.empty() ) if( logDir.empty() )
logDir = getRootDir(); logDir = getRootDir();
if( !directory_exist(logDir) )
{
ostringstream err;
err << "Configuration: LogDir=" << logDir << " NOT EXISTS";
throw uniset::SystemError(err.str());
}
} }
else if( name == "LockDir" ) else if( name == "LockDir" )
{ {
...@@ -654,6 +675,13 @@ namespace uniset ...@@ -654,6 +675,13 @@ namespace uniset
if( lockDir.empty() ) if( lockDir.empty() )
lockDir = getRootDir(); lockDir = getRootDir();
if( !directory_exist(lockDir) )
{
ostringstream err;
err << "Configuration: LockDir=" << lockDir << " NOT EXISTS";
throw uniset::SystemError(err.str());
}
} }
else if( name == "ConfDir" ) else if( name == "ConfDir" )
{ {
...@@ -661,6 +689,13 @@ namespace uniset ...@@ -661,6 +689,13 @@ namespace uniset
if( confDir.empty() ) if( confDir.empty() )
confDir = getRootDir(); confDir = getRootDir();
if( !directory_exist(confDir) )
{
ostringstream err;
err << "Configuration: ConfDir=" << confDir << " NOT EXISTS";
throw uniset::SystemError(err.str());
}
} }
} }
......
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
#include <iomanip> #include <iomanip>
#include <sstream> #include <sstream>
#include <fstream> #include <fstream>
#include <Poco/File.h>
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "Configuration.h" #include "Configuration.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -30,142 +31,142 @@ using namespace uniset; ...@@ -30,142 +31,142 @@ using namespace uniset;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
float uniset::fcalibrate( float raw, float rawMin, float rawMax, float uniset::fcalibrate( float raw, float rawMin, float rawMax,
float calMin, float calMax, bool limit ) float calMin, float calMax, bool limit )
{ {
if( rawMax == rawMin ) return 0; // деление на 0!!! if( rawMax == rawMin ) return 0; // деление на 0!!!
float ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin; float ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin;
if( !limit ) if( !limit )
return ret; return ret;
// Переворачиваем calMin и calMax для проверки, если calMin > calMax // Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) if (calMin < calMax)
{ {
if( ret < calMin ) if( ret < calMin )
return calMin; return calMin;
if( ret > calMax ) if( ret > calMax )
return calMax; return calMax;
} }
else else
{ {
if( ret > calMin ) if( ret > calMin )
return calMin; return calMin;
if( ret < calMax ) if( ret < calMax )
return calMax; return calMax;
} }
return ret; return ret;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
double uniset::dcalibrate( double raw, double rawMin, double rawMax, double uniset::dcalibrate( double raw, double rawMin, double rawMax,
double calMin, double calMax, bool limit ) double calMin, double calMax, bool limit )
{ {
if( rawMax == rawMin ) return 0; // деление на 0!!! if( rawMax == rawMin ) return 0; // деление на 0!!!
double ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin; double ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin;
if( !limit ) if( !limit )
return ret; return ret;
// Переворачиваем calMin и calMax для проверки, если calMin > calMax // Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) if (calMin < calMax)
{ {
if( ret < calMin ) if( ret < calMin )
return calMin; return calMin;
if( ret > calMax ) if( ret > calMax )
return calMax; return calMax;
} }
else else
{ {
if( ret > calMin ) if( ret > calMin )
return calMin; return calMin;
if( ret < calMax ) if( ret < calMax )
return calMax; return calMax;
} }
return ret; return ret;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Пересчитываем из исходных пределов в заданные // Пересчитываем из исходных пределов в заданные
long uniset::lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit ) long uniset::lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit )
{ {
if( rawMax == rawMin ) return 0; // деление на 0!!! if( rawMax == rawMin ) return 0; // деление на 0!!!
long ret = lroundf( (float)(raw - rawMin) * (float)(calMax - calMin) / long ret = lroundf( (float)(raw - rawMin) * (float)(calMax - calMin) /
(float)( rawMax - rawMin ) + calMin ); (float)( rawMax - rawMin ) + calMin );
if( !limit ) if( !limit )
return ret; return ret;
return setinregion(ret, calMin, calMax); return setinregion(ret, calMin, calMax);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Приводим указанное значение в заданные пределы // Приводим указанное значение в заданные пределы
long uniset::setinregion(long ret, long calMin, long calMax) long uniset::setinregion(long ret, long calMin, long calMax)
{ {
// Переворачиваем calMin и calMax для проверки, если calMin > calMax // Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) if (calMin < calMax)
{ {
if( ret < calMin ) if( ret < calMin )
return calMin; return calMin;
if( ret > calMax ) if( ret > calMax )
return calMax; return calMax;
} }
else else
{ {
if( ret > calMin ) if( ret > calMin )
return calMin; return calMin;
if( ret < calMax ) if( ret < calMax )
return calMax; return calMax;
} }
return ret; return ret;
} }
// Выводим указанное значение из заданных пределов (на границы) // Выводим указанное значение из заданных пределов (на границы)
long uniset::setoutregion(long ret, long calMin, long calMax) long uniset::setoutregion(long ret, long calMin, long calMax)
{ {
if ((ret > calMin) && (ret < calMax)) if ((ret > calMin) && (ret < calMax))
{ {
if ((ret * 10) >= ((calMax + calMin) * 5)) if ((ret * 10) >= ((calMax + calMin) * 5))
ret = calMax; ret = calMax;
else else
ret = calMin; ret = calMin;
} }
return ret; return ret;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
uniset::IDList::IDList( const std::vector<string>& svec ): // -V730 uniset::IDList::IDList( const std::vector<string>& svec ): // -V730
uniset::IDList::IDList() uniset::IDList::IDList()
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
for( const auto& s : svec ) for( const auto& s : svec )
{ {
ObjectId id; ObjectId id;
if( is_digit(s) ) if( is_digit(s) )
id = uni_atoi(s); id = uni_atoi(s);
else else
id = conf->getSensorID(s); id = conf->getSensorID(s);
if( id != DefaultObjectId ) if( id != DefaultObjectId )
add(id); add(id);
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
uniset::IDList::IDList(): uniset::IDList::IDList():
node( (uniset::uniset_conf() ? uniset::uniset_conf()->getLocalNode() : DefaultObjectId) ) node( (uniset::uniset_conf() ? uniset::uniset_conf()->getLocalNode() : DefaultObjectId) )
{ {
} }
...@@ -176,555 +177,567 @@ uniset::IDList::~IDList() ...@@ -176,555 +177,567 @@ uniset::IDList::~IDList()
void uniset::IDList::add( ObjectId id ) void uniset::IDList::add( ObjectId id )
{ {
for( auto it = lst.begin(); it != lst.end(); ++it ) for( auto it = lst.begin(); it != lst.end(); ++it )
{ {
if( (*it) == id ) if( (*it) == id )
return; return;
} }
lst.push_back(id); lst.push_back(id);
} }
void uniset::IDList::del( ObjectId id ) void uniset::IDList::del( ObjectId id )
{ {
for( auto it = lst.begin(); it != lst.end(); ++it ) for( auto it = lst.begin(); it != lst.end(); ++it )
{ {
if( (*it) == id ) if( (*it) == id )
{ {
lst.erase(it); lst.erase(it);
return; return;
} }
} }
} }
std::list<uniset::ObjectId> uniset::IDList::getList() const noexcept std::list<uniset::ObjectId> uniset::IDList::getList() const noexcept
{ {
return lst; return lst;
} }
uniset::ObjectId uniset::IDList::getFirst() const noexcept uniset::ObjectId uniset::IDList::getFirst() const noexcept
{ {
if( lst.empty() ) if( lst.empty() )
return uniset::DefaultObjectId; return uniset::DefaultObjectId;
return (*lst.begin()); return (*lst.begin());
} }
// за освобождение выделенной памяти // за освобождение выделенной памяти
// отвечает вызывающий! // отвечает вызывающий!
IDSeq* uniset::IDList::getIDSeq() const IDSeq* uniset::IDList::getIDSeq() const
{ {
IDSeq* seq = new IDSeq(); IDSeq* seq = new IDSeq();
seq->length(lst.size()); seq->length(lst.size());
int i = 0; int i = 0;
for( auto it = lst.begin(); it != lst.end(); ++it, i++ ) for( auto it = lst.begin(); it != lst.end(); ++it, i++ )
(*seq)[i] = (*it); (*seq)[i] = (*it);
return seq; return seq;
}
// -------------------------------------------------------------------------
bool uniset::directory_exist( const std::string& path )
{
try
{
Poco::File f(path);
return f.isDirectory() && f.exists();
}
catch( ... ) {}
return false;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool uniset::file_exist( const std::string& filename ) bool uniset::file_exist( const std::string& filename )
{ {
std::ifstream file; std::ifstream file;
#ifdef HAVE_IOS_NOCREATE #ifdef HAVE_IOS_NOCREATE
file.open( filename.c_str(), std::ios::in | std::ios::nocreate ); file.open( filename.c_str(), std::ios::in | std::ios::nocreate );
#else #else
file.open( filename.c_str(), std::ios::in ); file.open( filename.c_str(), std::ios::in );
#endif #endif
bool result = false; bool result = false;
if( file.is_open() ) if( file.is_open() )
result = true; result = true;
file.close(); file.close();
return result; return result;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
uniset::IDList uniset::explode( const std::string& str, char sep ) uniset::IDList uniset::explode( const std::string& str, char sep )
{ {
uniset::IDList l( explode_str(str, sep) ); uniset::IDList l( explode_str(str, sep) );
return l; return l;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::vector<std::string> uniset::explode_str( const std::string& str, char sep ) std::vector<std::string> uniset::explode_str( const std::string& str, char sep )
{ {
std::vector<std::string> v; std::vector<std::string> v;
string::size_type prev = 0; string::size_type prev = 0;
string::size_type pos = 0; string::size_type pos = 0;
string::size_type sz = str.size(); string::size_type sz = str.size();
do do
{ {
if( prev >= sz ) if( prev >= sz )
break; break;
pos = str.find(sep, prev); pos = str.find(sep, prev);
if( pos == string::npos ) if( pos == string::npos )
{ {
string s(str.substr(prev, sz - prev)); string s(str.substr(prev, sz - prev));
if( !s.empty() ) if( !s.empty() )
v.emplace_back( std::move(s) ); v.emplace_back( std::move(s) );
break; break;
} }
if( pos == 0 ) if( pos == 0 )
{ {
prev = 1; prev = 1;
continue; continue;
} }
string s(str.substr(prev, pos - prev)); string s(str.substr(prev, pos - prev));
if( !s.empty() ) if( !s.empty() )
{ {
v.emplace_back(std::move(s)); v.emplace_back(std::move(s));
prev = pos + 1; prev = pos + 1;
} }
} }
while( pos != string::npos ); while( pos != string::npos );
return v; return v;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool uniset::is_digit( const std::string& s ) noexcept bool uniset::is_digit( const std::string& s ) noexcept
{ {
if( s.empty() ) if( s.empty() )
return false; return false;
for( const auto& c : s ) for( const auto& c : s )
{ {
if( !isdigit(c) ) if( !isdigit(c) )
return false; return false;
} }
return true; return true;
//return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false; //return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
std::list<uniset::ParamSInfo> uniset::getSInfoList( const string& str, std::shared_ptr<Configuration> conf ) std::list<uniset::ParamSInfo> uniset::getSInfoList( const string& str, std::shared_ptr<Configuration> conf )
{ {
std::list<uniset::ParamSInfo> res; std::list<uniset::ParamSInfo> res;
auto lst = uniset::explode_str(str, ','); auto lst = uniset::explode_str(str, ',');
for( const auto& it : lst ) for( const auto& it : lst )
{ {
uniset::ParamSInfo item; uniset::ParamSInfo item;
auto p = uniset::explode_str(it, '='); auto p = uniset::explode_str(it, '=');
std::string s = ""; std::string s = "";
if( p.size() == 1 ) if( p.size() == 1 )
{ {
s = *(p.begin()); s = *(p.begin());
item.val = 0; item.val = 0;
} }
else if( p.size() == 2 ) else if( p.size() == 2 )
{ {
s = *(p.begin()); s = *(p.begin());
item.val = uni_atoi(*(++p.begin())); item.val = uni_atoi(*(++p.begin()));
} }
else else
{ {
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl; cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue; continue;
} }
item.fname = s; item.fname = s;
auto t = uniset::explode_str(s, '@'); auto t = uniset::explode_str(s, '@');
if( t.size() == 1 ) if( t.size() == 1 )
{ {
std::string s_id = *(t.begin()); std::string s_id = *(t.begin());
if( is_digit(s_id) || !conf ) if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id); item.si.id = uni_atoi(s_id);
else else
item.si.id = conf->getSensorID(s_id); item.si.id = conf->getSensorID(s_id);
item.si.node = DefaultObjectId; item.si.node = DefaultObjectId;
} }
else if( t.size() == 2 ) else if( t.size() == 2 )
{ {
std::string s_id = *(t.begin()); std::string s_id = *(t.begin());
std::string s_node = *(++t.begin()); std::string s_node = *(++t.begin());
if( is_digit(s_id) || !conf ) if( is_digit(s_id) || !conf )
item.si.id = uni_atoi(s_id); item.si.id = uni_atoi(s_id);
else else
item.si.id = conf->getSensorID(s_id); item.si.id = conf->getSensorID(s_id);
if( is_digit(s_node) || !conf ) if( is_digit(s_node) || !conf )
item.si.node = uni_atoi(s_node); item.si.node = uni_atoi(s_node);
else else
item.si.node = conf->getNodeID(s_node); item.si.node = conf->getNodeID(s_node);
} }
else else
{ {
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl; cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue; continue;
} }
res.emplace_back( std::move(item) ); res.emplace_back( std::move(item) );
} }
return res; return res;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
std::list<uniset::ConsumerInfo> uniset::getObjectsList( const string& str, std::shared_ptr<Configuration> conf ) std::list<uniset::ConsumerInfo> uniset::getObjectsList( const string& str, std::shared_ptr<Configuration> conf )
{ {
if( conf == nullptr ) if( conf == nullptr )
conf = uniset_conf(); conf = uniset_conf();
std::list<uniset::ConsumerInfo> res; std::list<uniset::ConsumerInfo> res;
auto lst = uniset::explode_str(str, ','); auto lst = uniset::explode_str(str, ',');
for( const auto& it : lst ) for( const auto& it : lst )
{ {
uniset::ConsumerInfo item; uniset::ConsumerInfo item;
auto t = uniset::explode_str(it, '@'); auto t = uniset::explode_str(it, '@');
if( t.size() == 1 ) if( t.size() == 1 )
{ {
std::string s_id(*(t.begin())); std::string s_id(*(t.begin()));
if( is_digit(s_id) ) if( is_digit(s_id) )
item.id = uni_atoi(s_id); item.id = uni_atoi(s_id);
else else
{ {
item.id = conf->getObjectID(s_id); item.id = conf->getObjectID(s_id);
if( item.id == DefaultObjectId ) if( item.id == DefaultObjectId )
item.id = conf->getControllerID(s_id); item.id = conf->getControllerID(s_id);
if( item.id == DefaultObjectId ) if( item.id == DefaultObjectId )
item.id = conf->getServiceID(s_id); item.id = conf->getServiceID(s_id);
} }
item.node = DefaultObjectId; item.node = DefaultObjectId;
} }
else if( t.size() == 2 ) else if( t.size() == 2 )
{ {
std::string s_id = *(t.begin()); std::string s_id = *(t.begin());
std::string s_node = *(++t.begin()); std::string s_node = *(++t.begin());
if( is_digit(s_id) ) if( is_digit(s_id) )
item.id = uni_atoi(s_id); item.id = uni_atoi(s_id);
else else
{ {
item.id = conf->getObjectID(s_id); item.id = conf->getObjectID(s_id);
if( item.id == DefaultObjectId ) if( item.id == DefaultObjectId )
item.id = conf->getControllerID(s_id); item.id = conf->getControllerID(s_id);
if( item.id == DefaultObjectId ) if( item.id == DefaultObjectId )
item.id = conf->getServiceID(s_id); item.id = conf->getServiceID(s_id);
} }
if( is_digit(s_node) ) if( is_digit(s_node) )
item.node = uni_atoi(s_node); item.node = uni_atoi(s_node);
else else
item.node = conf->getNodeID(s_node); item.node = conf->getNodeID(s_node);
} }
else else
{ {
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl; cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue; continue;
} }
res.emplace_back( std::move(item) ); res.emplace_back( std::move(item) );
} }
return res; return res;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
UniversalIO::IOType uniset::getIOType( const std::string& stype ) noexcept UniversalIO::IOType uniset::getIOType( const std::string& stype ) noexcept
{ {
if ( stype == "DI" || stype == "di" ) if ( stype == "DI" || stype == "di" )
return UniversalIO::DI; return UniversalIO::DI;
if( stype == "AI" || stype == "ai" ) if( stype == "AI" || stype == "ai" )
return UniversalIO::AI; return UniversalIO::AI;
if ( stype == "DO" || stype == "do" ) if ( stype == "DO" || stype == "do" )
return UniversalIO::DO; return UniversalIO::DO;
if ( stype == "AO" || stype == "ao" ) if ( stype == "AO" || stype == "ao" )
return UniversalIO::AO; return UniversalIO::AO;
return UniversalIO::UnknownIOType; return UniversalIO::UnknownIOType;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
std::string uniset::iotype2str( const UniversalIO::IOType& t ) noexcept std::string uniset::iotype2str( const UniversalIO::IOType& t ) noexcept
{ {
if( t == UniversalIO::AI ) if( t == UniversalIO::AI )
return "AI"; return "AI";
if( t == UniversalIO::DI ) if( t == UniversalIO::DI )
return "DI"; return "DI";
if( t == UniversalIO::AO ) if( t == UniversalIO::AO )
return "AO"; return "AO";
if( t == UniversalIO::DO ) if( t == UniversalIO::DO )
return "DO"; return "DO";
return "UnknownIOType"; return "UnknownIOType";
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
std::ostream& uniset::operator<<( std::ostream& os, const UniversalIO::IOType t ) std::ostream& uniset::operator<<( std::ostream& os, const UniversalIO::IOType t )
{ {
return os << iotype2str(t); return os << iotype2str(t);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool uniset::check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val ) noexcept bool uniset::check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val ) noexcept
{ {
if( f_prop.empty() ) if( f_prop.empty() )
return true; return true;
// просто проверка на не пустой field // просто проверка на не пустой field
if( f_val.empty() && it.getProp(f_prop).empty() ) if( f_val.empty() && it.getProp(f_prop).empty() )
return false; return false;
// просто проверка что field = value // просто проверка что field = value
if( !f_val.empty() && it.getProp(f_prop) != f_val ) if( !f_val.empty() && it.getProp(f_prop) != f_val )
return false; return false;
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
string uniset::timeToString(time_t tm, const std::string& brk ) noexcept string uniset::timeToString(time_t tm, const std::string& brk ) noexcept
{ {
std::tm tms; std::tm tms;
gmtime_r(&tm, &tms); gmtime_r(&tm, &tms);
ostringstream time; ostringstream time;
time << std::setw(2) << std::setfill('0') << tms.tm_hour << brk; time << std::setw(2) << std::setfill('0') << tms.tm_hour << brk;
time << std::setw(2) << std::setfill('0') << tms.tm_min << brk; time << std::setw(2) << std::setfill('0') << tms.tm_min << brk;
time << std::setw(2) << std::setfill('0') << tms.tm_sec; time << std::setw(2) << std::setfill('0') << tms.tm_sec;
return time.str(); return time.str();
} }
string uniset::dateToString(time_t tm, const std::string& brk ) noexcept string uniset::dateToString(time_t tm, const std::string& brk ) noexcept
{ {
std::tm tms; std::tm tms;
gmtime_r(&tm, &tms); gmtime_r(&tm, &tms);
ostringstream date; ostringstream date;
date << std::setw(4) << std::setfill('0') << tms.tm_year + 1900 << brk; date << std::setw(4) << std::setfill('0') << tms.tm_year + 1900 << brk;
date << std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << brk; date << std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << brk;
date << std::setw(2) << std::setfill('0') << tms.tm_mday; date << std::setw(2) << std::setfill('0') << tms.tm_mday;
return date.str(); return date.str();
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
int uniset::uni_atoi( const char* str ) noexcept int uniset::uni_atoi( const char* str ) noexcept
{ {
// if str is NULL or sscanf failed, we return 0 // if str is NULL or sscanf failed, we return 0
if( str == nullptr ) if( str == nullptr )
return 0; return 0;
// приходиться самостоятельно проверять на наличие префикса "0x" // приходиться самостоятельно проверять на наличие префикса "0x"
// чтобы применить соответствующую функцию. // чтобы применить соответствующую функцию.
// причём для чисел применяется atoll, // причём для чисел применяется atoll,
// чтобы корректно обрабатывать большие числа типа std::numeric_limits<unsigned int>::max() // чтобы корректно обрабатывать большие числа типа std::numeric_limits<unsigned int>::max()
// \warning есть сомнения, что на 64bit-тах это будет корректно работать.. // \warning есть сомнения, что на 64bit-тах это будет корректно работать..
unsigned int n = 0; unsigned int n = 0;
if( strlen(str) > 2 ) if( strlen(str) > 2 )
{ {
if( str[0] == '0' && str[1] == 'x' ) if( str[0] == '0' && str[1] == 'x' )
{ {
std::sscanf(str, "%x", &n); std::sscanf(str, "%x", &n);
return n; return n;
} }
} }
n = std::atoll(str); // универсальнее получать unsigned, чтобы не потерять "большие числа".. n = std::atoll(str); // универсальнее получать unsigned, чтобы не потерять "большие числа"..
return n; // а возвращаем int.. return n; // а возвращаем int..
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
char* uniset::uni_strdup( const string& src ) char* uniset::uni_strdup( const string& src )
{ {
size_t len = src.size(); size_t len = src.size();
char* d = new char[len + 1]; char* d = new char[len + 1];
memcpy(d, src.data(), len); memcpy(d, src.data(), len);
d[len] = '\0'; d[len] = '\0';
return d; return d;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& uniset::operator<<( std::ostream& os, const IOController_i::CalibrateInfo& c ) std::ostream& uniset::operator<<( std::ostream& os, const IOController_i::CalibrateInfo& c )
{ {
os << "[ rmin=" << c.minRaw os << "[ rmin=" << c.minRaw
<< " rmax=" << c.maxRaw << " rmax=" << c.maxRaw
<< " cmin=" << c.minCal << " cmin=" << c.minCal
<< " cmax=" << c.maxCal << " cmax=" << c.maxCal
<< " prec=" << c.precision << " prec=" << c.precision
<< " ]"; << " ]";
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& uniset::operator<<( std::ostream& os, const IONotifyController_i::ThresholdInfo& ti ) std::ostream& uniset::operator<<( std::ostream& os, const IONotifyController_i::ThresholdInfo& ti )
{ {
os << "[ id=" << ti.id os << "[ id=" << ti.id
<< " hilim=" << ti.hilimit << " hilim=" << ti.hilimit
<< " lowlim=" << ti.lowlimit << " lowlim=" << ti.lowlimit
<< " state=" << ti.state << " state=" << ti.state
<< " tv_sec=" << ti.tv_sec << " tv_sec=" << ti.tv_sec
<< " tv_nsec=" << ti.tv_nsec << " tv_nsec=" << ti.tv_nsec
<< " invert=" << ti.invert << " invert=" << ti.invert
<< " ]"; << " ]";
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& uniset::operator<<( std::ostream& os, const IOController_i::ShortIOInfo& s ) std::ostream& uniset::operator<<( std::ostream& os, const IOController_i::ShortIOInfo& s )
{ {
os << setw(10) << dateToString(s.tv_sec) os << setw(10) << dateToString(s.tv_sec)
<< " " << setw(8) << timeToString(s.tv_sec) << "." << s.tv_nsec << " " << setw(8) << timeToString(s.tv_sec) << "." << s.tv_nsec
<< " [ value=" << s.value << " supplier=" << s.supplier << " ]"; << " [ value=" << s.value << " supplier=" << s.supplier << " ]";
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& uniset::operator<<( std::ostream& os, const IONotifyController_i::ThresholdState& s ) std::ostream& uniset::operator<<( std::ostream& os, const IONotifyController_i::ThresholdState& s )
{ {
if( s == IONotifyController_i::LowThreshold ) if( s == IONotifyController_i::LowThreshold )
return os << "low"; return os << "low";
if( s == IONotifyController_i::HiThreshold ) if( s == IONotifyController_i::HiThreshold )
return os << "hi"; return os << "hi";
if( s == IONotifyController_i::NormalThreshold ) if( s == IONotifyController_i::NormalThreshold )
return os << "norm"; return os << "norm";
return os << "Unknown"; return os << "Unknown";
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::string uniset::replace_all( const std::string& src, const std::string& from, const std::string& to ) std::string uniset::replace_all( const std::string& src, const std::string& from, const std::string& to )
{ {
string res(src); string res(src);
if( from.empty() ) if( from.empty() )
return res; return res;
size_t pos = res.find(from, 0); size_t pos = res.find(from, 0);
while( pos != std::string::npos ) while( pos != std::string::npos )
{ {
res.replace(pos, from.length(), to); res.replace(pos, from.length(), to);
pos += to.length(); pos += to.length();
pos = res.find(from, pos); pos = res.find(from, pos);
} }
return res; return res;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
timeval uniset::to_timeval( const chrono::system_clock::duration& d ) timeval uniset::to_timeval( const chrono::system_clock::duration& d )
{ {
struct timeval tv; struct timeval tv;
if( d.count() == 0 ) if( d.count() == 0 )
tv.tv_sec = tv.tv_usec = 0; tv.tv_sec = tv.tv_usec = 0;
else else
{ {
std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d); std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d);
tv.tv_sec = sec.count(); tv.tv_sec = sec.count();
tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(d - sec).count(); tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(d - sec).count();
} }
return tv; return tv;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
timespec uniset::to_timespec( const chrono::system_clock::duration& d ) timespec uniset::to_timespec( const chrono::system_clock::duration& d )
{ {
struct timespec ts; struct timespec ts;
if( d.count() == 0 ) if( d.count() == 0 )
ts.tv_sec = ts.tv_nsec = 0; ts.tv_sec = ts.tv_nsec = 0;
else else
{ {
std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d); std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d);
ts.tv_sec = sec.count(); ts.tv_sec = sec.count();
ts.tv_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count(); ts.tv_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count();
} }
return ts; return ts;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
timespec uniset::now_to_timespec() timespec uniset::now_to_timespec()
{ {
auto d = std::chrono::system_clock::now().time_since_epoch(); auto d = std::chrono::system_clock::now().time_since_epoch();
return to_timespec(d); return to_timespec(d);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
uniset::Timespec_var uniset::now_to_uniset_timespec() uniset::Timespec_var uniset::now_to_uniset_timespec()
{ {
auto d = std::chrono::system_clock::now().time_since_epoch(); auto d = std::chrono::system_clock::now().time_since_epoch();
return to_uniset_timespec(d); return to_uniset_timespec(d);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
uniset::Timespec_var uniset::to_uniset_timespec( const chrono::system_clock::duration& d ) uniset::Timespec_var uniset::to_uniset_timespec( const chrono::system_clock::duration& d )
{ {
uniset::Timespec_var ts; uniset::Timespec_var ts;
if( d.count() == 0 ) if( d.count() == 0 )
ts->sec = ts->nsec = 0; ts->sec = ts->nsec = 0;
else else
{ {
std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d); std::chrono::seconds const sec = std::chrono::duration_cast<std::chrono::seconds>(d);
ts->sec = sec.count(); ts->sec = sec.count();
ts->nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count(); ts->nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(d - sec).count();
} }
return ts; return ts;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
char uniset::checkBadSymbols( const string& str ) char uniset::checkBadSymbols( const string& str )
{ {
for ( const auto& c : str ) for ( const auto& c : str )
{ {
for( size_t k = 0; k < sizeof(BadSymbols); k++ ) for( size_t k = 0; k < sizeof(BadSymbols); k++ )
{ {
if ( c == BadSymbols[k] ) if ( c == BadSymbols[k] )
return (char)BadSymbols[k]; return (char)BadSymbols[k];
} }
} }
return 0; return 0;
} }
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
string uniset::BadSymbolsToStr() string uniset::BadSymbolsToStr()
{ {
string bad = ""; string bad = "";
for( size_t i = 0; i < sizeof(BadSymbols); i++ ) for( size_t i = 0; i < sizeof(BadSymbols); i++ )
{ {
bad += "'" + bad += "'" +
bad += BadSymbols[i]; bad += BadSymbols[i];
bad += "', "; bad += "', ";
} }
return bad; return bad;
} }
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
uniset::KeyType uniset::key( const uniset::ObjectId id, const uniset::ObjectId node ) uniset::KeyType uniset::key( const uniset::ObjectId id, const uniset::ObjectId node )
{ {
//! \warning что тут у нас с переполнением.. //! \warning что тут у нас с переполнением..
return KeyType( (id * node) + (id + 2 * node) ); return KeyType( (id * node) + (id + 2 * node) );
} }
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
uniset::KeyType uniset::key( const IOController_i::SensorInfo& si ) uniset::KeyType uniset::key( const IOController_i::SensorInfo& si )
{ {
return key(si.id, si.node); return key(si.id, si.node);
} }
// --------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------
...@@ -252,6 +252,12 @@ TEST_CASE("UniSetTypes: file_exist", "[utypes][file_exist]" ) ...@@ -252,6 +252,12 @@ TEST_CASE("UniSetTypes: file_exist", "[utypes][file_exist]" )
CHECK( file_exist(conf->getConfFileName()) ); CHECK( file_exist(conf->getConfFileName()) );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: directory_exist", "[utypes][directory_exist]" )
{
CHECK_FALSE( directory_exist("uknown_dir") );
CHECK( directory_exist("/") ); // linux only
}
// -----------------------------------------------------------------------------
TEST_CASE("UniSetTypes: check_filter", "[utypes][check_filter]" ) TEST_CASE("UniSetTypes: check_filter", "[utypes][check_filter]" )
{ {
// bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept; // bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
......
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