Commit 7e85d143 authored by Pavel Vainerman's avatar Pavel Vainerman

make style (atyle)

parent d79d7839
......@@ -198,6 +198,7 @@ int main(int argc, char** argv)
{
if( opt == 'z' )
csv = true;
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf);
......@@ -712,13 +713,16 @@ int getValue( const string& args, UInterface& ui )
// т.к. может сработать исключение, а нам надо вывести ','
// до числа, то сперва получаем val
long val = ui.getValue(it.si.id, it.si.node);
if( csv && num++ > 0 )
cout << ",";
cout << val;
}
else
cout << ui.getValue(it.si.id, it.si.node);
}
break;
default:
......@@ -1009,14 +1013,14 @@ int oinfo(const string& args, UInterface& ui, const string& userparam )
auto conf = uniset_conf();
auto sl = uniset::getObjectsList( args, conf );
for( auto&& it : sl )
for( auto && it : sl )
{
if( it.node == DefaultObjectId )
it.node = conf->getLocalNode();
try
{
cout << ui.getObjectInfo(it.id, userparam,it.node) << endl;
cout << ui.getObjectInfo(it.id, userparam, it.node) << endl;
}
catch( const std::exception& ex )
{
......
......@@ -32,7 +32,7 @@ AC_ENABLE_SHARED(yes)
AC_ENABLE_STATIC(no)
AM_PROG_LIBTOOL
ASTYLE_OPT="-A1 -T -C -S -N -L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi"
ASTYLE_OPT="-A1 -T -C -S -L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi --max-instatement-indent=50"
AC_SUBST(ASTYLE_OPT)
# Checks for libraries.
......
......@@ -27,7 +27,7 @@ namespace uniset
// -----------------------------------------------------------------------------
namespace UniSetUDP
{
/*! Для оптимизации размера передаваемх данных, но с учётом того, что ID могут идти не подряд.
/*! Для оптимизации размера передаваемх данных, но с учётом того, что ID могут идти не подряд.
Сделан следующий формат:
Для аналоговых величин передаётся массив пар "id-value"(UDPAData).
Для булевых величин - отдельно массив ID и отдельно битовый массив со значениями,
......@@ -38,12 +38,12 @@ namespace UniSetUDP
\warning ТЕКУЩАЯ ВЕРСИЯ ПРОТОКОЛА НЕ БУДЕТ РАБОТАТЬ МЕЖДУ 32-битными и 64-битными системами (из-за отличия в типе long).
т.к. это не сильно актуально, пока не переделываю.
*/
*/
const uint32_t UNETUDP_MAGICNUM = 0x1337A1D; // идентификатор протокола
const uint32_t UNETUDP_MAGICNUM = 0x1337A1D; // идентификатор протокола
struct UDPHeader
{
struct UDPHeader
{
UDPHeader() noexcept: magic(UNETUDP_MAGICNUM), num(0), nodeID(0), procID(0), dcount(0), acount(0) {}
uint32_t magic;
size_t num;
......@@ -55,12 +55,12 @@ namespace UniSetUDP
friend std::ostream& operator<<( std::ostream& os, UDPHeader& p );
friend std::ostream& operator<<( std::ostream& os, UDPHeader* p );
} __attribute__((packed));
} __attribute__((packed));
const size_t MaxPacketNum = std::numeric_limits<size_t>::max();
const size_t MaxPacketNum = std::numeric_limits<size_t>::max();
struct UDPAData
{
struct UDPAData
{
UDPAData() noexcept: id(uniset::DefaultObjectId), val(0) {}
UDPAData(long id, long val) noexcept: id(id), val(val) {}
......@@ -68,31 +68,31 @@ namespace UniSetUDP
long val;
friend std::ostream& operator<<( std::ostream& os, UDPAData& p );
} __attribute__((packed));
} __attribute__((packed));
// Теоретический размер данных в UDP пакете (исключая заголовки) 65507
// Фактически желательно не вылезать за размер MTU (обычно 1500) - заголовки = 1432 байта
// т.е. надо чтобы sizeof(UDPPacket) < 1432
// Теоретический размер данных в UDP пакете (исключая заголовки) 65507
// Фактически желательно не вылезать за размер MTU (обычно 1500) - заголовки = 1432 байта
// т.е. надо чтобы sizeof(UDPPacket) < 1432
// При текущих настройках sizeof(UDPPacket) = 32654 (!)
static const size_t MaxACount = 1500;
static const size_t MaxDCount = 5000;
static const size_t MaxDDataCount = 1 + MaxDCount / 8 * sizeof(unsigned char);
// При текущих настройках sizeof(UDPPacket) = 32654 (!)
static const size_t MaxACount = 1500;
static const size_t MaxDCount = 5000;
static const size_t MaxDDataCount = 1 + MaxDCount / 8 * sizeof(unsigned char);
struct UDPPacket
{
struct UDPPacket
{
UDPPacket() noexcept: len(0) {}
size_t len;
uint8_t data[ sizeof(UDPHeader) + MaxDCount * sizeof(long) + MaxDDataCount + MaxACount * sizeof(UDPAData) ];
} __attribute__((packed));
} __attribute__((packed));
static const size_t MaxDataLen = sizeof(UDPPacket);
static const size_t MaxDataLen = sizeof(UDPPacket);
struct UDPMessage:
struct UDPMessage:
public UDPHeader
{
{
UDPMessage() noexcept;
UDPMessage(UDPMessage&& m) noexcept = default;
......@@ -168,9 +168,9 @@ namespace UniSetUDP
uint8_t d_dat[MaxDDataCount]; /*!< битовые значения */
friend std::ostream& operator<<( std::ostream& os, UDPMessage& p );
};
};
uint16_t makeCRC( unsigned char* buf, size_t len ) noexcept;
uint16_t makeCRC( unsigned char* buf, size_t len ) noexcept;
}
// --------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -28,24 +28,24 @@ namespace uniset
//--------------------------------------------------------------------------
namespace extensions
{
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
uniset::ObjectId getSharedMemoryID();
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
uniset::ObjectId getSharedMemoryID();
xmlNode* findNode( xmlNode* node, const std::string& snode, const std::string& field );
xmlNode* findNode( xmlNode* node, const std::string& snode, const std::string& field );
xmlNode* getCalibrationsSection();
xmlNode* getCalibrationsSection();
/*! замена служебных символов в строке
/*! замена служебных символов в строке
* '\\' -> '\n'
*/
void escape_string( std::string& s );
*/
void escape_string( std::string& s );
/*! Загрузка калибровочной диаграммы */
Calibration* buildCalibrationDiagram( const std::string& dname );
/*! Загрузка калибровочной диаграммы */
Calibration* buildCalibrationDiagram( const std::string& dname );
void on_sigchild( int sig );
void on_sigchild( int sig );
std::shared_ptr<DebugStream> dlog();
std::shared_ptr<DebugStream> dlog();
}
// -------------------------------------------------------------------------
// "синтаксический сахар"..для логов
......
......@@ -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 std::move(vmon.pretty_str()); }
inline std::string dumpVars()
{
return std::move(vmon.pretty_str());
}
// ------------------------------------------------------------
std::string help() noexcept;
......@@ -152,22 +161,25 @@ 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 getMonitInfo()
{
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
#ifndef DISABLE_REST_API
virtual void httpGetUserData( nlohmann::json& jdata ){} /*!< для пользовательских данных в httpGet() */
virtual void httpGetUserData( nlohmann::json& jdata ) {} /*!< для пользовательских данных в httpGet() */
virtual nlohmann::json httpDumpIO();
virtual nlohmann::json httpRequestLog( const Poco::URI::QueryParameters& p );
#endif
// Выполнение очередного шага программы
virtual void step(){}
virtual void step() {}
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const uniset::SystemMessage* sm );
......@@ -196,9 +208,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;
......@@ -249,7 +267,7 @@ 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::string ostate = { "" }; /*!< состояние процесса (выводится в getInfo()) */
......
......@@ -29,9 +29,9 @@ namespace uniset
// -----------------------------------------------------------------------------
namespace VTypes
{
/*! Тип переменной для Modbus[RTU|TCP] */
enum VType
{
/*! Тип переменной для Modbus[RTU|TCP] */
enum VType
{
vtUnknown,
vtF2, /*!< двойное слово float(4 байта). В виде строки задаётся как \b "F2". */
vtF2r, /*!< двойное слово float(4 байта). С перевёрнутой (reverse) последовательностью слов. \b "F2r". */
......@@ -43,17 +43,17 @@ namespace VTypes
vtI2r, /*!< целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "I2r".*/
vtU2, /*!< беззнаковое целое (4 байта). В виде строки задаётся как \b "U2".*/
vtU2r /*!< беззнаковое целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "U2r".*/
};
};
std::ostream& operator<<( std::ostream& os, const VType& vt );
std::ostream& operator<<( std::ostream& os, const VType& vt );
// -------------------------------------------------------------------------
std::string type2str( VType t ) noexcept; /*!< преобразование строки в тип */
VType str2type( const std::string& s ) noexcept; /*!< преобразование названия в строку */
int wsize( VType t ) noexcept; /*!< длина данных в словах */
// -------------------------------------------------------------------------
class F2
{
// -------------------------------------------------------------------------
std::string type2str( VType t ) noexcept; /*!< преобразование строки в тип */
VType str2type( const std::string& s ) noexcept; /*!< преобразование названия в строку */
int wsize( VType t ) noexcept; /*!< длина данных в словах */
// -------------------------------------------------------------------------
class F2
{
public:
// ------------------------------------------
......@@ -108,11 +108,11 @@ namespace VTypes
}
F2mem raw;
};
// --------------------------------------------------------------------------
class F2r:
};
// --------------------------------------------------------------------------
class F2r:
public F2
{
{
public:
// ------------------------------------------
......@@ -137,10 +137,10 @@ namespace VTypes
~F2r() noexcept {}
F2mem raw_backorder;
};
// --------------------------------------------------------------------------
class F4
{
};
// --------------------------------------------------------------------------
class F4
{
public:
// ------------------------------------------
static const size_t f4Size = 4;
......@@ -190,10 +190,10 @@ namespace VTypes
}
F4mem raw;
};
// --------------------------------------------------------------------------
class Byte
{
};
// --------------------------------------------------------------------------
class Byte
{
public:
static const size_t bsize = 2;
......@@ -255,10 +255,10 @@ namespace VTypes
}
Bytemem raw;
};
// --------------------------------------------------------------------------
class Unsigned
{
};
// --------------------------------------------------------------------------
class Unsigned
{
public:
// ------------------------------------------
......@@ -294,10 +294,10 @@ namespace VTypes
}
unsigned short raw;
};
// --------------------------------------------------------------------------
class Signed
{
};
// --------------------------------------------------------------------------
class Signed
{
public:
// ------------------------------------------
......@@ -333,10 +333,10 @@ namespace VTypes
}
signed short raw;
};
// --------------------------------------------------------------------------
class I2
{
};
// --------------------------------------------------------------------------
class I2
{
public:
// ------------------------------------------
......@@ -383,11 +383,11 @@ namespace VTypes
}
I2mem raw;
};
// --------------------------------------------------------------------------
class I2r:
};
// --------------------------------------------------------------------------
class I2r:
public I2
{
{
public:
I2r() noexcept
{
......@@ -410,10 +410,10 @@ namespace VTypes
~I2r() noexcept {}
I2mem raw_backorder;
};
// --------------------------------------------------------------------------
class U2
{
};
// --------------------------------------------------------------------------
class U2
{
public:
// ------------------------------------------
......@@ -460,11 +460,11 @@ namespace VTypes
}
U2mem raw;
};
// --------------------------------------------------------------------------
class U2r:
};
// --------------------------------------------------------------------------
class U2r:
public U2
{
{
public:
U2r() noexcept
{
......@@ -487,8 +487,8 @@ namespace VTypes
~U2r() {}
U2mem raw_backorder;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace VTypes
// --------------------------------------------------------------------------
......
......@@ -27,10 +27,10 @@ namespace uniset
// -------------------------------------------------------------------------
namespace extensions
{
static std::shared_ptr<DebugStream> _dlog;
static std::shared_ptr<DebugStream> _dlog;
std::shared_ptr<DebugStream> dlog()
{
std::shared_ptr<DebugStream> dlog()
{
if( _dlog )
return _dlog;
......@@ -44,12 +44,12 @@ namespace extensions
conf->initLogStream(_dlog, "dlog");
return _dlog;
}
// -------------------------------------------------------------------------
static uniset::ObjectId shmID = DefaultObjectId;
}
// -------------------------------------------------------------------------
static uniset::ObjectId shmID = DefaultObjectId;
uniset::ObjectId getSharedMemoryID()
{
uniset::ObjectId getSharedMemoryID()
{
if( shmID != DefaultObjectId )
return shmID;
......@@ -68,10 +68,10 @@ namespace extensions
// cout << "(uniset): shm=" << name << " id=" << shmID << endl;
return shmID;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
if( s.empty() )
return;
......@@ -82,23 +82,23 @@ namespace extensions
s.replace(pos, 2, "\n");
pos = s.find("\\n");
}
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
xmlNode* getCalibrationsSection()
{
xmlNode* getCalibrationsSection()
{
if( xmlCalibrationsNode )
return xmlCalibrationsNode;
xmlCalibrationsNode = uniset_conf()->getNode("Calibrations");
return xmlCalibrationsNode;
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
{
xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
{
if( !node )
return 0;
......@@ -114,10 +114,10 @@ namespace extensions
}
return 0;
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
xmlNode* root = getCalibrationsSection();
if( !root )
......@@ -139,10 +139,10 @@ namespace extensions
}
return new Calibration(dnode);
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
while(1)
{
int istatus;
......@@ -152,8 +152,8 @@ namespace extensions
if( pid <= 0 ) break;
}
}
// --------------------------------------------------------------------------
}
// --------------------------------------------------------------------------
} // end of namespace extensions
} // end of namespace uniset
// -------------------------------------------------------------------------
......@@ -25,13 +25,13 @@ namespace uniset
namespace VTypes
{
std::ostream& operator<<( std::ostream& os, const VType& vt )
{
std::ostream& operator<<( std::ostream& os, const VType& vt )
{
return os << type2str(vt);
}
}
VType str2type( const std::string& s ) noexcept
{
VType str2type( const std::string& s ) noexcept
{
if( s == "Byte" || s == "byte" )
return vtByte;
......@@ -63,10 +63,10 @@ namespace VTypes
return vtU2r;
return vtUnknown;
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
if( t == vtByte )
return "Byte";
......@@ -98,10 +98,10 @@ namespace VTypes
return "U2r";
return "vtUnknown";
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
if( t == vtByte )
return Byte::wsize();
......@@ -124,8 +124,8 @@ namespace VTypes
return U2::wsize();
return 1;
}
// -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // end of namespace VTypes
// -----------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -32,10 +32,10 @@ LostPassiveTestProc::LostPassiveTestProc( uniset::ObjectId id, xmlNode* confnode
if( it.getProp("iotype") != "AI" )
continue;
slist.emplace(it.getIntProp("id"),0);
slist.emplace(it.getIntProp("id"), 0);
}
setMaxSizeOfMessageQueue(slist.size()*2+500);
setMaxSizeOfMessageQueue(slist.size() * 2 + 500);
smTestID = slist.begin()->first;
}
......@@ -53,6 +53,7 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
{
std::lock_guard<std::mutex> lock(mut);
auto s = slist.find(sid);
if( s == slist.end() )
{
ostringstream err;
......@@ -66,13 +67,13 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
LostPassiveTestProc::LostPassiveTestProc()
{
cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception(myname+"(init): FAILED..");
throw uniset::Exception(myname + "(init): FAILED..");
}
// -----------------------------------------------------------------------------
void LostPassiveTestProc::askSensors(UniversalIO::UIOCommand cmd)
{
for( const auto& s: slist )
askSensor(s.first,cmd);
for( const auto& s : slist )
askSensor(s.first, cmd);
}
// -----------------------------------------------------------------------------
void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
......@@ -80,6 +81,7 @@ void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
std::lock_guard<std::mutex> lock(mut);
auto s = slist.find(sm->id);
if( s == slist.end() )
{
mycrit << myname << "(sensorInfo): ERROR: message from UNKNOWN SENSOR sm->id=" << sm->id << endl;
......
......@@ -24,7 +24,7 @@ class LostPassiveTestProc:
virtual void sensorInfo( const uniset::SensorMessage* sm ) override;
std::mutex mut;
std::unordered_map<uniset::ObjectId,long> slist;
std::unordered_map<uniset::ObjectId, long> slist;
private:
};
......
......@@ -24,7 +24,7 @@ void LostTestProc::setChildPassiveProc( const std::shared_ptr<LostPassiveTestPro
LostTestProc::LostTestProc()
{
cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception(myname+"(init): FAILED..");
throw uniset::Exception(myname + "(init): FAILED..");
}
// -----------------------------------------------------------------------------
void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
......@@ -36,11 +36,11 @@ void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
askTimer(tmCheck, checkTime);
// начальная инициализация значений в SM
for( auto&& s: slist )
for( auto && s : slist )
{
try
{
ui->setValue(s.first,s.second);
ui->setValue(s.first, s.second);
}
catch( std::exception& ex )
{
......@@ -78,11 +78,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
waitEmpty = false;
myinfo << myname << ": [OK]: empty queue. CHECK VALUE... " << endl;
for( auto&& s: slist )
for( auto && s : slist )
{
try
{
long smValue = ui->getValue(s.first);
if( smValue != s.second )
{
cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << s.second << endl;
......@@ -94,6 +96,7 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
if( child )
{
long childValue = child->checkValue(s.first);
if( smValue != childValue )
{
cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << childValue
......@@ -108,13 +111,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
cerr << i2->info << endl;
// cerr << "JSON: " << endl;
// Poco::URI::QueryParameters p;
// auto j = httpGet(p);
// cerr << j.dump() << endl;
// cerr << "-------------------------" << endl;
// auto j2 = child->httpGet(p);
// cerr << j2.dump() << endl;
// cerr << "JSON: " << endl;
// Poco::URI::QueryParameters p;
// auto j = httpGet(p);
// cerr << j.dump() << endl;
// cerr << "-------------------------" << endl;
// auto j2 = child->httpGet(p);
// cerr << j2.dump() << endl;
std::abort();
}
......@@ -127,20 +130,21 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
}
myinfo << myname << ": [OK]: UPDATE VALUE... " << endl;
for( auto&& s: slist )
for( auto && s : slist )
{
try
{
// Выставляем новое значение
ui->setValue(s.first, s.second+1);
ui->setValue(s.first, s.second + 1);
// проверяем что сохранилось
long smValue = ui->getValue(s.first);
if(ui->getValue(s.first) != (s.second+1) )
if(ui->getValue(s.first) != (s.second + 1) )
{
cerr << myname << "(check): SAVE TO SM ERROR!! sid=" << s.first
<< " value=" << smValue << " != " << (s.second+1) << endl;
<< " value=" << smValue << " != " << (s.second + 1) << endl;
uniset::SimpleInfo_var i = getInfo();
cerr << i->info << endl;
std::abort();
......
......@@ -43,7 +43,7 @@ int main(int argc, const char** argv)
act->add(tp);
ostringstream sp;
sp << "TestProc" << (i+max);
sp << "TestProc" << (i + max);
cout << "..create passive " << sp.str() << endl;
auto child = make_shared<LostPassiveTestProc>( conf->getObjectID(sp.str()));
......
......@@ -28,15 +28,15 @@
//-----------------------------------------------------------------------------
namespace uniset
{
class LimitTimers:
class LimitTimers:
public uniset::Exception
{
{
public:
LimitTimers(): Exception("LimitTimers") {}
/*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */
LimitTimers(const std::string& err): Exception(err) {}
};
};
//----------------------------------------------------------------------------------------
/*!
......
......@@ -37,13 +37,13 @@
*/
namespace uniset
{
/*!
/*!
Конфигуратор системы
\note В случае обнаружения критической ошибки в настроечном файле файле.
Вырабатывает исключение и прекращает работу.
*/
class Configuration
{
*/
class Configuration
{
public:
virtual ~Configuration();
......@@ -227,16 +227,16 @@ namespace uniset
bool transientIOR = { false };
timeout_t heartbeat_msec = { 3000 };
};
};
/*! Глобальный указатель на конфигурацию (singleton) */
std::shared_ptr<Configuration> uniset_conf() noexcept;
/*! Глобальный указатель на конфигурацию (singleton) */
std::shared_ptr<Configuration> uniset_conf() noexcept;
/*! Глобальный объект для вывода логов */
std::shared_ptr<DebugStream> ulog() noexcept;
/*! Глобальный объект для вывода логов */
std::shared_ptr<DebugStream> ulog() noexcept;
/*! инициализация "глобальной" конфигурации */
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile = "configure.xml" );
/*! инициализация "глобальной" конфигурации */
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile = "configure.xml" );
// --------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
......
......@@ -283,13 +283,15 @@ class DebugStream : public std::ostream
public:
explicit IosFlagSaver(std::ostream& _ios):
ios(_ios),
f(_ios.flags()) {
f(_ios.flags())
{
}
~IosFlagSaver() {
~IosFlagSaver()
{
ios.flags(f);
}
IosFlagSaver(const IosFlagSaver &rhs) = delete;
IosFlagSaver(const IosFlagSaver& rhs) = delete;
IosFlagSaver& operator= (const IosFlagSaver& rhs) = delete;
private:
......
......@@ -30,20 +30,20 @@
namespace uniset
{
/**
/**
@defgroup UniSetExceptions Исключения
@{
*/
*/
// namespase UniSetExceptions
// namespase UniSetExceptions
/*!
/*!
Базовый класс для всех исключений в библиотеке UniSet
\note Все вновь создаваемые исключения обязаны наследоваться от него или его потомков
*/
class Exception:
*/
class Exception:
public std::exception
{
{
public:
Exception(const std::string& txt) noexcept: text(txt.c_str()) {}
......@@ -63,127 +63,127 @@ namespace uniset
protected:
const std::string text;
};
};
class OutOfRange: public Exception
{
class OutOfRange: public Exception
{
public:
OutOfRange() noexcept: Exception("OutOfRange") {}
OutOfRange(const std::string& err) noexcept: Exception(err) {}
};
};
/*! Исключение, вырабатываемое функциями репозитория объектов.
/*! Исключение, вырабатываемое функциями репозитория объектов.
Например неверное имя секции при регистрации в репозитории объектов.
*/
class ORepFailed: public Exception
{
*/
class ORepFailed: public Exception
{
public:
ORepFailed() noexcept: Exception("ORepFailed") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ORepFailed(const std::string& err) noexcept: Exception(err) {}
};
};
/*! Системные ошибки */
class SystemError: public Exception
{
/*! Системные ошибки */
class SystemError: public Exception
{
public:
SystemError() noexcept: Exception("SystemError") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
SystemError(const std::string& err) noexcept: Exception(err) {}
};
};
/*! Ошибка соединения */
class CommFailed: public Exception
{
/*! Ошибка соединения */
class CommFailed: public Exception
{
public:
CommFailed() noexcept: Exception("CommFailed") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
CommFailed(const std::string& err) noexcept: Exception(err) {}
};
};
/*!
/*!
Исключение, вырабатываемое функциями, использующими удаленный вызов,
при невозможности вызвать удалённый метод за заданное время.
*/
class TimeOut: public CommFailed
{
*/
class TimeOut: public CommFailed
{
public:
TimeOut() noexcept: CommFailed("TimeOut") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
TimeOut(const std::string& err) noexcept: CommFailed(err) {}
};
};
/*! Исключение вырабатываемое при ошибке разыменования объекта репозитория */
class ResolveNameError: public ORepFailed
{
/*! Исключение вырабатываемое при ошибке разыменования объекта репозитория */
class ResolveNameError: public ORepFailed
{
public:
ResolveNameError() noexcept: ORepFailed("ResolveNameError") {}
ResolveNameError(const std::string& err) noexcept: ORepFailed(err) {}
};
};
class NSResolveError: public ORepFailed
{
class NSResolveError: public ORepFailed
{
public:
NSResolveError() noexcept: ORepFailed("NSResolveError") {}
NSResolveError(const std::string& err) noexcept: ORepFailed(err) {}
};
};
/*!
/*!
Исключение, вырабатываемое функциями репозитория объектов.
Попытка зарегистрировать объект под уже существующим именем
*/
class ObjectNameAlready: public ResolveNameError
{
*/
class ObjectNameAlready: public ResolveNameError
{
public:
ObjectNameAlready() noexcept: ResolveNameError("ObjectNameAlready") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ObjectNameAlready(const std::string& err) noexcept: ResolveNameError(err) {}
};
};
/*!
/*!
Исключение, вырабатываемое в случае указания неправильных аргументов при работе
с объектами(функциями) ввода/вывода
*/
class IOBadParam: public Exception
{
*/
class IOBadParam: public Exception
{
public:
IOBadParam() noexcept: Exception("IOBadParam") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
IOBadParam(const std::string& err) noexcept: Exception(err) {}
};
};
/*!
/*!
Исключение, вырабатываемое в случае присутствия в имени недопустимых символов.
См. uniset::BadSymbols[]
*/
class InvalidObjectName: public ResolveNameError
{
*/
class InvalidObjectName: public ResolveNameError
{
public:
InvalidObjectName() noexcept: ResolveNameError("InvalidObjectName") {}
InvalidObjectName(const std::string& err) noexcept: ResolveNameError(err) {}
};
};
class NameNotFound: public ResolveNameError
{
class NameNotFound: public ResolveNameError
{
public:
NameNotFound() noexcept: ResolveNameError("NameNotFound") {}
NameNotFound(const std::string& err) noexcept: ResolveNameError(err) {}
};
};
//@}
// end of UniSetException group
// ---------------------------------------------------------------------
//@}
// end of UniSetException group
// ---------------------------------------------------------------------
} // end of uniset namespace
// ---------------------------------------------------------------------
#endif // Exception_h_
......
......@@ -98,7 +98,7 @@ class IOController:
#ifndef DISABLE_REST_API
// http API
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
#endif
......
......@@ -34,7 +34,7 @@
//---------------------------------------------------------------------------
namespace uniset
{
class NCRestorer;
class NCRestorer;
//---------------------------------------------------------------------------
/*!
\page page_IONotifyController Хранение информации о состоянии с уведомлениями об изменении (IONotifyController)
......
......@@ -27,11 +27,11 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*! Класс работы с файлами содержащими IOR объекта
/*! Класс работы с файлами содержащими IOR объекта
\todo Для оптимизации можно сделать кэширование id:node > filename
*/
class IORFile
{
*/
class IORFile
{
public:
IORFile();
......@@ -44,8 +44,8 @@ namespace uniset
protected:
private:
};
// -----------------------------------------------------------------------------------------
};
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
......@@ -29,7 +29,7 @@
//---------------------------------------------------------------------------
namespace uniset
{
class UniSetObject;
class UniSetObject;
//---------------------------------------------------------------------------
/*! \class LT_Object
......
......@@ -25,9 +25,9 @@ namespace uniset
namespace LogServerTypes
{
const unsigned int MAGICNUM = 0x20160417;
enum Command
{
const unsigned int MAGICNUM = 0x20160417;
enum Command
{
cmdNOP, /*!< отсутствие команды */
cmdSetLevel, /*!< установить уровень вывода */
cmdAddLevel, /*!< добавить уровень вывода */
......@@ -45,12 +45,12 @@ namespace LogServerTypes
cmdFilterMode, /*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */
cmdViewDefaultLogLevel /*!< вывести уровни логов сохранённых как умолчательный (cmdSaveLogLevel) */
// cmdSetLogFile
};
};
std::ostream& operator<<(std::ostream& os, Command c );
std::ostream& operator<<(std::ostream& os, Command c );
struct lsMessage
{
struct lsMessage
{
lsMessage(): magic(MAGICNUM), cmd(cmdNOP), data(0)
{
std::memset(logname, 0, sizeof(logname));
......@@ -67,9 +67,9 @@ namespace LogServerTypes
// для команды 'cmdSetLogFile'
// static const size_t MAXLOGFILENAME = 200;
// char logfile[MAXLOGFILENAME];
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, lsMessage& m );
std::ostream& operator<<(std::ostream& os, lsMessage& m );
}
// -------------------------------------------------------------------------
} // end of uniset namespace
......
......@@ -25,9 +25,9 @@
//--------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//--------------------------------------------------------------------------
/*! \class MQMutex
* Простая "многопоточная" очередь сообщений с использованием std::mutex.
......
......@@ -30,8 +30,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
class Message
{
class Message
{
public:
enum TypeOfMessage
{
......@@ -78,13 +78,13 @@ namespace uniset
tmsg.consumer = msg.consumer;
return std::move(tmsg);
}
};
};
std::ostream& operator<<( std::ostream& os, const Message::TypeOfMessage& t );
std::ostream& operator<<( std::ostream& os, const Message::TypeOfMessage& t );
// ------------------------------------------------------------------------
class VoidMessage : public Message
{
// ------------------------------------------------------------------------
class VoidMessage : public Message
{
public:
VoidMessage( VoidMessage&& ) noexcept = default;
......@@ -115,12 +115,12 @@ namespace uniset
}
uniset::ByteOfMessage data[sizeof(uniset::RawDataOfTransportMessage) - sizeof(Message)];
};
};
// ------------------------------------------------------------------------
/*! Сообщение об изменении состояния датчика */
class SensorMessage : public Message
{
// ------------------------------------------------------------------------
/*! Сообщение об изменении состояния датчика */
class SensorMessage : public Message
{
public:
ObjectId id = { uniset::DefaultObjectId };
......@@ -159,12 +159,12 @@ namespace uniset
{
return transport(*this);
}
};
};
// ------------------------------------------------------------------------
/*! Системное сообщение */
class SystemMessage : public Message
{
// ------------------------------------------------------------------------
/*! Системное сообщение */
class SystemMessage : public Message
{
public:
enum Command
{
......@@ -200,14 +200,14 @@ namespace uniset
int command;
long data[2];
};
std::ostream& operator<<( std::ostream& os, const SystemMessage::Command& c );
};
std::ostream& operator<<( std::ostream& os, const SystemMessage::Command& c );
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Собщение о срабатывании таймера */
class TimerMessage : public Message
{
/*! Собщение о срабатывании таймера */
class TimerMessage : public Message
{
public:
TimerMessage( TimerMessage&& ) noexcept = default;
TimerMessage& operator=(TimerMessage&& ) noexcept = default;
......@@ -224,13 +224,13 @@ namespace uniset
}
uniset::TimerId id; /*!< id сработавшего таймера */
};
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Подтверждение(квитирование) сообщения */
class ConfirmMessage: public Message
{
/*! Подтверждение(квитирование) сообщения */
class ConfirmMessage: public Message
{
public:
inline TransportMessage transport_msg() const noexcept
......@@ -267,7 +267,7 @@ namespace uniset
protected:
ConfirmMessage() noexcept;
};
};
}
// --------------------------------------------------------------------------
......
......@@ -28,9 +28,9 @@
// -----------------------------------------------------------------------------------------
namespace uniset
{
// rwmutex..
class uniset_rwmutex
{
// rwmutex..
class uniset_rwmutex
{
public:
uniset_rwmutex( const std::string& name );
uniset_rwmutex();
......@@ -65,12 +65,12 @@ namespace uniset
std::string nm;
friend class uniset_rwmutex_lock;
std::unique_ptr<Poco::RWLock> m;
};
};
std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m );
// -------------------------------------------------------------------------
class uniset_rwmutex_wrlock
{
std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m );
// -------------------------------------------------------------------------
class uniset_rwmutex_wrlock
{
public:
uniset_rwmutex_wrlock( uniset_rwmutex& m );
~uniset_rwmutex_wrlock();
......@@ -79,10 +79,10 @@ namespace uniset
uniset_rwmutex_wrlock(const uniset_rwmutex_wrlock&) = delete;
uniset_rwmutex_wrlock& operator=(const uniset_rwmutex_wrlock&) = delete;
uniset_rwmutex& m;
};
};
class uniset_rwmutex_rlock
{
class uniset_rwmutex_rlock
{
public:
uniset_rwmutex_rlock( uniset_rwmutex& m );
~uniset_rwmutex_rlock();
......@@ -91,8 +91,8 @@ namespace uniset
uniset_rwmutex_rlock(const uniset_rwmutex_rlock&) = delete;
uniset_rwmutex_rlock& operator=(const uniset_rwmutex_rlock&) = delete;
uniset_rwmutex& m;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of UniSetTypes namespace
#endif
......@@ -34,31 +34,31 @@ namespace uniset
*/
namespace ORepHelpers
{
//! Получение ссылки на корень репозитория
CosNaming::NamingContext_ptr getRootNamingContext( const CORBA::ORB_ptr orb,
//! Получение ссылки на корень репозитория
CosNaming::NamingContext_ptr getRootNamingContext( const CORBA::ORB_ptr orb,
const std::string& nsName, int timeOutSec = 2);
//! Получение контекста по заданному имени
CosNaming::NamingContext_ptr getContext(const std::string& cname, int argc,
//! Получение контекста по заданному имени
CosNaming::NamingContext_ptr getContext(const std::string& cname, int argc,
const char* const* argv, const std::string& nsName)
throw(uniset::ORepFailed);
throw(uniset::ORepFailed);
CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const std::string& cname,
CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const std::string& cname,
const std::string& nsName)
throw(uniset::ORepFailed);
throw(uniset::ORepFailed);
//! Функция отделяющая имя секции от полного имени
const std::string getSectionName(const std::string& fullName, const std::string& brk = "/");
//! Функция отделяющая имя секции от полного имени
const std::string getSectionName(const std::string& fullName, const std::string& brk = "/");
//! Функция выделения имени из полного имени
const std::string getShortName(const std::string& fullName, const std::string& brk = "/");
//! Функция выделения имени из полного имени
const std::string getShortName(const std::string& fullName, const std::string& brk = "/");
//! Проверка на наличие недопустимых символов
char checkBadSymbols(const std::string& str);
//! Проверка на наличие недопустимых символов
char checkBadSymbols(const std::string& str);
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
std::string BadSymbolsToStr();
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
std::string BadSymbolsToStr();
}
// -------------------------------------------------------------------------
......
......@@ -27,8 +27,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
class ObjectIndex
{
class ObjectIndex
{
public:
ObjectIndex() {};
virtual ~ObjectIndex() {};
......@@ -77,10 +77,10 @@ namespace uniset
private:
};
};
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
......@@ -30,14 +30,14 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*!
/*!
\todo Проверить функции этого класса на повторную входимость
\bug При обращении к objectsMap[0].textName срабатывает исключение(видимо какое-то из std).
Требуется дополнительное изучение.
*/
class ObjectIndex_Array:
*/
class ObjectIndex_Array:
public ObjectIndex
{
{
public:
ObjectIndex_Array(const ObjectInfo* objectInfo);
virtual ~ObjectIndex_Array();
......@@ -59,8 +59,8 @@ namespace uniset
MapObjectKey mok;
const ObjectInfo* objectInfo;
size_t maxId;
};
// -----------------------------------------------------------------------------------------
};
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
......@@ -31,10 +31,10 @@
namespace uniset
{
/*! \todo Проверить функции этого класса на повторную входимость */
class ObjectIndex_XML:
/*! \todo Проверить функции этого класса на повторную входимость */
class ObjectIndex_XML:
public ObjectIndex
{
{
public:
ObjectIndex_XML(const std::string& xmlfile, size_t minSize = 1000 );
ObjectIndex_XML( const std::shared_ptr<UniXML>& xml, size_t minSize = 1000 );
......@@ -58,8 +58,8 @@ namespace uniset
typedef std::unordered_map<std::string, ObjectId> MapObjectKey;
MapObjectKey mok; // для обратного писка
std::vector<ObjectInfo> omap; // для прямого поиска
};
// -----------------------------------------------------------------------------------------
};
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
......@@ -22,18 +22,18 @@
// --------------------------------------------------------------------------
namespace uniset
{
// Шаблон для "универсальной инициализации объекта(процесса)".
// Использование:
// auto m = make_object<MyClass>("ObjectId","secname",...);
// --
// Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. );
// ---------------
// Если secname задан, то ищется: <secname name="ObjectId" ....>
// Если secname не задан, то: <idname name="idname" ...>
//----------------
template<typename T, typename... _Args>
std::shared_ptr<T> make_object( const std::string& idname, const std::string& secname, _Args&& ... __args )
{
// Шаблон для "универсальной инициализации объекта(процесса)".
// Использование:
// auto m = make_object<MyClass>("ObjectId","secname",...);
// --
// Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. );
// ---------------
// Если secname задан, то ищется: <secname name="ObjectId" ....>
// Если secname не задан, то: <idname name="idname" ...>
//----------------
template<typename T, typename... _Args>
std::shared_ptr<T> make_object( const std::string& idname, const std::string& secname, _Args&& ... __args )
{
auto conf = uniset::uniset_conf();
uniset::ObjectId id = conf->getObjectID(idname);
......@@ -53,13 +53,13 @@ namespace uniset
throw uniset::SystemError("(make_object<T> == nullptr" + string(typeid(T).name()));
return obj;
}
// -----------------------------------------------------------------------------
// версия с указанием начального xml-узла, с которого ведётся поиск xmlNode
// а ID берётся из поля name="" у найденного xmlnode.
template<typename T, typename... _Args>
std::shared_ptr<T> make_object_x( xmlNode* root, const std::string& secname, _Args&& ... __args )
{
}
// -----------------------------------------------------------------------------
// версия с указанием начального xml-узла, с которого ведётся поиск xmlNode
// а ID берётся из поля name="" у найденного xmlnode.
template<typename T, typename... _Args>
std::shared_ptr<T> make_object_x( xmlNode* root, const std::string& secname, _Args&& ... __args )
{
auto conf = uniset::uniset_conf();
auto xml = conf->getConfXML();
xmlNode* cnode = conf->findNode(root, secname, "");
......@@ -75,17 +75,17 @@ namespace uniset
return std::make_shared<T>(id, cnode, std::forward<_Args>(__args)...);
}
// -----------------------------------------------------------------------------
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// "по задумке" позволяет не загромаждать код..
// T - тип создаваемого объекта
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// Использование
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object( M* m, const std::string& idname, const std::string& secname, _Args&& ... __args )
{
}
// -----------------------------------------------------------------------------
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// "по задумке" позволяет не загромаждать код..
// T - тип создаваемого объекта
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// Использование
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object( M* m, const std::string& idname, const std::string& secname, _Args&& ... __args )
{
try
{
m->log()->info() << m->getName() << "(" << __FUNCTION__ << "): " << "create " << idname << "..." << std::endl;
......@@ -99,12 +99,12 @@ namespace uniset
m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << idname << "): " << ex << std::endl;
throw;
}
}
// -----------------------------------------------------------------------------
// Версия использующая make_object_x<>
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object_x( M* m, xmlNode* root, const std::string& secname, _Args&& ... __args )
{
}
// -----------------------------------------------------------------------------
// Версия использующая make_object_x<>
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object_x( M* m, xmlNode* root, const std::string& secname, _Args&& ... __args )
{
try
{
auto o = uniset::make_object_x<T>(root, secname, std::forward<_Args>(__args)...);
......@@ -117,8 +117,8 @@ namespace uniset
m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << string(typeid(T).name()) << "): " << ex << std::endl;
throw;
}
}
// -----------------------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------------------
} // endof namespace uniset
// -----------------------------------------------------------------------------------------
#endif // UHelpers_H_
......@@ -47,17 +47,17 @@
// -------------------------------------------------------------------------
namespace uniset
{
namespace UHttp
{
// текущая версия API
const std::string UHTTP_API_VERSION="v01";
namespace UHttp
{
// текущая версия API
const std::string UHTTP_API_VERSION = "v01";
/*! интерфейс для объекта выдающего json-данные */
class IHttpRequest
{
/*! интерфейс для объекта выдающего json-данные */
class IHttpRequest
{
public:
IHttpRequest(){}
virtual ~IHttpRequest(){}
IHttpRequest() {}
virtual ~IHttpRequest() {}
// throw SystemError
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) = 0;
......@@ -65,14 +65,14 @@ namespace uniset
// не обязательная функция.
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p );
};
// -------------------------------------------------------------------------
/*! интерфейс для обработки запросов к объектам */
class IHttpRequestRegistry
{
};
// -------------------------------------------------------------------------
/*! интерфейс для обработки запросов к объектам */
class IHttpRequestRegistry
{
public:
IHttpRequestRegistry(){}
virtual ~IHttpRequestRegistry(){}
IHttpRequestRegistry() {}
virtual ~IHttpRequestRegistry() {}
// throw SystemError, NameNotFound
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
......@@ -81,36 +81,36 @@ namespace uniset
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0;
};
};
// -------------------------------------------------------------------------
class UHttpRequestHandler:
// -------------------------------------------------------------------------
class UHttpRequestHandler:
public Poco::Net::HTTPRequestHandler
{
{
public:
UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry );
virtual void handleRequest( Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp ) override;
virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override;
private:
std::shared_ptr<IHttpRequestRegistry> registry;
std::shared_ptr<DebugStream> log;
};
// -------------------------------------------------------------------------
class UHttpRequestHandlerFactory:
};
// -------------------------------------------------------------------------
class UHttpRequestHandlerFactory:
public Poco::Net::HTTPRequestHandlerFactory
{
{
public:
UHttpRequestHandlerFactory( std::shared_ptr<IHttpRequestRegistry>& _registry );
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest & ) override;
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& ) override;
private:
std::shared_ptr<IHttpRequestRegistry> registry;
};
}
};
}
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
......
......@@ -31,10 +31,10 @@
// -------------------------------------------------------------------------
namespace uniset
{
namespace UHttp
{
class UHttpServer
{
namespace UHttp
{
class UHttpServer
{
public:
UHttpServer( std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& host, int port );
......@@ -56,8 +56,8 @@ namespace uniset
std::shared_ptr<Poco::Net::HTTPServer> http;
std::shared_ptr<UHttpRequestHandlerFactory> reqFactory;
};
}
};
}
}
// -------------------------------------------------------------------------
#endif // UHttpServer_H_
......
......@@ -11,15 +11,15 @@ namespace uniset
namespace UTCPCore
{
bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ) noexcept;
bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ) noexcept;
// -------------------------------------------
// author: https://gist.github.com/koblas/3364414
// ----------------------
// for use with ev::io..
// Buffer class - allow for output buffering such that it can be written out into async pieces
struct Buffer
{
// -------------------------------------------
// author: https://gist.github.com/koblas/3364414
// ----------------------
// for use with ev::io..
// Buffer class - allow for output buffering such that it can be written out into async pieces
struct Buffer
{
Buffer( const unsigned char* bytes, ssize_t nbytes );
Buffer( const std::string& s );
virtual ~Buffer();
......@@ -31,7 +31,7 @@ namespace UTCPCore
unsigned char* data = { 0 };
ssize_t len;
ssize_t pos;
};
};
}
// -------------------------------------------------------------------------
} // end of uniset namespace
......
......@@ -56,7 +56,7 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
class UniSetActivator:
public UniSetManager
#ifndef DISABLE_REST_API
,public uniset::UHttp::IHttpRequestRegistry
, public uniset::UHttp::IHttpRequestRegistry
#endif
{
public:
......
......@@ -134,7 +134,7 @@ class UniSetManager:
const std::shared_ptr<UniSetObject> deepFindObject( const std::string& name );
// рекурсивное наполнение списка объектов
void getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>>& vec, size_t lim=1000 );
void getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>>& vec, size_t lim = 1000 );
typedef UniSetManagerList::iterator MListIterator;
......
......@@ -75,7 +75,7 @@ class UniSetObject:
public POA_UniSetObject_i,
public LT_Object
#ifndef DISABLE_REST_API
,public uniset::UHttp::IHttpRequest
, public uniset::UHttp::IHttpRequest
#endif
{
public:
......
......@@ -13,14 +13,14 @@ class ModbusRTUMaster;
// -------------------------------------------------------------------------
namespace ModbusHelpers
{
ModbusRTU::ModbusAddr autodetectSlave( ModbusRTUMaster* m,
ModbusRTU::ModbusAddr autodetectSlave( ModbusRTUMaster* m,
ModbusRTU::ModbusAddr beg = 0,
ModbusRTU::ModbusAddr end = 255,
ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut();
ModbusRTU::ModbusAddr autodetectSlave( std::string dev,
ModbusRTU::ModbusAddr autodetectSlave( std::string dev,
ComPort::Speed s, int tout = 1000,
ModbusRTU::ModbusAddr beg = 0,
ModbusRTU::ModbusAddr end = 255,
......@@ -28,12 +28,12 @@ namespace ModbusHelpers
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut();
ComPort::Speed autodetectSpeed( ModbusRTUMaster* m, ModbusRTU::ModbusAddr slave,
ComPort::Speed autodetectSpeed( ModbusRTUMaster* m, ModbusRTU::ModbusAddr slave,
ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut();
ComPort::Speed autodetectSpeed( std::string dev,
ComPort::Speed autodetectSpeed( std::string dev,
ModbusRTU::ModbusAddr slave,
int timeout_msec = 1000,
ModbusRTU::ModbusData reg = 0,
......
......@@ -10,11 +10,11 @@ namespace uniset
// -------------------------------------------------------------------------
namespace ModbusRTU
{
/*! Ошибки обмена
/*! Ошибки обмена
все ошибки > InternalErrorCode в сеть не посылаются...
*/
enum mbErrCode
{
*/
enum mbErrCode
{
erNoError = 0, /*!< нет ошибок */
erUnExpectedPacketType = 1, /*!< Неожидаемый тип пакета (ошибка кода функции) */
erBadDataAddress = 2, /*!< адрес запрещен к опросу или не существует */
......@@ -32,14 +32,14 @@ namespace ModbusRTU
erTimeOut = 14, /*!< Тайм-аут при приеме ответа */
erPacketTooLong = 15, /*!< пакет длинее буфера приема */
erSessionClosed = 16 /*!< соединение закрыто */
};
};
// ---------------------------------------------------------------------
std::string mbErr2Str( mbErrCode e );
// ---------------------------------------------------------------------
class mbException:
// ---------------------------------------------------------------------
std::string mbErr2Str( mbErrCode e );
// ---------------------------------------------------------------------
class mbException:
public uniset::Exception
{
{
public:
mbException():
uniset::Exception("mbException"), err(ModbusRTU::erNoError) {}
......@@ -53,8 +53,8 @@ namespace ModbusRTU
{
return os << "(" << ex.err << ") " << mbErr2Str(ex.err);
}
};
// ---------------------------------------------------------------------
};
// ---------------------------------------------------------------------
} // end of namespace ModbusRTU
// -------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -15,15 +15,15 @@
// -------------------------------------------------------------------------
namespace std
{
template<>
class hash<uniset::ModbusRTU::mbErrCode>
{
template<>
class hash<uniset::ModbusRTU::mbErrCode>
{
public:
size_t operator()(const uniset::ModbusRTU::mbErrCode& e) const
{
return std::hash<size_t>()(e);
}
};
};
}
// -------------------------------------------------------------------------
namespace uniset
......
......@@ -12,17 +12,17 @@ namespace uniset
/*! ModbusTCP core functions */
namespace ModbusTCPCore
{
// Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed
// Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed
// t - msec (сколько ждать)
size_t readNextData(UTCPStream* tcp, std::queue<unsigned char>& qrecv, size_t max = 100);
size_t getNextData( UTCPStream* tcp, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len );
ModbusRTU::mbErrCode sendData(UTCPStream* tcp, unsigned char* buf, size_t len );
// t - msec (сколько ждать)
size_t readNextData(UTCPStream* tcp, std::queue<unsigned char>& qrecv, size_t max = 100);
size_t getNextData( UTCPStream* tcp, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len );
ModbusRTU::mbErrCode sendData(UTCPStream* tcp, unsigned char* buf, size_t len );
// работа напрямую с сокетом
size_t readDataFD(int fd, std::queue<unsigned char>& qrecv, size_t max = 100, size_t attempts = 1 );
size_t getDataFD( int fd, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len, size_t attempts = 1 );
ModbusRTU::mbErrCode sendDataFD( int fd, unsigned char* buf, size_t len );
// работа напрямую с сокетом
size_t readDataFD(int fd, std::queue<unsigned char>& qrecv, size_t max = 100, size_t attempts = 1 );
size_t getDataFD( int fd, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len, size_t attempts = 1 );
ModbusRTU::mbErrCode sendDataFD( int fd, unsigned char* buf, size_t len );
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -64,6 +64,7 @@ long pyUInterface::getValue( long id )throw(UException)
using namespace uniset;
UniversalIO::IOType t = conf->getIOType(id);
if( t == UniversalIO::UnknownIOType )
{
ostringstream e;
......@@ -99,6 +100,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
using namespace uniset;
UniversalIO::IOType t = conf->getIOType(id);
if( t == UniversalIO::UnknownIOType )
{
ostringstream e;
......
......@@ -23,22 +23,22 @@
// --------------------------------------------------------------------------
namespace pyUInterface
{
void uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException);
void uniset_init( int argc, char** argv, const std::string& xmlfile )throw(UException);
void uniset_activate_objects() throw(UException);
void uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException);
void uniset_init( int argc, char** argv, const std::string& xmlfile )throw(UException);
void uniset_activate_objects() throw(UException);
//---------------------------------------------------------------------------
long getValue( long id )throw(UException);
void setValue( long id, long val, long supplier = UTypes::DefaultSupplerID )throw(UException);
//---------------------------------------------------------------------------
long getValue( long id )throw(UException);
void setValue( long id, long val, long supplier = UTypes::DefaultSupplerID )throw(UException);
long getSensorID( const std::string& name );
long getObjectID( const std::string& name );
long getSensorID( const std::string& name );
long getObjectID( const std::string& name );
std::string getShortName( long id );
std::string getName( long id );
std::string getTextName( long id );
std::string getShortName( long id );
std::string getName( long id );
std::string getTextName( long id );
std::string getConfFileName();
std::string getConfFileName();
}
//---------------------------------------------------------------------------
#endif
......
......@@ -135,7 +135,7 @@ UTypes::ShortIOInfo UConnector::getTimeChange( long id, long node )
try
{
IOController_i::ShortIOInfo i = ui->getTimeChange(id,node);
IOController_i::ShortIOInfo i = ui->getTimeChange(id, node);
return toUTypes(i);
}
catch( const std::exception& ex )
......@@ -198,7 +198,7 @@ throw(UException)
try
{
return ui->getObjectInfo(id,params,node);
return ui->getObjectInfo(id, params, node);
}
catch( std::exception& ex )
{
......
......@@ -19,7 +19,7 @@
// --------------------------------------------------------------------------
struct UException
{
UException():err("UException") {}
UException(): err("UException") {}
explicit UException( const std::string& e ): err(e) {}
explicit UException( const char* e ): err( std::string(e)) {}
~UException() {}
......
......@@ -60,7 +60,7 @@ class UProxyObject_impl:
};
std::mutex mutexSMap;
std::unordered_map<uniset::ObjectId,SInfo> smap;
std::unordered_map<uniset::ObjectId, SInfo> smap;
bool askOK = { false };
};
// --------------------------------------------------------------------------
......@@ -72,6 +72,7 @@ UProxyObject::UProxyObject() throw(UException)
UProxyObject::UProxyObject( const std::string& name ) throw( UException )
{
auto conf = uniset_conf();
if ( !conf )
{
std::ostringstream err;
......@@ -117,7 +118,7 @@ long UProxyObject::getValue( long id ) throw(UException)
// --------------------------------------------------------------------------
void UProxyObject::setValue( long id, long val ) throw(UException)
{
uobj->impl_setValue(id,val);
uobj->impl_setValue(id, val);
}
// --------------------------------------------------------------------------
bool UProxyObject::askIsOK()
......@@ -160,7 +161,7 @@ void UProxyObject::addToAsk( long id ) throw(UException)
}
// --------------------------------------------------------------------------
UProxyObject_impl::UProxyObject_impl( ObjectId id ):
UObject_SK(id,nullptr)
UObject_SK(id, nullptr)
{
}
......@@ -179,6 +180,7 @@ void UProxyObject_impl::impl_addToAsk( ObjectId id ) throw( UException )
i.si.node = conf->getLocalNode();
auto inf = conf->oind->getObjectInfo(id);
if( inf && inf->data )
{
UniXML::iterator it( (xmlNode*)(inf->data) );
......@@ -193,6 +195,7 @@ long UProxyObject_impl::impl_getValue( long id ) throw(UException)
{
std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(id);
if( i == smap.end() )
{
std::ostringstream err;
......@@ -207,6 +210,7 @@ float UProxyObject_impl::impl_getFloatValue( long id ) throw(UException)
{
std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(id);
if( i == smap.end() )
{
std::ostringstream err;
......@@ -227,7 +231,7 @@ void UProxyObject_impl::impl_setValue( long id, long val ) throw(UException)
{
try
{
UObject_SK::setValue(id,val);
UObject_SK::setValue(id, val);
}
catch( std::exception& ex )
{
......@@ -247,11 +251,12 @@ bool UProxyObject_impl::impl_updateValues()
{
std::unique_lock<std::mutex> lk(mutexSMap);
bool ret = true;
for( auto&& i: smap )
for( auto && i : smap )
{
try
{
i.second.value = ui->getValue(i.second.si.id,i.second.si.node);
i.second.value = ui->getValue(i.second.si.id, i.second.si.node);
i.second.fvalue = (float)i.second.value / pow(10.0, i.second.precision);
}
catch( std::exception& ex )
......@@ -270,18 +275,19 @@ bool UProxyObject_impl::impl_smIsOK()
// проверяем по первому датчику
auto s = smap.begin();
return ui->isExist(s->second.si.id,s->second.si.node);
return ui->isExist(s->second.si.id, s->second.si.node);
}
// --------------------------------------------------------------------------
void UProxyObject_impl::askSensors( UniversalIO::UIOCommand cmd )
{
std::unique_lock<std::mutex> lk(mutexSMap);
askOK = true;
for( const auto& i: smap )
for( const auto& i : smap )
{
try
{
ui->askRemoteSensor(i.second.si.id,cmd,i.second.si.node, getId());
ui->askRemoteSensor(i.second.si.id, cmd, i.second.si.node, getId());
}
catch( std::exception& ex )
{
......@@ -295,6 +301,7 @@ void UProxyObject_impl::sensorInfo( const SensorMessage* sm )
{
std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(sm->id);
if( i != smap.end() )
{
i->second.value = sm->value;
......
......@@ -23,11 +23,11 @@
// --------------------------------------------------------------------------
namespace UTypes
{
const long DefaultID = uniset::DefaultObjectId;
const long DefaultSupplerID = uniset::AdminID;
const long DefaultID = uniset::DefaultObjectId;
const long DefaultSupplerID = uniset::AdminID;
struct Params
{
struct Params
{
static const int max = 20;
Params(): argc(0)
......@@ -64,15 +64,15 @@ namespace UTypes
{
return Params();
}
};
};
struct ShortIOInfo
{
struct ShortIOInfo
{
long value;
unsigned long tv_sec;
unsigned long tv_nsec;
long supplier;
};
};
}
//---------------------------------------------------------------------------
......
......@@ -99,7 +99,8 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
if( objectName == "help" )
{
nlohmann::json jdata;
jdata["help"] = {
jdata["help"] =
{
{"help", {"desc", "this help"}},
{"list", {"desc", "list of objects"}},
{"ObjectName", {"desc", "'ObjectName' information"}},
......
......@@ -26,7 +26,7 @@ using namespace UHttp;
// -------------------------------------------------------------------------
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host,_port)
sa(_host, _port)
{
try
{
......
......@@ -80,7 +80,7 @@ bool TCPCheck::check( const std::string& _ip, int _port, timeout_t tout )
TGuard<TCPCheck> t(this, &TCPCheck::check_thread);
std::unique_lock<std::mutex> lock(thr_mutex);
thr_event.wait_for(lock,std::chrono::milliseconds(tout), [=]()
thr_event.wait_for(lock, std::chrono::milliseconds(tout), [ = ]()
{
return ( thr_finished == true );
} );
......@@ -118,7 +118,7 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, const std::string&
TGuard<TCPCheck> t(this, &TCPCheck::ping_thread);
std::unique_lock<std::mutex> lock(thr_mutex);
thr_event.wait_for(lock,std::chrono::milliseconds(tout), [=]()
thr_event.wait_for(lock, std::chrono::milliseconds(tout), [ = ]()
{
return ( thr_finished == true );
} );
......
......@@ -177,7 +177,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207
std::ostringstream fmt;
fmt << "%Od" << brk << "%Om" << brk << "%Y";
return (*this) << std::put_time(&tms,fmt.str().c_str());
return (*this) << std::put_time(&tms, fmt.str().c_str());
#else
return (*this) << std::setw(2) << std::setfill('0') << tms.tm_mday << brk
<< std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << brk
......@@ -200,16 +200,17 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207
std::ostringstream fmt;
fmt << "%OH" << brk << "%OM" << brk << "%OS";
(*this) << std::put_time(&tms,fmt.str().c_str());
(*this) << std::put_time(&tms, fmt.str().c_str());
#else
*this << std::setw(2) << std::setfill('0') << tms.tm_hour << brk
<< std::setw(2) << std::setfill('0') << tms.tm_min << brk
<< std::setw(2) << std::setfill('0') << tms.tm_sec;
#endif
if( show_usec )
(*this) << "." << std::setw(6) << (tv.tv_nsec/1000);
(*this) << "." << std::setw(6) << (tv.tv_nsec / 1000);
else if( show_msec )
(*this) << "." << std::setw(3) << (tv.tv_nsec/1000000);
(*this) << "." << std::setw(3) << (tv.tv_nsec / 1000000);
return *this;
}
......@@ -227,7 +228,7 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
std::tm tms = *std::localtime(&tv.tv_sec);
#if __GLIBCXX__ >= 20151207
*this << std::put_time(&tms,"%Od/%Om/%Y %OH:%OM:%OS");
*this << std::put_time(&tms, "%Od/%Om/%Y %OH:%OM:%OS");
#else
*this << std::setw(2) << std::setfill('0') << tms.tm_mday << "/"
<< std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << "/"
......@@ -238,9 +239,9 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
#endif
if( show_usec )
(*this) << "." << std::setw(6) << std::setfill('0') << (tv.tv_nsec/1000);
(*this) << "." << std::setw(6) << std::setfill('0') << (tv.tv_nsec / 1000);
else if( show_msec )
(*this) << "." << std::setw(3) << std::setfill('0') << (tv.tv_nsec/1000000);
(*this) << "." << std::setw(3) << std::setfill('0') << (tv.tv_nsec / 1000000);
return *this;
}
......
......@@ -226,6 +226,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
ostringstream err;
err << myname << "(evprepare): " << ex.what();
if( mylog.is_crit() )
mylog.crit() << err.str() << endl;
......@@ -368,6 +369,7 @@ nlohmann::json LogServer::httpGetShortInfo()
uniset_rwmutex_rlock l(mutSList);
auto& jsess = jdata["sessions"];
for( const auto& s : slist )
jsess.push_back(s->httpGetShortInfo());
}
......
......@@ -35,22 +35,22 @@ namespace ORepHelpers
{
// --------------------------------------------------------------------------
/*!
// --------------------------------------------------------------------------
/*!
* \param cname - полное имя контекста ссылку на который, возвратит функция.
* \param argc - argc
* \param argc - argv
* \param nsName - параметры инициализации ORB
*/
CosNaming::NamingContext_ptr getContext(const string& cname, int argc, const char* const* argv, const string& nsName ) throw(ORepFailed)
{
*/
CosNaming::NamingContext_ptr getContext(const string& cname, int argc, const char* const* argv, const string& nsName ) throw(ORepFailed)
{
CORBA::ORB_var orb = CORBA::ORB_init( argc, (char**)argv );
ulogrep << "OREPHELP: orb init ok" << endl;
return getContext(orb, cname, nsName);
}
// --------------------------------------------------------------------------
CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const string& cname, const string& servname) throw(ORepFailed)
{
}
// --------------------------------------------------------------------------
CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const string& cname, const string& servname) throw(ORepFailed)
{
CosNaming::NamingContext_var rootC;
ulogrep << "OREPHELPER(getContext): get rootcontext...(servname = " << servname << ")" << endl;
......@@ -133,12 +133,12 @@ namespace ORepHelpers
// Если _var
return ctx._retn();
}
}
// ---------------------------------------------------------------------------------------------------------------
/*! \param orb - ссылка на ORB */
CosNaming::NamingContext_ptr getRootNamingContext(const CORBA::ORB_ptr orb, const string& nsName, int timeoutSec)
{
// ---------------------------------------------------------------------------------------------------------------
/*! \param orb - ссылка на ORB */
CosNaming::NamingContext_ptr getRootNamingContext(const CORBA::ORB_ptr orb, const string& nsName, int timeoutSec)
{
CosNaming::NamingContext_var rootContext;
try
......@@ -191,45 +191,45 @@ namespace ORepHelpers
// Если создан как _var
return rootContext._retn();
}
// ---------------------------------------------------------------------------------------------------------------
/*!
}
// ---------------------------------------------------------------------------------------------------------------
/*!
* \param fname - полное имя включающее в себя путь ("Root/Section1/name|Node:Alias")
* \param brk - используемый символ разделитель
*/
const string getShortName( const string& fname, const std::string& brk )
{
*/
const string getShortName( const string& fname, const std::string& brk )
{
string::size_type pos = fname.rfind(brk);
if( pos == string::npos )
return fname;
return fname.substr( pos + 1, fname.length() );
}
}
// ---------------------------------------------------------------------------------------------------------------
/*!
// ---------------------------------------------------------------------------------------------------------------
/*!
* \param fullName - полное имя включающее в себя путь
* \param brk - используемый символ разделитель
* \note Функция возвращает путь без последнего символа разделителя ("Root/Section1/name" -> "Root/Section1")
*/
const string getSectionName( const string& fullName, const std::string& brk )
{
*/
const string getSectionName( const string& fullName, const std::string& brk )
{
string::size_type pos = fullName.rfind(brk);
if( pos == string::npos )
return "";
return fullName.substr(0, pos);
}
}
// ---------------------------------------------------------------------------------------------------------------
/*
// ---------------------------------------------------------------------------------------------------------------
/*
* Запрещенные символы см. uniset::BadSymbols[]
* \return Если не найдено запрещенных символов то будет возвращен 0, иначе найденный символ
*/
char checkBadSymbols( const string& str )
{
*/
char checkBadSymbols( const string& str )
{
using namespace uniset;
for ( size_t i = 0; i < str.length(); i++)
......@@ -242,11 +242,11 @@ namespace ORepHelpers
}
return 0;
}
}
// ---------------------------------------------------------------------------------------------------------------
string BadSymbolsToStr()
{
// ---------------------------------------------------------------------------------------------------------------
string BadSymbolsToStr()
{
string bad = "";
for( size_t i = 0; i < sizeof(uniset::BadSymbols); i++ )
......@@ -258,7 +258,7 @@ namespace ORepHelpers
}
return std::move(bad);
}
// ---------------------------------------------------------------------------------------------------------------
}
// ---------------------------------------------------------------------------------------------------------------
}
}
......@@ -529,14 +529,16 @@ void UniSetActivator::init()
abortScript = conf->getArgParam("--uniset-abort-script", "");
#ifndef DISABLE_REST_API
if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 )
{
httpHost = conf->getArgParam("--activator-httpserver-host", "localhost");
ostringstream s;
s << (getId()==DefaultObjectId ? 8080 : getId() );
s << (getId() == DefaultObjectId ? 8080 : getId() );
httpPort = conf->getArgInt("--activator-httpserver-port", s.str());
ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
}
#endif
orb = conf->getORB();
......@@ -668,12 +670,13 @@ void UniSetActivator::run( bool thread )
set_signals(true);
#ifndef DISABLE_REST_API
if( !httpHost.empty() )
{
try
{
auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this());
httpserv = make_shared<UHttp::UHttpServer>(reg,httpHost,httpPort);
httpserv = make_shared<UHttp::UHttpServer>(reg, httpHost, httpPort);
httpserv->start();
}
catch( std::exception& ex )
......@@ -681,6 +684,7 @@ void UniSetActivator::run( bool thread )
uwarn << myname << "(run): init http server error: " << ex.what() << endl;
}
}
#endif
if( thread )
......@@ -719,8 +723,10 @@ void UniSetActivator::stop()
ulogsys << myname << "(stop): discard request ok." << endl;
#ifndef DISABLE_REST_API
if( httpserv )
httpserv->stop();
#endif
}
......@@ -876,6 +882,7 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U
return httpGet(p);
auto obj = deepFindObject(name);
if( obj )
return obj->httpGet(p);
......@@ -894,9 +901,9 @@ nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParame
//! \todo Доделать обработку параметров beg,lim на случай большого количества объектов (и частичных запросов)
size_t lim = 1000;
getAllObjectsList(vec,lim);
getAllObjectsList(vec, lim);
for( const auto& o: vec )
for( const auto& o : vec )
jdata.push_back(o->getName());
return jdata;
......@@ -908,6 +915,7 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
return httpHelp(p);
auto obj = deepFindObject(name);
if( obj )
return obj->httpHelp(p);
......@@ -919,11 +927,12 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
nlohmann::json UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p)
{
if( name == myname )
return httpRequest(req,p);
return httpRequest(req, p);
auto obj = deepFindObject(name);
if( obj )
return obj->httpRequest(req,p);
return obj->httpRequest(req, p);
ostringstream err;
err << "Object '" << name << "' not found";
......
......@@ -412,7 +412,8 @@ bool UniSetManager::deactivateObject()
const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& name )
{
uniset_rwmutex_rlock lock(olistMutex);
for( auto&& o: olist )
for( auto && o : olist )
{
if( o->getName() == name )
return o;
......@@ -424,7 +425,8 @@ const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& nam
const std::shared_ptr<UniSetManager> UniSetManager::findManager( const string& name )
{
uniset_rwmutex_rlock lock(mlistMutex);
for( auto&& m: mlist )
for( auto && m : mlist )
{
if( m->getName() == name )
return m;
......@@ -437,11 +439,13 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
{
{
auto obj = findObject(name);
if( obj )
return obj;
}
auto man = findManager(name);
if( man )
{
auto obj = dynamic_pointer_cast<UniSetObject>(man);
......@@ -449,9 +453,10 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
}
// ищем в глубину у каждого менеджера
for( const auto& m: mlist )
for( const auto& m : mlist )
{
auto obj = m->deepFindObject(name);
if( obj )
return obj;
}
......@@ -465,18 +470,19 @@ void UniSetManager::getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>
vec.push_back(get_ptr());
// добавить подчинённые объекты
for( const auto& o: olist )
for( const auto& o : olist )
{
vec.push_back(o);
if( lim > 0 && vec.size() >= lim )
return;
}
// добавить рекурсивно по менеджерам
for( const auto& m: mlist )
for( const auto& m : mlist )
{
// вызываем рекурсивно
m->getAllObjectsList(vec,lim);
m->getAllObjectsList(vec, lim);
}
}
// ------------------------------------------------------------------------------------------
......
......@@ -41,16 +41,19 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
{
{
std::lock_guard<std::mutex> lck(wlist_mutex);
if( std::find(wlist.begin(), wlist.end(), w) != wlist.end() )
{
cerr << "(CommonEventLoop::evrun): " << w->wname() << " ALREADY ADDED.." << endl;
return false;
}
wlist.push_back(w);
}
{
std::lock_guard<std::mutex> lck(thr_mutex);
if( !thr )
{
thr = make_shared<std::thread>( [ = ] { CommonEventLoop::defaultLoop(); } );
......@@ -58,7 +61,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
std::unique_lock<std::mutex> locker(prep_mutex);
// ожидаем запуска loop
// иначе evprep.send() улетит в никуда
prep_event.wait_for(locker,std::chrono::milliseconds(waitTimeout_msec), [=]()
prep_event.wait_for(locker, std::chrono::milliseconds(waitTimeout_msec), [ = ]()
{
return ( isrunning == true );
} );
......@@ -86,7 +89,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
evprep.send(); // будим default loop
// ожидаем обработки evprepare (которая будет в defaultLoop)
prep_event.wait_for(locker,std::chrono::milliseconds(waitTimeout_msec), [=]()
prep_event.wait_for(locker, std::chrono::milliseconds(waitTimeout_msec), [ = ]()
{
return ( prep_notify == true );
} );
......@@ -137,7 +140,7 @@ bool CommonEventLoop::evstop( EvWatcher* w )
}
wlist.erase( std::remove( wlist.begin(), wlist.end(), w ), wlist.end() );
// wlist.remove(w);
// wlist.remove(w);
if( !wlist.empty() )
return false;
......@@ -170,6 +173,7 @@ void CommonEventLoop::onPrepare() noexcept
prep_notify = false;
{
std::lock_guard<std::mutex> lock(prep_mutex);
if( wprep )
{
try
......
......@@ -849,15 +849,17 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
auto& jhelp = jdata[myname]["help"];
jhelp["get"]["desc"] = "get value for sensor";
jhelp["get"]["params"] = {
{"id1,name2,id3","get value for id1,name2,id3 sensors"},
{"shortInfo","get short information for sensors"}
jhelp["get"]["params"] =
{
{"id1,name2,id3", "get value for id1,name2,id3 sensors"},
{"shortInfo", "get short information for sensors"}
};
jhelp["sensors"]["desc"] = "get all sensors.";
jhelp["sensors"]["params"] = {
{"nameonly","get only name sensors"},
{"offset=N","get from N record"},
{"limit=M","limit of records"}
jhelp["sensors"]["params"] =
{
{"nameonly", "get only name sensors"},
{"offset=N", "get from N record"},
{"limit=M", "limit of records"}
};
return jdata;
......@@ -866,12 +868,12 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
nlohmann::json IOController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{
if( req == "get" )
return request_get(req,p);
return request_get(req, p);
if( req == "sensors" )
return request_sensors(req,p);
return request_sensors(req, p);
return UniSetManager::httpRequest(req,p);
return UniSetManager::httpRequest(req, p);
}
// -----------------------------------------------------------------------------
nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p )
......@@ -885,6 +887,7 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
auto conf = uniset_conf();
auto slist = uniset::getSInfoList( p[0].first, conf );
if( slist.empty() )
{
ostringstream err;
......@@ -893,20 +896,22 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
}
bool shortInfo = false;
if( p.size() > 1 && p[1].first=="shortInfo" )
if( p.size() > 1 && p[1].first == "shortInfo" )
shortInfo = true;
// ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl;
// ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl;
nlohmann::json jdata;
auto& jsens = jdata[myname]["sensors"];
for( const auto& s: slist )
for( const auto& s : slist )
{
try
{
auto sinf = ioList.find(s.si.id);
if( sinf == ioList.end() )
{
string sid( std::to_string(s.si.id) );
......@@ -960,12 +965,13 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor
jsens["default_val"] = s->default_val;
jsens["dbignore"] = s->dbignore;
jsens["nchanges"] = s->nchanges;
jsens["calibration"] = {
{ "cmin",s->ci.minCal},
{ "cmax",s->ci.maxCal},
{ "rmin",s->ci.minRaw},
{ "rmax",s->ci.maxRaw},
{ "precision",s->ci.precision}
jsens["calibration"] =
{
{ "cmin", s->ci.minCal},
{ "cmax", s->ci.maxCal},
{ "rmin", s->ci.minRaw},
{ "rmax", s->ci.maxRaw},
{ "precision", s->ci.precision}
};
// ::CORBA::Boolean undefined;
......@@ -984,7 +990,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
size_t offset = 0;
size_t limit = 0;
for( const auto& p: params )
for( const auto& p : params )
{
if( p.first == "offset" )
offset = uni_atoi(p.second);
......@@ -994,7 +1000,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
size_t endnum = offset + limit;
for( auto it=myioBegin(); it!=myioEnd(); ++it,num++ )
for( auto it = myioBegin(); it != myioEnd(); ++it, num++ )
{
if( limit > 0 && num >= endnum )
break;
......@@ -1002,7 +1008,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
if( offset > 0 && num < offset )
continue;
getSensorInfo(jdata, it->second,false);
getSensorInfo(jdata, it->second, false);
}
jdata["count"] = num;
......
......@@ -88,10 +88,12 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
{
std::lock_guard<std::mutex> lock(lostConsumersMutex);
if( lostConsumers.size() > 0 )
{
inf << "-------------------------- lost consumers list [maxAttemtps=" << maxAttemtps << "] ------------------" << endl;
for( const auto& l: lostConsumers )
for( const auto& l : lostConsumers )
{
inf << " " << "(" << setw(6) << l.first << ")"
<< setw(35) << std::left << ORepHelpers::getShortName(oind->getMapName(l.first))
......@@ -99,6 +101,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
<< endl;
}
}
inf << "----------------------------------------------------------------------------------" << endl;
}
......@@ -200,7 +203,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
{
uniset_rwmutex_wrlock l(lst.mut);
for( auto&& it : lst.clst )
for( auto && it : lst.clst )
{
if( it.id == ci.id && it.node == ci.node )
{
......@@ -211,7 +214,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что заказчик опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false;
return false;
......@@ -233,7 +237,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что клиент опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false;
return true;
......@@ -547,6 +552,7 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag
{
std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto& c = lostConsumers[li->id];
// если уже выставлен флаг что "заказчик" пропал, то не надо увеличивать "счётчик"
// видимо мы уже зафиксировали его пропажу на другом датчике...
if( !c.lost )
......@@ -1172,7 +1178,7 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
{
nlohmann::json jdata = IOController::httpHelp(p);
jdata[myname]["help"]["consumers"]["desc"] = "get consumers list";
jdata[myname]["help"]["consumers"]["params"] = {"sensor1,sensor2,sensor3","get consumers for sensors"};
jdata[myname]["help"]["consumers"]["params"] = {"sensor1,sensor2,sensor3", "get consumers for sensors"};
jdata[myname]["help"]["lost"]["desc"] = "get lost consumers list";
return std::move(jdata);
}
......@@ -1180,12 +1186,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
nlohmann::json IONotifyController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{
if( req == "consumers" )
return request_consumers(req,p);
return request_consumers(req, p);
if( req == "lost" )
return request_lost(req,p);
return request_lost(req, p);
return IOController::httpRequest(req,p);
return IOController::httpRequest(req, p);
}
// -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request_consumers( const string& req, const Poco::URI::QueryParameters& p )
......@@ -1198,6 +1204,7 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
auto oind = uniset_conf()->oind;
std::list<ParamSInfo> slist;
if( p.size() > 0 )
{
if( !p[0].first.empty() )
......@@ -1218,9 +1225,10 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
{
auto& jnotfound = json[myname]["notfound"];
for( const auto& s: slist )
for( const auto& s : slist )
{
auto a = askIOList.find(s.si.id);
if( a == askIOList.end() )
{
jnotfound.push_back(std::to_string(s.si.id));
......@@ -1228,15 +1236,16 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
}
// Включаем в ответ все, даже если список заказчиков пустой
jdata.push_back( getConsumers(a->first,a->second,false) );
jdata.push_back( getConsumers(a->first, a->second, false) );
}
}
else // Проход по всему списку
{
for( auto&& a : askIOList )
for( auto && a : askIOList )
{
// добавляем только датчики с непустым списком заказчиков
auto jret = getConsumers(a.first,a.second,true);
auto jret = getConsumers(a.first, a.second, true);
if( !jret.empty() )
jdata.push_back( std::move(jret) );
}
......@@ -1287,7 +1296,7 @@ nlohmann::json IONotifyController::request_lost( const string& req, const Poco::
std::lock_guard<std::mutex> lock(lostConsumersMutex);
for( const auto& c: lostConsumers )
for( const auto& c : lostConsumers )
{
string cid( std::to_string(c.first) );
auto& jcons = jdata[cid];
......
......@@ -359,7 +359,8 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
continue;
IOController_i::SensorInfo si;
if( !getBaseInfo(xml,it.getCurrent(),si) )
if( !getBaseInfo(xml, it.getCurrent(), si) )
{
ostringstream err;
err << ic->getName()
......
......@@ -118,7 +118,7 @@ const Poco::Timespan UniSetTimer::millisecToPoco( const timeout_t msec ) noexcep
if( msec == WaitUpTime )
{
// int days, int hours, int minutes, int seconds, int microSeconds
return Poco::Timespan(std::numeric_limits<int>::max(),0,0,0,0);
return Poco::Timespan(std::numeric_limits<int>::max(), 0, 0, 0, 0);
}
// msec --> usec
......@@ -130,7 +130,7 @@ const Poco::Timespan UniSetTimer::microsecToPoco( const timeout_t usec ) noexcep
if( usec == WaitUpTime )
{
// int days, int hours, int minutes, int seconds, int microSeconds
return Poco::Timespan(std::numeric_limits<int>::max(),0,0,0,0);
return Poco::Timespan(std::numeric_limits<int>::max(), 0, 0, 0, 0);
}
return Poco::Timespan( long(usec / 1000000), long(usec % 1000000) );
......
......@@ -30,9 +30,9 @@
namespace uniset
{
//--------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, const Message::TypeOfMessage& t )
{
//--------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, const Message::TypeOfMessage& t )
{
if( t == Message::Unused )
return os << "Unused";
......@@ -49,41 +49,41 @@ namespace uniset
return os << "Timer";
return os << "Unkown";
}
//--------------------------------------------------------------------------------------------
Message::Message() noexcept:
}
//--------------------------------------------------------------------------------------------
Message::Message() noexcept:
type(Unused), priority(Medium),
node( uniset::uniset_conf() ? uniset::uniset_conf()->getLocalNode() : DefaultObjectId ),
supplier(DefaultObjectId),
consumer(DefaultObjectId)
{
{
tm = uniset::now_to_timespec();
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
VoidMessage::VoidMessage( const TransportMessage& tm ) noexcept:
VoidMessage::VoidMessage( const TransportMessage& tm ) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
assert(sizeof(VoidMessage) >= sizeof(uniset::RawDataOfTransportMessage));
memcpy(this, &tm.data, sizeof(tm.data));
consumer = tm.consumer;
}
}
VoidMessage::VoidMessage() noexcept
{
VoidMessage::VoidMessage() noexcept
{
assert(sizeof(VoidMessage) >= sizeof(uniset::RawDataOfTransportMessage));
}
}
//--------------------------------------------------------------------------------------------
SensorMessage::SensorMessage() noexcept:
//--------------------------------------------------------------------------------------------
SensorMessage::SensorMessage() noexcept:
id(DefaultObjectId),
value(0),
undefined(false),
sensor_type(UniversalIO::DI),
threshold(false),
tid(uniset::DefaultThresholdId)
{
{
type = Message::SensorInfo;
sm_tv = tm; // или инициализировать нулём ?
ci.minRaw = 0;
......@@ -91,9 +91,9 @@ namespace uniset
ci.minCal = 0;
ci.maxCal = 0;
ci.precision = 0;
}
}
SensorMessage::SensorMessage(ObjectId id, long value, const IOController_i::CalibrateInfo& ci,
SensorMessage::SensorMessage(ObjectId id, long value, const IOController_i::CalibrateInfo& ci,
Priority priority,
UniversalIO::IOType st, ObjectId consumer) noexcept:
id(id),
......@@ -103,50 +103,50 @@ namespace uniset
ci(ci),
threshold(false),
tid(uniset::DefaultThresholdId)
{
{
type = Message::SensorInfo;
this->priority = priority;
this->consumer = consumer;
sm_tv = tm;
}
}
SensorMessage::SensorMessage( int dummy ) noexcept:
SensorMessage::SensorMessage( int dummy ) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
type = Message::SensorInfo;
}
}
SensorMessage::SensorMessage(const VoidMessage* msg) noexcept:
SensorMessage::SensorMessage(const VoidMessage* msg) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy(this, msg, sizeof(*this));
assert(this->type == Message::SensorInfo);
}
//--------------------------------------------------------------------------------------------
SystemMessage::SystemMessage() noexcept:
}
//--------------------------------------------------------------------------------------------
SystemMessage::SystemMessage() noexcept:
command(SystemMessage::Unknown)
{
{
memset(data, 0, sizeof(data));
type = Message::SysCommand;
}
}
SystemMessage::SystemMessage(Command command, Priority priority, ObjectId consumer) noexcept:
SystemMessage::SystemMessage(Command command, Priority priority, ObjectId consumer) noexcept:
command(command)
{
{
type = Message::SysCommand;
this->priority = priority;
this->consumer = consumer;
}
}
SystemMessage::SystemMessage(const VoidMessage* msg) noexcept:
SystemMessage::SystemMessage(const VoidMessage* msg) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy(this, msg, sizeof(*this));
assert(this->type == Message::SysCommand);
}
//--------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, const SystemMessage::Command& c )
{
}
//--------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, const SystemMessage::Command& c )
{
if( c == SystemMessage::Unknown )
return os << "Unknown";
......@@ -172,36 +172,36 @@ namespace uniset
return os << "LogRotate";
return os;
}
//--------------------------------------------------------------------------------------------
TimerMessage::TimerMessage():
}
//--------------------------------------------------------------------------------------------
TimerMessage::TimerMessage():
id(uniset::DefaultTimerId)
{
{
type = Message::Timer;
}
}
TimerMessage::TimerMessage(uniset::TimerId id, Priority prior, ObjectId cons):
TimerMessage::TimerMessage(uniset::TimerId id, Priority prior, ObjectId cons):
id(id)
{
{
type = Message::Timer;
this->consumer = cons;
}
}
TimerMessage::TimerMessage(const VoidMessage* msg) noexcept:
TimerMessage::TimerMessage(const VoidMessage* msg) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy(this, msg, sizeof(*this));
assert(this->type == Message::Timer);
}
//--------------------------------------------------------------------------------------------
ConfirmMessage::ConfirmMessage( const VoidMessage* msg ) noexcept:
}
//--------------------------------------------------------------------------------------------
ConfirmMessage::ConfirmMessage( const VoidMessage* msg ) noexcept:
Message(1) // вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy(this, msg, sizeof(*this));
assert(this->type == Message::Confirm);
}
//--------------------------------------------------------------------------------------------
ConfirmMessage::ConfirmMessage(uniset::ObjectId in_sensor_id,
}
//--------------------------------------------------------------------------------------------
ConfirmMessage::ConfirmMessage(uniset::ObjectId in_sensor_id,
const double& in_sensor_value,
const timespec& in_sensor_time,
const timespec& in_confirm_time,
......@@ -212,12 +212,12 @@ namespace uniset
confirm_time(in_confirm_time),
broadcast(false),
forward(false)
{
{
type = Message::Confirm;
priority = in_priority;
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
} // end of namespace uniset
//--------------------------------------------------------------------------------------------
......@@ -10,14 +10,14 @@ class UTestSupplier:
public UHttp::IHttpRequest
{
public:
UTestSupplier(){}
virtual ~UTestSupplier(){}
UTestSupplier() {}
virtual ~UTestSupplier() {}
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& params ) override
{
nlohmann::json j;
for( const auto& p: params )
for( const auto& p : params )
j[p.first] = p.second;
j["test"] = 42;
......@@ -27,9 +27,10 @@ class UTestSupplier:
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override
{
nlohmann::json j;
j["test"]["help"] = {
{"cmd1","help for cmd1"},
{"cmd2","help for cmd2"}
j["test"]["help"] =
{
{"cmd1", "help for cmd1"},
{"cmd2", "help for cmd2"}
};
return j;
......@@ -47,8 +48,8 @@ class UTestRequestRegistry:
public UHttp::IHttpRequestRegistry
{
public:
UTestRequestRegistry(){}
virtual ~UTestRequestRegistry(){}
UTestRequestRegistry() {}
virtual ~UTestRequestRegistry() {}
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
......@@ -70,9 +71,10 @@ class UTestRequestRegistry:
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{
nlohmann::json j;
j["TestObject"]["help"] = {
{"cmd1","help for cmd1"},
{"cmd2","help for cmd2"}
j["TestObject"]["help"] =
{
{"cmd1", "help for cmd1"},
{"cmd2", "help for cmd2"}
};
return j;
......@@ -97,7 +99,7 @@ int main(int argc, const char** argv)
auto reg = std::make_shared<UTestRequestRegistry>();
auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg);
auto http = make_shared<UHttp::UHttpServer>(ireg,"localhost", 5555);
auto http = make_shared<UHttp::UHttpServer>(ireg, "localhost", 5555);
http->log()->level(Debug::ANY);
cout << "start http test server localhost:5555" << endl;
......
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