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();
}
// -------------------------------------------------------------------------
// "синтаксический сахар"..для логов
......
......@@ -34,9 +34,9 @@ class ModbusRTUMaster;
// -----------------------------------------------------------------------------
namespace MTR
{
// реализованные в данном интерфейсе типы данных
enum MTRType
{
// реализованные в данном интерфейсе типы данных
enum MTRType
{
mtUnknown,
mtT1,
mtT2,
......@@ -53,29 +53,29 @@ namespace MTR
mtF1,
mtT_Str16,
mtT_Str8
};
// -------------------------------------------------------------------------
std::string type2str( MTRType t ); /*!< преоразование строки в тип */
MTRType str2type( const std::string& s ); /*!< преобразование названия в строку */
size_t wsize( MTRType t ); /*!< длина данных в словах */
// -------------------------------------------------------------------------
// Информация
const ModbusRTU::ModbusData regModelNumber = 0x01;
const ModbusRTU::ModbusData regSerialNumber = 0x09;
std::string getModelNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr );
std::string getSerialNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr );
// -------------------------------------------------------------------------
// Настройки связи (чтение - read03, запись - write06)
const ModbusRTU::ModbusData regUpdateConfiguration = 53;
const ModbusRTU::ModbusData regAddress = 55;
const ModbusRTU::ModbusData regBaudRate = 56;
const ModbusRTU::ModbusData regStopBit = 57; /* 0 - Stop bit, 1 - Stop bits */
const ModbusRTU::ModbusData regParity = 58;
const ModbusRTU::ModbusData regDataBits = 59;
enum mtrBaudRate
{
};
// -------------------------------------------------------------------------
std::string type2str( MTRType t ); /*!< преоразование строки в тип */
MTRType str2type( const std::string& s ); /*!< преобразование названия в строку */
size_t wsize( MTRType t ); /*!< длина данных в словах */
// -------------------------------------------------------------------------
// Информация
const ModbusRTU::ModbusData regModelNumber = 0x01;
const ModbusRTU::ModbusData regSerialNumber = 0x09;
std::string getModelNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr );
std::string getSerialNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr );
// -------------------------------------------------------------------------
// Настройки связи (чтение - read03, запись - write06)
const ModbusRTU::ModbusData regUpdateConfiguration = 53;
const ModbusRTU::ModbusData regAddress = 55;
const ModbusRTU::ModbusData regBaudRate = 56;
const ModbusRTU::ModbusData regStopBit = 57; /* 0 - Stop bit, 1 - Stop bits */
const ModbusRTU::ModbusData regParity = 58;
const ModbusRTU::ModbusData regDataBits = 59;
enum mtrBaudRate
{
br1200 = 0,
br2400 = 1,
br4800 = 2,
......@@ -84,58 +84,58 @@ namespace MTR
br38400 = 5,
br57600 = 6,
br115200 = 7
};
};
enum mtrParity
{
enum mtrParity
{
mpNoParity = 0,
mpOddParity = 1,
mpEvenParity = 2
};
};
enum mtrDataBits
{
enum mtrDataBits
{
db8Bits = 0,
db7Bits = 1
};
bool setAddress( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusAddr newAddr );
bool setBaudRate( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrBaudRate br );
bool setStopBit( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, bool state );
bool setParity( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrParity p );
bool setDataBits( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrDataBits d );
ComPort::Parity get_parity( ModbusRTU::ModbusData data );
ComPort::Speed get_speed( ModbusRTU::ModbusData data );
// -------------------------------------------------------------------------
enum MTRError
{
};
bool setAddress( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusAddr newAddr );
bool setBaudRate( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrBaudRate br );
bool setStopBit( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, bool state );
bool setParity( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrParity p );
bool setDataBits( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrDataBits d );
ComPort::Parity get_parity( ModbusRTU::ModbusData data );
ComPort::Speed get_speed( ModbusRTU::ModbusData data );
// -------------------------------------------------------------------------
enum MTRError
{
mtrNoError,
mtrBadDeviceType,
mtrDontReadConfile,
mtrSendParamFailed,
mtrUnknownError
};
std::ostream& operator<<(std::ostream& os, MTRError& e );
// Настройка из конф. файла
MTRError update_configuration( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr,
};
std::ostream& operator<<(std::ostream& os, MTRError& e );
// Настройка из конф. файла
MTRError update_configuration( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr,
const std::string& mtrconfile, int verbose = 0 );
// ---------------------------
// вспомогательные функции и типы данных
typedef std::list<ModbusRTU::ModbusData> DataList;
typedef std::unordered_map<ModbusRTU::ModbusData, DataList> DataMap;
const int attempts = 3; //
static const ModbusRTU::ModbusData skip[] = {48, 49, 59}; // registers which should not write
bool send_param( ModbusRTUMaster* mb, DataMap& dmap, ModbusRTU::ModbusAddr addr, int verb );
bool read_param( const std::string& str, std::string& str1, std::string& str2 );
DataMap read_confile( const std::string& f );
void update_communication_params( ModbusRTU::ModbusAddr reg, ModbusRTU::ModbusData data,
// ---------------------------
// вспомогательные функции и типы данных
typedef std::list<ModbusRTU::ModbusData> DataList;
typedef std::unordered_map<ModbusRTU::ModbusData, DataList> DataMap;
const int attempts = 3; //
static const ModbusRTU::ModbusData skip[] = {48, 49, 59}; // registers which should not write
bool send_param( ModbusRTUMaster* mb, DataMap& dmap, ModbusRTU::ModbusAddr addr, int verb );
bool read_param( const std::string& str, std::string& str1, std::string& str2 );
DataMap read_confile( const std::string& f );
void update_communication_params( ModbusRTU::ModbusAddr reg, ModbusRTU::ModbusData data,
ModbusRTUMaster* mb, ModbusRTU::ModbusAddr& addr, int verb );
// -------------------------------------------------------------------------
static const size_t u2size = 2;
// -------------------------------------------------------------------------
class T1
{
// -------------------------------------------------------------------------
static const size_t u2size = 2;
// -------------------------------------------------------------------------
class T1
{
public:
T1(): val(0) {}
T1( unsigned short v ): val(v) {}
......@@ -154,11 +154,11 @@ namespace MTR
}
// ------------------------------------------
unsigned short val;
};
std::ostream& operator<<(std::ostream& os, T1& t );
// -------------------------------------------------------------------------
class T2
{
};
std::ostream& operator<<(std::ostream& os, T1& t );
// -------------------------------------------------------------------------
class T2
{
public:
T2(): val(0) {}
T2( signed short v ): val(v) {}
......@@ -177,11 +177,11 @@ namespace MTR
}
// ------------------------------------------
signed short val;
};
std::ostream& operator<<(std::ostream& os, T2& t );
// -------------------------------------------------------------------------
class T3
{
};
std::ostream& operator<<(std::ostream& os, T2& t );
// -------------------------------------------------------------------------
class T3
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -238,11 +238,11 @@ namespace MTR
}
T3mem raw;
};
std::ostream& operator<<(std::ostream& os, T3& t );
// --------------------------------------------------------------------------
class T4
{
};
std::ostream& operator<<(std::ostream& os, T3& t );
// --------------------------------------------------------------------------
class T4
{
public:
// ------------------------------------------
// конструкторы на разные случаи...
......@@ -250,7 +250,7 @@ namespace MTR
T4( uint16_t v1 ): raw(v1)
{
char c[3];
memcpy(c, &v1,2);
memcpy(c, &v1, 2);
c[2] = '\0';
sval = std::string(c);
}
......@@ -279,11 +279,11 @@ namespace MTR
// ------------------------------------------
std::string sval;
unsigned short raw;
};
std::ostream& operator<<(std::ostream& os, T4& t );
// --------------------------------------------------------------------------
class T5
{
};
std::ostream& operator<<(std::ostream& os, T4& t );
// --------------------------------------------------------------------------
class T5
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -342,11 +342,11 @@ namespace MTR
// ------------------------------------------
double val;
T5mem raw;
};
std::ostream& operator<<(std::ostream& os, T5& t );
// --------------------------------------------------------------------------
class T6
{
};
std::ostream& operator<<(std::ostream& os, T5& t );
// --------------------------------------------------------------------------
class T6
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -405,11 +405,11 @@ namespace MTR
// ------------------------------------------
double val = { 0.0 };
T6mem raw;
};
std::ostream& operator<<(std::ostream& os, T6& t );
// --------------------------------------------------------------------------
class T7
{
};
std::ostream& operator<<(std::ostream& os, T6& t );
// --------------------------------------------------------------------------
class T7
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -468,11 +468,11 @@ namespace MTR
// ------------------------------------------
double val = { 0.0 };
T7mem raw;
};
std::ostream& operator<<(std::ostream& os, T7& t );
// --------------------------------------------------------------------------
class T8
{
};
std::ostream& operator<<(std::ostream& os, T7& t );
// --------------------------------------------------------------------------
class T8
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -540,11 +540,11 @@ namespace MTR
}
// ------------------------------------------
T8mem raw;
};
std::ostream& operator<<(std::ostream& os, T8& t );
// --------------------------------------------------------------------------
class T9
{
};
std::ostream& operator<<(std::ostream& os, T8& t );
// --------------------------------------------------------------------------
class T9
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -612,11 +612,11 @@ namespace MTR
}
// ------------------------------------------
T9mem raw;
};
std::ostream& operator<<(std::ostream& os, T9& t );
// -------------------------------------------------------------------------
class T10
{
};
std::ostream& operator<<(std::ostream& os, T9& t );
// -------------------------------------------------------------------------
class T10
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -679,12 +679,12 @@ namespace MTR
}
// ------------------------------------------
T10mem raw;
};
std::ostream& operator<<(std::ostream& os, T10& t );
// --------------------------------------------------------------------------
};
std::ostream& operator<<(std::ostream& os, T10& t );
// --------------------------------------------------------------------------
class T16
{
class T16
{
public:
T16(): val(0) {}
T16( unsigned short v ): val(v)
......@@ -724,11 +724,11 @@ namespace MTR
unsigned short val = { 0 };
float fval = { 0.0 };
};
std::ostream& operator<<(std::ostream& os, T16& t );
// --------------------------------------------------------------------------
class T17
{
};
std::ostream& operator<<(std::ostream& os, T16& t );
// --------------------------------------------------------------------------
class T17
{
public:
T17(): val(0) {}
T17( signed short v ): val(v)
......@@ -772,11 +772,11 @@ namespace MTR
signed short val = { 0 };
float fval = { 0 };
};
std::ostream& operator<<(std::ostream& os, T17& t );
// --------------------------------------------------------------------------
class F1
{
};
std::ostream& operator<<(std::ostream& os, T17& t );
// --------------------------------------------------------------------------
class F1
{
public:
// ------------------------------------------
/*! тип хранения в памяти */
......@@ -835,11 +835,11 @@ namespace MTR
}
F1mem raw;
};
std::ostream& operator<<(std::ostream& os, F1& t );
// --------------------------------------------------------------------------
class T_Str16
{
};
std::ostream& operator<<(std::ostream& os, F1& t );
// --------------------------------------------------------------------------
class T_Str16
{
public:
// ------------------------------------------
// конструкторы на разные случаи...
......@@ -871,12 +871,12 @@ namespace MTR
}
// ------------------------------------------
std::string sval;
};
std::ostream& operator<<(std::ostream& os, T_Str16& t );
// --------------------------------------------------------------------------
};
std::ostream& operator<<(std::ostream& os, T_Str16& t );
// --------------------------------------------------------------------------
class T_Str8
{
class T_Str8
{
public:
// ------------------------------------------
// конструкторы на разные случаи...
......@@ -908,9 +908,9 @@ namespace MTR
}
// ------------------------------------------
std::string sval;
};
std::ostream& operator<<(std::ostream& os, T_Str8& t );
// --------------------------------------------------------------------------
};
std::ostream& operator<<(std::ostream& os, T_Str8& t );
// --------------------------------------------------------------------------
} // end of namespace MTR
// --------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -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
// -------------------------------------------------------------------------
......@@ -31,8 +31,8 @@ namespace uniset
namespace MTR
{
MTRType str2type( const std::string& s )
{
MTRType str2type( const std::string& s )
{
if( s == "T1" )
return mtT1;
......@@ -79,10 +79,10 @@ namespace MTR
return mtT_Str8;
return mtUnknown;
}
// -------------------------------------------------------------------------
string type2str( MTRType t )
{
}
// -------------------------------------------------------------------------
string type2str( MTRType t )
{
if( t == mtT1 )
return "T1";
......@@ -129,10 +129,10 @@ namespace MTR
return "T_Str8";
return "Unknown";
}
// -------------------------------------------------------------------------
size_t wsize( MTRType t )
{
}
// -------------------------------------------------------------------------
size_t wsize( MTRType t )
{
if( t == mtT1 )
return T1::wsize();
......@@ -179,10 +179,10 @@ namespace MTR
return T_Str8::wsize();
return 0;
}
// -------------------------------------------------------------------------
bool setAddress( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusAddr newAddr )
{
}
// -------------------------------------------------------------------------
bool setAddress( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, ModbusRTU::ModbusAddr newAddr )
{
try
{
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06( addr, regAddress, newAddr );
......@@ -195,10 +195,10 @@ namespace MTR
}
return false;
}
// -----------------------------------------------------------------------------
bool setBaudRate( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrBaudRate br )
{
}
// -----------------------------------------------------------------------------
bool setBaudRate( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrBaudRate br )
{
try
{
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06( addr, regBaudRate, br );
......@@ -211,10 +211,10 @@ namespace MTR
}
return false;
}
// -----------------------------------------------------------------------------
bool setStopBit( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, bool state )
{
}
// -----------------------------------------------------------------------------
bool setStopBit( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, bool state )
{
try
{
ModbusRTU::ModbusData dat = state ? 1 : 0;
......@@ -228,10 +228,10 @@ namespace MTR
}
return false;
}
// -----------------------------------------------------------------------------
bool setParity( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrParity p )
{
}
// -----------------------------------------------------------------------------
bool setParity( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrParity p )
{
try
{
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06( addr, regParity, p );
......@@ -244,10 +244,10 @@ namespace MTR
}
return false;
}
// -----------------------------------------------------------------------------
bool setDataBits( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrDataBits d )
{
}
// -----------------------------------------------------------------------------
bool setDataBits( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr, mtrDataBits d )
{
try
{
ModbusRTU::WriteSingleOutputRetMessage ret = mb->write06( addr, regDataBits, d );
......@@ -260,10 +260,10 @@ namespace MTR
}
return false;
}
// -----------------------------------------------------------------------------
std::string getModelNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr )
{
}
// -----------------------------------------------------------------------------
std::string getModelNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr )
{
try
{
ModbusRTU::ReadInputRetMessage ret = mb->read04( addr, regModelNumber, T_Str16::wsize() );
......@@ -275,10 +275,10 @@ namespace MTR
}
return "";
}
// -----------------------------------------------------------------------------
std::string getSerialNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr )
{
}
// -----------------------------------------------------------------------------
std::string getSerialNumber( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr addr )
{
try
{
ModbusRTU::ReadInputRetMessage ret = mb->read04( addr, regSerialNumber, T_Str8::wsize() );
......@@ -290,10 +290,10 @@ namespace MTR
}
return "";
}
// -----------------------------------------------------------------------------
DataMap read_confile( const std::string& f )
{
}
// -----------------------------------------------------------------------------
DataMap read_confile( const std::string& f )
{
DataMap dmap;
std::ifstream ifs(f.c_str(), std::ios::in);
......@@ -366,10 +366,10 @@ namespace MTR
ifs.close();
return dmap;
}
// --------------------------------------------------------------------------
bool read_param( const std::string& str, std::string& str1, std::string& str2 )
{
}
// --------------------------------------------------------------------------
bool read_param( const std::string& str, std::string& str1, std::string& str2 )
{
string::size_type pos = str.find('=');
if( pos == string::npos )
......@@ -378,10 +378,10 @@ namespace MTR
str1 = str.substr(0, pos);
str2 = str.substr(pos + 1, str.size());
return true;
}
// ------------------------------------------------------------------------------------------
ComPort::Speed get_speed( ModbusRTU::ModbusData data )
{
}
// ------------------------------------------------------------------------------------------
ComPort::Speed get_speed( ModbusRTU::ModbusData data )
{
static const ComPort::Speed speed_conv[] = { ComPort::ComSpeed1200,
ComPort::ComSpeed2400, ComPort::ComSpeed4800, ComPort::ComSpeed9600,
ComPort::ComSpeed19200, ComPort::ComSpeed38400, ComPort::ComSpeed57600,
......@@ -392,10 +392,10 @@ namespace MTR
return ComPort::ComSpeed0;
return speed_conv[data];
}
// ------------------------------------------------------------------------------------------
ComPort::Parity get_parity( ModbusRTU::ModbusData data )
{
}
// ------------------------------------------------------------------------------------------
ComPort::Parity get_parity( ModbusRTU::ModbusData data )
{
static const ComPort::Parity parity_conv[] =
{
ComPort::NoParity, ComPort::Odd, ComPort::Even
......@@ -405,11 +405,11 @@ namespace MTR
return ComPort::NoParity;
return parity_conv[data];
}
// ------------------------------------------------------------------------------------------
void update_communication_params( ModbusRTU::ModbusAddr reg, ModbusRTU::ModbusData data,
}
// ------------------------------------------------------------------------------------------
void update_communication_params( ModbusRTU::ModbusAddr reg, ModbusRTU::ModbusData data,
ModbusRTUMaster* mb, ModbusRTU::ModbusAddr& addr, int verb )
{
{
if( reg == regAddress )
{
addr = data;
......@@ -454,10 +454,10 @@ namespace MTR
cout << "(mtr-setup): parity is set to "
<< (data ? ((data == 1) ? "odd" : "even") : "no") << endl;
}
}
// ------------------------------------------------------------------------------------------
bool send_param( ModbusRTUMaster* mb, DataMap& dmap, ModbusRTU::ModbusAddr addr, int verb )
{
}
// ------------------------------------------------------------------------------------------
bool send_param( ModbusRTUMaster* mb, DataMap& dmap, ModbusRTU::ModbusAddr addr, int verb )
{
if( !mb )
{
cerr << "(MTR::send_param): mb=NULL!" << endl;
......@@ -544,11 +544,11 @@ namespace MTR
cout << "(mtr-setup): not save parameters " << endl;
return false;
}
// ------------------------------------------------------------------------------------------
MTR::MTRError update_configuration( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr slaveaddr,
}
// ------------------------------------------------------------------------------------------
MTR::MTRError update_configuration( ModbusRTUMaster* mb, ModbusRTU::ModbusAddr slaveaddr,
const std::string& mtrconfile, int verb )
{
{
std::string m = MTR::getModelNumber(mb, slaveaddr);
if( m != "MTR315Transducer" && m != "MTR3-3Transducer" )
......@@ -566,10 +566,10 @@ namespace MTR
}
return send_param(mb, dmap, slaveaddr, verb) ? mtrNoError : mtrSendParamFailed;
}
// ------------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MTR::MTRError& e )
{
}
// ------------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MTR::MTRError& e )
{
switch(e)
{
case mtrNoError:
......@@ -594,88 +594,88 @@ namespace MTR
}
return os;
}
// ------------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MTR::T1& t )
{
}
// ------------------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MTR::T1& t )
{
return os << t.val;
}
std::ostream& operator<<(std::ostream& os, MTR::T2& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T2& t )
{
return os << t.val;
}
std::ostream& operator<<(std::ostream& os, MTR::T3& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T3& t )
{
return os << (long)(t);
}
std::ostream& operator<<(std::ostream& os, MTR::T4& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T4& t )
{
return os << t.sval;
}
std::ostream& operator<<(std::ostream& os, MTR::T5& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T5& t )
{
return os << t.raw.u2.val << " * 10^" << (int)t.raw.u2.exp
<< " [" << t.val << "]";
}
std::ostream& operator<<(std::ostream& os, MTR::T6& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T6& t )
{
return os << t.raw.u2.val << " * 10^" << (int)t.raw.u2.exp
<< " [" << t.val << "]";
}
std::ostream& operator<<(std::ostream& os, MTR::T7& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T7& t )
{
return os << t.val
<< " [" << ( t.raw.u2.ic == 0xFF ? "CAP" : "IND" ) << "|"
<< ( t.raw.u2.ie == 0xFF ? "EXP" : "IMP" ) << "]";
}
std::ostream& operator<<(std::ostream& os, MTR::T8& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T8& t )
{
std::ios_base::fmtflags old_flags = os.flags();
os << setfill('0') << hex
<< setw(2) << t.hour() << ":" << setw(2) << t.min()
<< " " << setw(2) << t.day() << "/" << setw(2) << t.mon();
os.setf(old_flags);
return os;
}
std::ostream& operator<<(std::ostream& os, MTR::T9& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T9& t )
{
std::ios_base::fmtflags old_flags = os.flags();
os << setfill('0') << hex
<< setw(2) << t.hour() << ":" << setw(2) << t.min()
<< ":" << setw(2) << t.sec() << "." << setw(2) << t.ssec();
os.setf(old_flags);
return os;
}
std::ostream& operator<<(std::ostream& os, MTR::T10& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T10& t )
{
std::ios_base::fmtflags old_flags = os.flags();
os << setfill('0') << dec
<< setw(4) << t.year() << "/" << setw(2) << t.mon()
<< "/" << setw(2) << t.day();
os.setf(old_flags);
return os;
}
std::ostream& operator<<(std::ostream& os, MTR::T16& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T16& t )
{
return os << t.fval;
}
std::ostream& operator<<(std::ostream& os, MTR::T17& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T17& t )
{
return os << t.fval;
}
std::ostream& operator<<(std::ostream& os, MTR::F1& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::F1& t )
{
return os << t.raw.val;
}
std::ostream& operator<<(std::ostream& os, MTR::T_Str8& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T_Str8& t )
{
return os << t.sval;
}
std::ostream& operator<<(std::ostream& os, MTR::T_Str16& t )
{
}
std::ostream& operator<<(std::ostream& os, MTR::T_Str16& t )
{
return os << t.sval;
}
// ------------------------------------------------------------------------------------------
}
// ------------------------------------------------------------------------------------------
} // end of namespace MTR
} // end of namespace uniset
// -----------------------------------------------------------------------------
......@@ -32,28 +32,28 @@ using namespace uniset;
// -----------------------------------------------------------------------------
UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла)
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables (public and proteced)
// variables (public and proteced)
// ------------------
active(false),
// ------------------
active(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
end_private(false)
end_private(false)
{
mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception( string(myname+": init failed!!!") );
throw uniset::Exception( string(myname + ": init failed!!!") );
}
// -----------------------------------------------------------------------------
// ( val, confval, default val )
......@@ -61,6 +61,7 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{
if( !s1.empty() )
return s1;
if( !s2.empty() )
return s2;
......@@ -74,41 +75,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
auto conf = uniset_conf();
if( conf->getProp(cnode,prop).empty() )
if( conf->getProp(cnode, prop).empty() )
return conf->getLocalNode();
return conf->getNodeID(conf->getProp(cnode,prop));
return conf->getNodeID(conf->getProp(cnode, prop));
}
// -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ):
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables
// variables
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ),
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
forceOut(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)),
forceOut(false),
end_private(false)
end_private(false)
{
auto conf = uniset_conf();
if( uniset::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
if( uniset::findArgParam("--print-id-list", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 )
{
// abort();
// abort();
}
......@@ -124,10 +125,10 @@ end_private(false)
{
ostringstream s;
s << argprefix << "log";
conf->initLogStream(mylog,s.str());
conf->initLogStream(mylog, s.str());
}
loga = make_shared<LogAgregator>(myname+"-loga");
loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(mylog);
loga->add(ulog());
......@@ -145,12 +146,14 @@ end_private(false)
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
}
forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false);
forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() )
{
idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId )
{
ostringstream err;
......@@ -158,13 +161,14 @@ end_private(false)
throw uniset::SystemError(err.str());
}
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime>0 )
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime());
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime);
else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10);
}
// Инициализация значений
......@@ -173,16 +177,18 @@ end_private(false)
si.id = uniset::DefaultObjectId;
si.node = conf->getLocalNode();
sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec","150", 150);
sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec", "150", 150);
string s_resetTime("");
if( s_resetTime.empty() )
s_resetTime = "500";
resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"),conf->getProp(cnode,"resetMsgTime"),s_resetTime));
resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"), conf->getProp(cnode, "resetMsgTime"), s_resetTime));
ptResetMsg.setTiming(resetMsgTime);
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout","");
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", "");
if( sm_tout == 0 )
smReadyTimeout = 60000;
else if( sm_tout < 0 )
......@@ -190,7 +196,7 @@ end_private(false)
else
smReadyTimeout = sm_tout;
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),""));
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"), conf->getProp(cnode, "smTestID"), ""));
if( smTestID == DefaultObjectId )
......@@ -217,7 +223,7 @@ end_private(false)
// help надо выводить в конце, когда уже все переменные инициализированы по умолчанию
if( uniset::findArgParam("--" + argprefix + "help",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
if( uniset::findArgParam("--" + argprefix + "help", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 )
cout << help() << endl;
}
......@@ -269,7 +275,7 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
void UObject_SK::resetMsg()
{
mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages
// reset messages
}
// -----------------------------------------------------------------------------
......@@ -326,19 +332,23 @@ std::string UObject_SK::dumpIO()
s << endl;
int n = 0;
for( const auto& e: v_in )
for( const auto& e : v_in )
{
s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl;
}
s << endl;
n = 0;
for( const auto& e: v_out )
for( const auto& e : v_out )
{
s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl;
}
......@@ -411,14 +421,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{
case SystemMessage::WatchDog:
myinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() )
{
mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break;
}
case SystemMessage::StartUp:
{
ostate = "StartUp...";
try
{
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
......@@ -468,9 +481,10 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
// переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() );
if( !fname.empty() )
{
mylog->logFile(fname.c_str(),true);
mylog->logFile(fname.c_str(), true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
}
......@@ -524,14 +538,16 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << endl;
auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t: timers )
for( const auto& t : timers )
{
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 )
<< " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 )
<< endl;
}
inf << endl;
inf << vmon.pretty_str() << endl;
inf << endl;
......@@ -552,10 +568,11 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
if( logserv )
{
jdata["LogServer"] = {
{"host",logserv_host},
{"port",logserv_port},
{"state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" )},
jdata["LogServer"] =
{
{"host", logserv_host},
{"port", logserv_port},
{"state", ( logserv->isRunning() ? "RUNNIG" : "STOPPED" )},
{"info", logserv->httpGetShortInfo() }
};
}
......@@ -565,10 +582,12 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
jdata["io"] = httpDumpIO();
auto timers = getTimersList();
auto& jtm = jdata["Timers"];
jtm["count"] = timers.size();
for( const auto& t: timers )
for( const auto& t : timers )
{
std::string tid(to_string(t.id));
auto& jt = jtm[tid];
......@@ -576,20 +595,21 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
jt["name"] = getTimerName(t.id);
jt["msec"] = t.tmr.getInterval();
jt["timeleft"] = t.curTimeMS;
jt["tick"] = ( t.curTick>=0 ? t.curTick : -1 );
jt["tick"] = ( t.curTick >= 0 ? t.curTick : -1 );
}
auto vlist = vmon.getList();
auto& jvmon = jdata["Variables"];
for( const auto& v: vlist )
for( const auto& v : vlist )
jvmon[v.first] = v.second;
auto& jstat = jdata["Statistics"];
jstat["processingMessageCatchCount"] = processingMessageCatchCount;
auto& jsens = jstat["sensors"];
for( const auto& s: smStat )
for( const auto& s : smStat )
{
std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first)));
auto& js = jsens[sname];
......@@ -618,7 +638,7 @@ nlohmann::json UObject_SK::httpRequest( const std::string& req, const Poco::URI:
if( req == "log" )
return httpRequestLog(p);
return UniSetObject::httpRequest(req,p);
return UniSetObject::httpRequest(req, p);
}
// -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpRequestLog( const Poco::URI::QueryParameters& p )
......@@ -674,7 +694,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID,wait_msec) )
if( !ui->waitReady(_testID, wait_msec) )
{
ostringstream err;
err << myname
......@@ -683,10 +703,10 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit << err.str() << endl;
std::abort();
// throw uniset::SystemError(err.str());
// throw uniset::SystemError(err.str());
}
if( !ui->waitWorking(_testID,wait_msec) )
if( !ui->waitWorking(_testID, wait_msec) )
{
ostringstream err;
err << myname
......@@ -695,7 +715,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit << err.str() << endl;
std::abort();
// throw uniset::SystemError(err.str());
// throw uniset::SystemError(err.str());
}
}
// ----------------------------------------------------------------------------
......@@ -731,39 +751,42 @@ void UObject_SK::callback() noexcept
{
if( !active )
return;
try
{
// проверка таймеров
checkTimers(this);
if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) )
if( resetMsgTime > 0 && trResetMsg.hi(ptResetMsg.checkTime()) )
{
// cout << myname << ": ********* reset messages *********" << endl;
// cout << myname << ": ********* reset messages *********" << endl;
resetMsg();
}
// обработка сообщений (таймеров и т.п.)
for( unsigned int i=0; i<20; i++ )
for( unsigned int i = 0; i < 20; i++ )
{
auto m = receiveMessage();
if( !m )
break;
processingMessage(m.get());
updateOutputs(forceOut);
// updatePreviousValues();
// updatePreviousValues();
}
// Выполнение шага программы
step();
// "сердцебиение"
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() )
if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
{
try
{
ui->setValue(idHeartBeat,maxHeartBeat);
ui->setValue(idHeartBeat, maxHeartBeat);
ptHeartBeat.reset();
}
catch( const uniset::Exception& ex )
......@@ -803,7 +826,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
ui->setValue(_sid,_val);
ui->setValue(_sid, _val);
}
// -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force )
......@@ -825,7 +848,7 @@ void UObject_SK::initFromSM()
// -----------------------------------------------------------------------------
void UObject_SK::askSensor( uniset::ObjectId _sid, UniversalIO::UIOCommand _cmd, uniset::ObjectId _node )
{
ui->askRemoteSensor(_sid,_cmd,_node,getId());
ui->askRemoteSensor(_sid, _cmd, _node, getId());
}
// -----------------------------------------------------------------------------
long UObject_SK::getValue( uniset::ObjectId _sid )
......@@ -847,10 +870,12 @@ long UObject_SK::getValue( uniset::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{
PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() )
{
cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300);
if( activated )
break;
}
......@@ -870,7 +895,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{
mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception&ex )
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
......
......@@ -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:
......
......@@ -48,63 +48,63 @@ inline void msleep( unsigned int m )
/*! Определения базовых типов библиотеки UniSet (вспомогательные типы данных, константы, полезные функции) */
namespace uniset
{
class Configuration;
// ---------------------------------------------------------------
// Вспомогательные типы данных и константы
class Configuration;
// ---------------------------------------------------------------
// Вспомогательные типы данных и константы
const ObjectId DefaultObjectId = -1; /*!< Идентификатор объекта по умолчанию */
const ThresholdId DefaultThresholdId = -1; /*!< идентификатор порогов по умолчанию */
const ThresholdId DefaultTimerId = -1; /*!< идентификатор таймера по умолчанию */
const ObjectId DefaultObjectId = -1; /*!< Идентификатор объекта по умолчанию */
const ThresholdId DefaultThresholdId = -1; /*!< идентификатор порогов по умолчанию */
const ThresholdId DefaultTimerId = -1; /*!< идентификатор таймера по умолчанию */
const ObjectId AdminID = -2; /*!< сервисный идентификатор используемый утилитой admin */
const ObjectId AdminID = -2; /*!< сервисный идентификатор используемый утилитой admin */
typedef size_t KeyType; /*!< уникальный ключ объекта */
typedef size_t KeyType; /*!< уникальный ключ объекта */
/*! генератор уникального положительного ключа
/*! генератор уникального положительного ключа
* Уникальность гарантируется только для пары значений
* id и node.
* \warning что тут у нас с переполнением..
* \warning Уникальность генерируемого ключа еще не проверялась,
но нареканий по использованию тоже не было :)
* \todo Желательно продумать что-нибудь с использованием хэш.
*/
inline static KeyType key( const uniset::ObjectId id, const uniset::ObjectId node )
{
* \todo Желательно продумать что-нибудь с использованием хэш.
*/
inline static KeyType key( const uniset::ObjectId id, const uniset::ObjectId node )
{
return KeyType((id * node) + (id + 2 * node));
}
}
inline static KeyType key( const IOController_i::SensorInfo& si )
{
inline static KeyType key( const IOController_i::SensorInfo& si )
{
return key(si.id, si.node);
}
}
typedef std::list<std::string> ListObjectName; /*!< Список объектов типа ObjectName */
typedef std::list<std::string> ListObjectName; /*!< Список объектов типа ObjectName */
typedef ObjectId SysId;
typedef CORBA::Object_ptr ObjectPtr; /*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef CORBA::Object_var ObjectVar; /*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef ObjectId SysId;
typedef CORBA::Object_ptr ObjectPtr; /*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef CORBA::Object_var ObjectVar; /*!< Ссылка на объект регистрируемый в ObjectRepository */
UniversalIO::IOType getIOType( const std::string& s ) noexcept;
std::string iotype2str( const UniversalIO::IOType& t ) noexcept;
std::ostream& operator<<( std::ostream& os, const UniversalIO::IOType t );
std::ostream& operator<<( std::ostream& os, const IONotifyController_i::ThresholdInfo& ti );
std::ostream& operator<<( std::ostream& os, const IOController_i::ShortIOInfo& s );
std::ostream& operator<<( std::ostream& os, const IONotifyController_i::ThresholdState& s);
UniversalIO::IOType getIOType( const std::string& s ) noexcept;
std::string iotype2str( const UniversalIO::IOType& t ) noexcept;
std::ostream& operator<<( std::ostream& os, const UniversalIO::IOType t );
std::ostream& operator<<( std::ostream& os, const IONotifyController_i::ThresholdInfo& ti );
std::ostream& operator<<( std::ostream& os, const IOController_i::ShortIOInfo& s );
std::ostream& operator<<( std::ostream& os, const IONotifyController_i::ThresholdState& s);
/*! Команды для управления лампочками */
enum LampCommand
{
/*! Команды для управления лампочками */
enum LampCommand
{
lmpOFF = 0, /*!< выключить */
lmpON = 1, /*!< включить */
lmpBLINK = 2, /*!< мигать */
lmpBLINK2 = 3, /*!< мигать */
lmpBLINK3 = 4 /*!< мигать */
};
};
static const long ChannelBreakValue = std::numeric_limits<long>::max();
static const long ChannelBreakValue = std::numeric_limits<long>::max();
class IDList
{
class IDList
{
public:
IDList( std::vector<std::string>& v );
......@@ -136,11 +136,11 @@ namespace uniset
private:
std::list<ObjectId> lst;
};
};
/*! Информация об имени объекта */
struct ObjectInfo
{
/*! Информация об имени объекта */
struct ObjectInfo
{
ObjectInfo() noexcept:
id(DefaultObjectId),
repName(""), textName(""), data(0) {}
......@@ -154,83 +154,83 @@ namespace uniset
{
return (id < o.id);
}
};
};
typedef std::list<NodeInfo> ListOfNode;
typedef std::list<NodeInfo> ListOfNode;
/*! Запрещенные для использования в именах объектов символы */
const char BadSymbols[] = {'.', '/'};
/*! Запрещенные для использования в именах объектов символы */
const char BadSymbols[] = {'.', '/'};
// ---------------------------------------------------------------
// Различные преобразования
// ---------------------------------------------------------------
// Различные преобразования
//! Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
int uni_atoi( const char* str ) noexcept;
inline int uni_atoi( const std::string& str ) noexcept
{
//! Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
int uni_atoi( const char* str ) noexcept;
inline int uni_atoi( const std::string& str ) noexcept
{
return uni_atoi(str.c_str());
}
}
char* uni_strdup( const std::string& src );
char* uni_strdup( const std::string& src );
std::string timeToString(time_t tm = time(0), const std::string& brk = ":") noexcept; /*!< Преобразование времени в строку HH:MM:SS */
std::string dateToString(time_t tm = time(0), const std::string& brk = "/") noexcept; /*!< Преобразование даты в строку DD/MM/YYYY */
std::string timeToString(time_t tm = time(0), const std::string& brk = ":") noexcept; /*!< Преобразование времени в строку HH:MM:SS */
std::string dateToString(time_t tm = time(0), const std::string& brk = "/") noexcept; /*!< Преобразование даты в строку DD/MM/YYYY */
struct timeval to_timeval( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timeval */
struct timespec to_timespec( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timespec */
struct timespec now_to_timespec(); /*!< получение текущего времени */
struct timeval to_timeval( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timeval */
struct timespec to_timespec( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timespec */
struct timespec now_to_timespec(); /*!< получение текущего времени */
inline bool operator==( const struct timespec& r1, const struct timespec& r2 )
{
inline bool operator==( const struct timespec& r1, const struct timespec& r2 )
{
return ( r1.tv_sec == r2.tv_sec && r1.tv_nsec == r2.tv_nsec );
}
}
inline bool operator!=( const struct timespec& r1, const struct timespec& r2 )
{
inline bool operator!=( const struct timespec& r1, const struct timespec& r2 )
{
return !(operator==(r1, r2));
}
}
/*! Разбивка строки по указанному символу */
IDList explode( const std::string& str, char sep = ',' );
std::vector<std::string> explode_str( const std::string& str, char sep = ',' );
/*! Разбивка строки по указанному символу */
IDList explode( const std::string& str, char sep = ',' );
std::vector<std::string> explode_str( const std::string& str, char sep = ',' );
struct ParamSInfo
{
struct ParamSInfo
{
IOController_i::SensorInfo si;
long val;
std::string fname; // fullname id@node or id
};
};
/*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,...
/*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,...
Если '=' не указано, возвращается val=0
Если @node не указано, возвращается node=DefaultObjectId */
std::list<ParamSInfo> getSInfoList( const std::string& s, std::shared_ptr<uniset::Configuration> conf = nullptr );
std::list<ParamSInfo> getSInfoList( const std::string& s, std::shared_ptr<uniset::Configuration> conf = nullptr );
/*! Функция разбора строки вида: id1@node1,id2@node2,...
/*! Функция разбора строки вида: id1@node1,id2@node2,...
Если @node не указано, возвращается node=DefaultObjectId */
std::list<uniset::ConsumerInfo> getObjectsList( const std::string& s, std::shared_ptr<uniset::Configuration> conf = nullptr );
std::list<uniset::ConsumerInfo> getObjectsList( const std::string& s, std::shared_ptr<uniset::Configuration> conf = nullptr );
/*! проверка является текст в строке - числом..*/
bool is_digit( const std::string& s ) noexcept;
/*! проверка является текст в строке - числом..*/
bool is_digit( const std::string& s ) noexcept;
/*! замена всех вхождений подстроки
/*! замена всех вхождений подстроки
* \param src - исходная строка
* \param from - подстрока которая ищется (для замены)
* \param to - строка на которую будет сделана замена
*/
std::string replace_all( const std::string& src, const std::string& from, const std::string& to );
// ---------------------------------------------------------------
// Работа с командной строкой
*/
std::string replace_all( const std::string& src, const std::string& from, const std::string& to );
// ---------------------------------------------------------------
// Работа с командной строкой
/*! Получение параметра командной строки
/*! Получение параметра командной строки
\param name - название параметра
\param defval - значение, которое будет возвращено, если параметр не найден
*/
inline std::string getArgParam( const std::string& name,
*/
inline std::string getArgParam( const std::string& name,
int _argc, const char* const* _argv,
const std::string& defval = "" ) noexcept
{
{
for( int i = 1; i < (_argc - 1) ; i++ )
{
if( name == _argv[i] )
......@@ -238,24 +238,24 @@ namespace uniset
}
return defval;
}
}
inline int getArgInt( const std::string& name,
inline int getArgInt( const std::string& name,
int _argc, const char* const* _argv,
const std::string& defval = "" ) noexcept
{
{
return uni_atoi(getArgParam(name, _argc, _argv, defval));
}
}
/*! Проверка наличия параметра в командной строке
/*! Проверка наличия параметра в командной строке
\param name - название параметра
\param _argc - argc
\param _argv - argv
\return Возвращает -1, если параметр не найден.
Или позицию параметра, если найден.
*/
inline int findArgParam( const std::string& name, int _argc, const char* const* _argv )
{
*/
inline int findArgParam( const std::string& name, int _argc, const char* const* _argv )
{
for( int i = 1; i < _argc; i++ )
{
if( name == _argv[i] )
......@@ -263,46 +263,46 @@ namespace uniset
}
return -1;
}
}
// ---------------------------------------------------------------
// Калибровка
// ---------------------------------------------------------------
// Калибровка
std::ostream& operator<<( std::ostream& os, const IOController_i::CalibrateInfo& c );
std::ostream& operator<<( std::ostream& os, const IOController_i::CalibrateInfo& c );
// Функции калибровки значений
// raw - преобразуемое значение
// rawMin - минимальная граница исходного диапазона
// rawMax - максимальная граница исходного диапазона
// calMin - минимальная граница калиброванного диапазона
// calMin - минимальная граница калиброванного диапазона
// limit - обрезать итоговое значение по границам
float fcalibrate(float raw, float rawMin, float rawMax, float calMin, float calMax, bool limit = true );
long lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit = true );
// Функции калибровки значений
// raw - преобразуемое значение
// rawMin - минимальная граница исходного диапазона
// rawMax - максимальная граница исходного диапазона
// calMin - минимальная граница калиброванного диапазона
// calMin - минимальная граница калиброванного диапазона
// limit - обрезать итоговое значение по границам
float fcalibrate(float raw, float rawMin, float rawMax, float calMin, float calMax, bool limit = true );
long lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit = true );
// установка значения в нужный диапазон
long setinregion(long raw, long rawMin, long rawMax);
// установка значения вне диапазона
long setoutregion(long raw, long rawMin, long rawMax);
// установка значения в нужный диапазон
long setinregion(long raw, long rawMin, long rawMax);
// установка значения вне диапазона
long setoutregion(long raw, long rawMin, long rawMax);
// ---------------------------------------------------------------
// Всякие helper-ы
// ---------------------------------------------------------------
// Всякие helper-ы
bool file_exist( const std::string& filename );
bool file_exist( const std::string& filename );
// Проверка xml-узла на соответствие <...f_prop="f_val">,
// если не задано f_val, то проверяется, что просто f_prop!=""
bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
// Проверка xml-узла на соответствие <...f_prop="f_val">,
// если не задано f_val, то проверяется, что просто f_prop!=""
bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
template<typename InputIterator,
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
template<typename InputIterator,
typename OutputIterator,
typename Predicate>
OutputIterator copy_if(InputIterator begin,
OutputIterator copy_if(InputIterator begin,
InputIterator end,
OutputIterator destBegin,
Predicate p)
{
{
while( begin != end)
{
if( p(*begin) ) &destBegin++ = *begin;
......@@ -311,7 +311,8 @@ namespace uniset
}
return destBegin;
}
}
// -----------------------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------------------
#endif
......@@ -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
......
......@@ -23,18 +23,18 @@ namespace uniset
// -------------------------------------------------------------------------
namespace ModbusRTU
{
// Базовые типы
typedef uint8_t ModbusByte; /*!< modbus-байт */
const size_t BitsPerByte = 8;
typedef uint8_t ModbusAddr; /*!< адрес узла в modbus-сети */
typedef uint16_t ModbusData; /*!< размер данных в modbus-сообщениях */
const size_t BitsPerData = 16;
typedef uint16_t ModbusCRC; /*!< размер CRC16 в modbus-сообщениях */
// ---------------------------------------------------------------------
/*! Коды используемых функций (согласно описанию modbus) */
enum SlaveFunctionCode
{
// Базовые типы
typedef uint8_t ModbusByte; /*!< modbus-байт */
const size_t BitsPerByte = 8;
typedef uint8_t ModbusAddr; /*!< адрес узла в modbus-сети */
typedef uint16_t ModbusData; /*!< размер данных в modbus-сообщениях */
const size_t BitsPerData = 16;
typedef uint16_t ModbusCRC; /*!< размер CRC16 в modbus-сообщениях */
// ---------------------------------------------------------------------
/*! Коды используемых функций (согласно описанию modbus) */
enum SlaveFunctionCode
{
fnUnknown = 0x00,
fnReadCoilStatus = 0x01, /*!< read coil status */
fnReadInputStatus = 0x02, /*!< read input status */
......@@ -52,11 +52,11 @@ namespace ModbusRTU
fnRemoteService = 0x53, /*!< call remote service */
fnJournalCommand = 0x65, /*!< read,write,delete alarm journal */
fnFileTransfer = 0x66 /*!< file transfer */
};
};
/*! Коды диагностически подфункций (для запроса 0x08) */
enum DiagnosticsSubFunction
{
/*! Коды диагностически подфункций (для запроса 0x08) */
enum DiagnosticsSubFunction
{
subEcho = 0x00, /*!< (0) Return Query Data (echo) */
dgRestartComm = 0x01, /*!< (1) Restart Communications Option */
dgDiagReg = 0x02, /*!< (2) Return Diagnostic Register */
......@@ -75,26 +75,26 @@ namespace ModbusRTU
// = 0x13, /*!< RESERVED */
dgClearOverrunCounter = 0x14 /*!< (20) Clear Overrun Counter and FlagN.A. */
// 21 ...65535 RESERVED
};
};
typedef unsigned long RegID;
typedef unsigned long RegID;
/*! Получение уникального ID (hash?) на основе номера функции и регистра
/*! Получение уникального ID (hash?) на основе номера функции и регистра
* Требования к данной функции:
* 1. ID > диапазона возможных регистров (>65535)
* 2. одинаковые регистры, но разные функции должны давать разный ID
* 3. регистры идущие подряд, должны давать ID идущие тоже подряд
*/
RegID genRegID( const ModbusRTU::ModbusData r, const int fn );
*/
RegID genRegID( const ModbusRTU::ModbusData r, const int fn );
// определение размера данных в зависимости от типа сообщения
// возвращает -1 - если динамический размер сообщения или размер неизвестен
ssize_t szRequestDiagnosticData( DiagnosticsSubFunction f );
// определение размера данных в зависимости от типа сообщения
// возвращает -1 - если динамический размер сообщения или размер неизвестен
ssize_t szRequestDiagnosticData( DiagnosticsSubFunction f );
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum RDIObjectID
{
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum RDIObjectID
{
rdiVendorName = 0x0,
rdiProductCode = 0x1,
rdiMajorMinorRevision = 0x2,
......@@ -104,25 +104,25 @@ namespace ModbusRTU
rdiUserApplicationName = 0x6
// 0x07 .. 0x7F - reserved
// 0x80 .. 0xFF - optionaly defined (product dependant)
};
};
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum RDIRequestDeviceID
{
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum RDIRequestDeviceID
{
rdevMinNum = 0,
rdevBasicDevice = 0x1, // request to get the basic device identification (stream access)
rdevRegularDevice = 0x2, // request to get the regular device identification (stream access)
rdevExtentedDevice = 0x3, // request to get the extended device identification (stream access)
rdevSpecificDevice = 0x4, // request to get the extended device identification (stream access)
rdevMaxNum = 0x5
};
};
std::string rdi2str( int id );
// -----------------------------------------------------------------------
std::string rdi2str( int id );
// -----------------------------------------------------------------------
/*! различные базовые константы */
enum
{
/*! различные базовые константы */
enum
{
/*! максимальное количество данных в пакете (c учётом контрольной суммы) */
MAXLENPACKET = 508, /*!< максимальная длина пакета 512 - header(2) - CRC(2) */
BroadcastAddr = 255, /*!< адрес для широковещательных сообщений */
......@@ -131,46 +131,46 @@ namespace ModbusRTU
Связано с тем, что в ответе есть поле bcnt - количество байт
Соответственно максимум туда можно записать только 255
*/
};
const unsigned char MBErrMask = 0x80;
// ---------------------------------------------------------------------
uint16_t SWAPSHORT( uint16_t x );
// ---------------------------------------------------------------------
/*! Расчёт контрольной суммы */
ModbusCRC checkCRC( ModbusByte* start, size_t len );
const size_t szCRC = sizeof(ModbusCRC); /*!< размер данных для контрольной суммы */
// ---------------------------------------------------------------------
/*! вывод сообщения */
std::ostream& mbPrintMessage(std::ostream& os, ModbusByte* b, size_t len );
// -------------------------------------------------------------------------
ModbusAddr str2mbAddr( const std::string& val );
ModbusData str2mbData( const std::string& val );
std::string dat2str( const ModbusData dat );
std::string addr2str( const ModbusAddr addr );
std::string b2str( const ModbusByte b );
// -------------------------------------------------------------------------
float dat2f( const ModbusData dat1, const ModbusData dat2 );
// -------------------------------------------------------------------------
bool isWriteFunction( SlaveFunctionCode c );
bool isReadFunction( SlaveFunctionCode c );
// -------------------------------------------------------------------------
/*! Заголовок сообщений */
struct ModbusHeader
{
};
const unsigned char MBErrMask = 0x80;
// ---------------------------------------------------------------------
uint16_t SWAPSHORT( uint16_t x );
// ---------------------------------------------------------------------
/*! Расчёт контрольной суммы */
ModbusCRC checkCRC( ModbusByte* start, size_t len );
const size_t szCRC = sizeof(ModbusCRC); /*!< размер данных для контрольной суммы */
// ---------------------------------------------------------------------
/*! вывод сообщения */
std::ostream& mbPrintMessage(std::ostream& os, ModbusByte* b, size_t len );
// -------------------------------------------------------------------------
ModbusAddr str2mbAddr( const std::string& val );
ModbusData str2mbData( const std::string& val );
std::string dat2str( const ModbusData dat );
std::string addr2str( const ModbusAddr addr );
std::string b2str( const ModbusByte b );
// -------------------------------------------------------------------------
float dat2f( const ModbusData dat1, const ModbusData dat2 );
// -------------------------------------------------------------------------
bool isWriteFunction( SlaveFunctionCode c );
bool isReadFunction( SlaveFunctionCode c );
// -------------------------------------------------------------------------
/*! Заголовок сообщений */
struct ModbusHeader
{
ModbusAddr addr; /*!< адрес в сети */
ModbusByte func; /*!< код функции */
ModbusHeader(): addr(0), func(0) {}
} __attribute__((packed));
} __attribute__((packed));
const size_t szModbusHeader = sizeof(ModbusHeader);
const size_t szModbusHeader = sizeof(ModbusHeader);
std::ostream& operator<<(std::ostream& os, const ModbusHeader& m );
std::ostream& operator<<(std::ostream& os, const ModbusHeader* m );
// -----------------------------------------------------------------------
struct ADUHeader
{
std::ostream& operator<<(std::ostream& os, const ModbusHeader& m );
std::ostream& operator<<(std::ostream& os, const ModbusHeader* m );
// -----------------------------------------------------------------------
struct ADUHeader
{
ModbusRTU::ModbusData tID; /*!< transaction ID */
ModbusRTU::ModbusData pID; /*!< protocol ID */
ModbusRTU::ModbusData len; /*!< lenght */
......@@ -179,16 +179,16 @@ namespace ModbusRTU
void swapdata();
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, const ADUHeader& m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const ADUHeader& m );
// -----------------------------------------------------------------------
/*! Базовое (сырое) сообщение
/*! Базовое (сырое) сообщение
\todo Может переименовать ModbusMessage в TransportMessage?
*/
struct ModbusMessage
{
*/
struct ModbusMessage
{
ModbusMessage();
ModbusMessage( ModbusMessage&& ) = default;
......@@ -234,15 +234,15 @@ namespace ModbusRTU
// Это поле вспомогательное и игнорируется при пересылке
size_t dlen = { 0 }; /*!< фактическая длина сообщения */
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, const ModbusMessage& m );
std::ostream& operator<<(std::ostream& os, const ModbusMessage* m );
// -----------------------------------------------------------------------
/*! Ответ сообщающий об ошибке */
struct ErrorRetMessage:
std::ostream& operator<<(std::ostream& os, const ModbusMessage& m );
std::ostream& operator<<(std::ostream& os, const ModbusMessage* m );
// -----------------------------------------------------------------------
/*! Ответ сообщающий об ошибке */
struct ErrorRetMessage:
public ModbusHeader
{
{
ModbusByte ecode = { erNoError };
ModbusCRC crc = { 0 };
......@@ -264,13 +264,13 @@ namespace ModbusRTU
{
return sizeof(ModbusByte) + szCRC;
}
};
};
std::ostream& operator<<(std::ostream& os, ErrorRetMessage& m );
std::ostream& operator<<(std::ostream& os, ErrorRetMessage* m );
// -----------------------------------------------------------------------
struct DataBits
{
std::ostream& operator<<(std::ostream& os, ErrorRetMessage& m );
std::ostream& operator<<(std::ostream& os, ErrorRetMessage* m );
// -----------------------------------------------------------------------
struct DataBits
{
DataBits( ModbusByte b );
DataBits( std::string s ); // example "10001111"
DataBits();
......@@ -290,13 +290,13 @@ namespace ModbusRTU
}
std::bitset<BitsPerByte> b;
};
};
std::ostream& operator<<(std::ostream& os, DataBits& m );
std::ostream& operator<<(std::ostream& os, DataBits* m );
// -----------------------------------------------------------------------
struct DataBits16
{
std::ostream& operator<<(std::ostream& os, DataBits& m );
std::ostream& operator<<(std::ostream& os, DataBits* m );
// -----------------------------------------------------------------------
struct DataBits16
{
DataBits16( ModbusData d );
DataBits16( const std::string& s ); // example "1000111110001111"
DataBits16();
......@@ -316,15 +316,15 @@ namespace ModbusRTU
}
std::bitset<BitsPerData> b;
};
};
std::ostream& operator<<(std::ostream& os, DataBits16& m );
std::ostream& operator<<(std::ostream& os, DataBits16* m );
// -----------------------------------------------------------------------
/*! Запрос 0x01 */
struct ReadCoilMessage:
std::ostream& operator<<(std::ostream& os, DataBits16& m );
std::ostream& operator<<(std::ostream& os, DataBits16* m );
// -----------------------------------------------------------------------
/*! Запрос 0x01 */
struct ReadCoilMessage:
public ModbusHeader
{
{
ModbusData start = { 0 };
ModbusData count = { 0 };
ModbusCRC crc = { 0 };
......@@ -345,17 +345,17 @@ namespace ModbusRTU
return sizeof(ModbusData) * 2 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ReadCoilMessage& m );
std::ostream& operator<<(std::ostream& os, ReadCoilMessage* m );
std::ostream& operator<<(std::ostream& os, ReadCoilMessage& m );
std::ostream& operator<<(std::ostream& os, ReadCoilMessage* m );
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ на 0x01 */
struct ReadCoilRetMessage:
/*! Ответ на 0x01 */
struct ReadCoilRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< numbers of bytes */
ModbusByte data[MAXLENPACKET]; /*!< данные */
......@@ -416,15 +416,15 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
ModbusMessage transport_msg();
};
};
std::ostream& operator<<(std::ostream& os, ReadCoilRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadCoilRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x02 */
struct ReadInputStatusMessage:
std::ostream& operator<<(std::ostream& os, ReadCoilRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadCoilRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x02 */
struct ReadInputStatusMessage:
public ModbusHeader
{
{
ModbusData start = { 0 };
ModbusData count = { 0 };
ModbusCRC crc = { 0 };
......@@ -447,15 +447,15 @@ namespace ModbusRTU
return sizeof(ModbusData) * 2 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ReadInputStatusMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputStatusMessage* m );
// -----------------------------------------------------------------------
/*! Ответ на 0x02 */
struct ReadInputStatusRetMessage:
std::ostream& operator<<(std::ostream& os, ReadInputStatusMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputStatusMessage* m );
// -----------------------------------------------------------------------
/*! Ответ на 0x02 */
struct ReadInputStatusRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< numbers of bytes */
ModbusByte data[MAXLENPACKET]; /*!< данные */
......@@ -516,16 +516,16 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
ModbusMessage transport_msg();
};
};
std::ostream& operator<<(std::ostream& os, ReadInputStatusRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputStatusRetMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ReadInputStatusRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputStatusRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x03 */
struct ReadOutputMessage:
/*! Запрос 0x03 */
struct ReadOutputMessage:
public ModbusHeader
{
{
ModbusData start = { 0 };
ModbusData count = { 0 };
ModbusCRC crc = { 0 };
......@@ -546,15 +546,15 @@ namespace ModbusRTU
return sizeof(ModbusData) * 2 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ReadOutputMessage& m );
std::ostream& operator<<(std::ostream& os, ReadOutputMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для 0x03 */
struct ReadOutputRetMessage:
std::ostream& operator<<(std::ostream& os, ReadOutputMessage& m );
std::ostream& operator<<(std::ostream& os, ReadOutputMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для 0x03 */
struct ReadOutputRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< numbers of bytes */
ModbusData data[MAXLENPACKET / sizeof(ModbusData)]; /*!< данные */
......@@ -605,15 +605,15 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
size_t count = { 0 }; /*!< фактическое количество данных в сообщении */
};
};
std::ostream& operator<<(std::ostream& os, ReadOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x04 */
struct ReadInputMessage:
std::ostream& operator<<(std::ostream& os, ReadOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x04 */
struct ReadInputMessage:
public ModbusHeader
{
{
ModbusData start = { 0 };
ModbusData count = { 0 };
ModbusCRC crc = { 0 };
......@@ -634,16 +634,16 @@ namespace ModbusRTU
return sizeof(ModbusData) * 2 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ReadInputMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ReadInputMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для 0x04 */
struct ReadInputRetMessage:
/*! Ответ для 0x04 */
struct ReadInputRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< numbers of bytes */
ModbusData data[MAXLENPACKET / sizeof(ModbusData)]; /*!< данные */
......@@ -696,15 +696,15 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
size_t count = { 0 }; /*!< фактическое количество данных в сообщении */
};
};
std::ostream& operator<<(std::ostream& os, ReadInputRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос на запись 0x0F */
struct ForceCoilsMessage:
std::ostream& operator<<(std::ostream& os, ReadInputRetMessage& m );
std::ostream& operator<<(std::ostream& os, ReadInputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос на запись 0x0F */
struct ForceCoilsMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< стартовый адрес записи */
ModbusData quant = { 0 }; /*!< количество записываемых битов */
ModbusByte bcnt = { 0 }; /*!< количество байт данных */
......@@ -775,15 +775,15 @@ namespace ModbusRTU
*/
bool checkFormat() const;
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ForceCoilsMessage& m );
std::ostream& operator<<(std::ostream& os, ForceCoilsMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса на запись 0x0F */
struct ForceCoilsRetMessage:
std::ostream& operator<<(std::ostream& os, ForceCoilsMessage& m );
std::ostream& operator<<(std::ostream& os, ForceCoilsMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса на запись 0x0F */
struct ForceCoilsRetMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< записанный начальный адрес */
ModbusData quant = { 0 }; /*!< количество записанных битов */
ModbusCRC crc = { 0 };
......@@ -814,16 +814,16 @@ namespace ModbusRTU
{
return sizeof(ModbusData) * 2 + sizeof(ModbusCRC);
}
};
};
std::ostream& operator<<(std::ostream& os, ForceCoilsRetMessage& m );
std::ostream& operator<<(std::ostream& os, ForceCoilsRetMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ForceCoilsRetMessage& m );
std::ostream& operator<<(std::ostream& os, ForceCoilsRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос на запись 0x10 */
struct WriteOutputMessage:
/*! Запрос на запись 0x10 */
struct WriteOutputMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< стартовый адрес записи */
ModbusData quant = { 0 }; /*!< количество слов данных */
ModbusByte bcnt = { 0 }; /*!< количество байт данных */
......@@ -868,16 +868,16 @@ namespace ModbusRTU
*/
bool checkFormat() const;
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, WriteOutputMessage& m );
std::ostream& operator<<(std::ostream& os, WriteOutputMessage* m );
std::ostream& operator<<(std::ostream& os, WriteOutputMessage& m );
std::ostream& operator<<(std::ostream& os, WriteOutputMessage* m );
/*! Ответ для запроса на запись 0x10 */
struct WriteOutputRetMessage:
/*! Ответ для запроса на запись 0x10 */
struct WriteOutputRetMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< записанный начальный адрес */
ModbusData quant = { 0 }; /*!< количество записанных слов данных */
......@@ -908,15 +908,15 @@ namespace ModbusRTU
{
return sizeof(ModbusData) * 2 + sizeof(ModbusCRC);
}
};
};
std::ostream& operator<<(std::ostream& os, WriteOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, WriteOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x05 */
struct ForceSingleCoilMessage:
std::ostream& operator<<(std::ostream& os, WriteOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, WriteOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x05 */
struct ForceSingleCoilMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< стартовый адрес записи */
ModbusData data = { 0 }; /*!< команда ON - true | OFF - false */
ModbusCRC crc = { 0 }; /*!< контрольная сумма */
......@@ -957,17 +957,17 @@ namespace ModbusRTU
что quant и bcnt - совпадают...
*/
bool checkFormat() const;
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, ForceSingleCoilMessage& m );
std::ostream& operator<<(std::ostream& os, ForceSingleCoilMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ForceSingleCoilMessage& m );
std::ostream& operator<<(std::ostream& os, ForceSingleCoilMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса 0x05 */
struct ForceSingleCoilRetMessage:
/*! Ответ для запроса 0x05 */
struct ForceSingleCoilRetMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< записанный начальный адрес */
ModbusData data = { 0 }; /*!< данные */
ModbusCRC crc = { 0 };
......@@ -1003,16 +1003,16 @@ namespace ModbusRTU
{
return 2 * sizeof(ModbusData) + sizeof(ModbusCRC);
}
};
};
std::ostream& operator<<(std::ostream& os, ForceSingleCoilRetMessage& m );
std::ostream& operator<<(std::ostream& os, ForceSingleCoilRetMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ForceSingleCoilRetMessage& m );
std::ostream& operator<<(std::ostream& os, ForceSingleCoilRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос на запись одного регистра 0x06 */
struct WriteSingleOutputMessage:
/*! Запрос на запись одного регистра 0x06 */
struct WriteSingleOutputMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< стартовый адрес записи */
ModbusData data = { 0 }; /*!< данные */
ModbusCRC crc = { 0 }; /*!< контрольная сумма */
......@@ -1048,17 +1048,17 @@ namespace ModbusRTU
что quant и bcnt - совпадают...
*/
bool checkFormat();
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, WriteSingleOutputMessage& m );
std::ostream& operator<<(std::ostream& os, WriteSingleOutputMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, WriteSingleOutputMessage& m );
std::ostream& operator<<(std::ostream& os, WriteSingleOutputMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса на запись */
struct WriteSingleOutputRetMessage:
/*! Ответ для запроса на запись */
struct WriteSingleOutputRetMessage:
public ModbusHeader
{
{
ModbusData start = { 0 }; /*!< записанный начальный адрес */
ModbusData data = { 0 }; /*!< записанные данные */
ModbusCRC crc = { 0 };
......@@ -1089,15 +1089,15 @@ namespace ModbusRTU
{
return 2 * sizeof(ModbusData) + sizeof(ModbusCRC);
}
};
};
std::ostream& operator<<(std::ostream& os, WriteSingleOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, WriteSingleOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x08 */
struct DiagnosticMessage:
std::ostream& operator<<(std::ostream& os, WriteSingleOutputRetMessage& m );
std::ostream& operator<<(std::ostream& os, WriteSingleOutputRetMessage* m );
// -----------------------------------------------------------------------
/*! Запрос 0x08 */
struct DiagnosticMessage:
public ModbusHeader
{
{
ModbusData subf = { 0 };
ModbusData data[MAXLENPACKET / sizeof(ModbusData)]; /*!< данные */
......@@ -1148,26 +1148,26 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
size_t count = { 0 }; /*!< фактическое количество данных в сообщении */
};
std::ostream& operator<<(std::ostream& os, DiagnosticMessage& m );
std::ostream& operator<<(std::ostream& os, DiagnosticMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для 0x08 */
struct DiagnosticRetMessage:
};
std::ostream& operator<<(std::ostream& os, DiagnosticMessage& m );
std::ostream& operator<<(std::ostream& os, DiagnosticMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для 0x08 */
struct DiagnosticRetMessage:
public DiagnosticMessage
{
{
DiagnosticRetMessage( const ModbusMessage& m );
DiagnosticRetMessage( const DiagnosticMessage& m );
DiagnosticRetMessage( ModbusAddr a, DiagnosticsSubFunction subf, ModbusData d = 0 );
};
};
std::ostream& operator<<(std::ostream& os, DiagnosticRetMessage& m );
std::ostream& operator<<(std::ostream& os, DiagnosticRetMessage* m );
// -----------------------------------------------------------------------
/*! Modbus Encapsulated Interface (0x2B). Read Device Identification (0x0E) */
struct MEIMessageRDI:
std::ostream& operator<<(std::ostream& os, DiagnosticRetMessage& m );
std::ostream& operator<<(std::ostream& os, DiagnosticRetMessage* m );
// -----------------------------------------------------------------------
/*! Modbus Encapsulated Interface (0x2B). Read Device Identification (0x0E) */
struct MEIMessageRDI:
public ModbusHeader
{
{
ModbusByte type; /*!< for RDI must be 0x0E */
ModbusByte devID; /*!< Read Device ID code */
ModbusByte objID; /*!< Object Id */
......@@ -1201,28 +1201,28 @@ namespace ModbusRTU
// вспомогательные функции
bool checkFormat() const;
} __attribute__((packed));
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MEIMessageRDI& m );
std::ostream& operator<<(std::ostream& os, MEIMessageRDI* m );
// -----------------------------------------------------------------------
} __attribute__((packed));
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MEIMessageRDI& m );
std::ostream& operator<<(std::ostream& os, MEIMessageRDI* m );
// -----------------------------------------------------------------------
struct RDIObjectInfo
{
struct RDIObjectInfo
{
RDIObjectInfo(): id(0), val("") {}
RDIObjectInfo( ModbusByte id, const std::string& v ): id(id), val(v) {}
RDIObjectInfo( ModbusByte id, const ModbusByte* dat, ModbusByte len );
ModbusByte id;
std::string val;
};
};
typedef std::list<RDIObjectInfo> RDIObjectList;
typedef std::list<RDIObjectInfo> RDIObjectList;
/*! Ответ для 0x2B/0x0E */
struct MEIMessageRetRDI:
/*! Ответ для 0x2B/0x0E */
struct MEIMessageRetRDI:
public ModbusHeader
{
{
ModbusByte type; /*!< 0x0E */
ModbusByte devID; /*!< Read Device ID code */
ModbusByte conformity; /*!< Conformity level (0x01 or 0x02 or 0x03 or 0x81 or 0x82 or 0x83) */
......@@ -1277,19 +1277,19 @@ namespace ModbusRTU
ModbusMessage transport_msg();
size_t bcnt = { 0 }; /*! размер данных в байтах, внутреннее служебное поле */
};
};
std::ostream& operator<<(std::ostream& os, MEIMessageRetRDI& m );
std::ostream& operator<<(std::ostream& os, MEIMessageRetRDI* m );
std::ostream& operator<<(std::ostream& os, RDIObjectList& dl );
std::ostream& operator<<(std::ostream& os, RDIObjectList* dl );
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, MEIMessageRetRDI& m );
std::ostream& operator<<(std::ostream& os, MEIMessageRetRDI* m );
std::ostream& operator<<(std::ostream& os, RDIObjectList& dl );
std::ostream& operator<<(std::ostream& os, RDIObjectList* dl );
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Чтение информации об ошибке */
struct JournalCommandMessage:
/*! Чтение информации об ошибке */
struct JournalCommandMessage:
public ModbusHeader
{
{
ModbusData cmd = { 0 }; /*!< код операции */
ModbusData num = { 0 }; /*!< номер записи */
ModbusCRC crc = { 0 };
......@@ -1304,15 +1304,15 @@ namespace ModbusRTU
return sizeof(ModbusByte) * 4 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, JournalCommandMessage& m );
std::ostream& operator<<(std::ostream& os, JournalCommandMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса на чтение ошибки */
struct JournalCommandRetMessage:
std::ostream& operator<<(std::ostream& os, JournalCommandMessage& m );
std::ostream& operator<<(std::ostream& os, JournalCommandMessage* m );
// -----------------------------------------------------------------------
/*! Ответ для запроса на чтение ошибки */
struct JournalCommandRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< numbers of bytes */
// ModbusByte data[MAXLENPACKET-1]; /*!< данные */
......@@ -1353,31 +1353,31 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
size_t count = { 0 }; /*!< фактическое количество данных в сообщении */
};
};
std::ostream& operator<<(std::ostream& os, JournalCommandRetMessage& m );
std::ostream& operator<<(std::ostream& os, JournalCommandRetMessage* m );
// -----------------------------------------------------------------------
/*! ответ в случае необходимости подтверждения команды
std::ostream& operator<<(std::ostream& os, JournalCommandRetMessage& m );
std::ostream& operator<<(std::ostream& os, JournalCommandRetMessage* m );
// -----------------------------------------------------------------------
/*! ответ в случае необходимости подтверждения команды
(просто пакует в JournalCommandRetMessage код команды и ошибки )
*/
struct JournalCommandRetOK:
*/
struct JournalCommandRetOK:
public JournalCommandRetMessage
{
{
// -------------
JournalCommandRetOK( ModbusAddr _from );
void set( ModbusData cmd, ModbusData ecode );
static void set( JournalCommandRetMessage& m, ModbusData cmd, ModbusData ecode );
};
};
std::ostream& operator<<(std::ostream& os, JournalCommandRetOK& m );
std::ostream& operator<<(std::ostream& os, JournalCommandRetOK* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, JournalCommandRetOK& m );
std::ostream& operator<<(std::ostream& os, JournalCommandRetOK* m );
// -----------------------------------------------------------------------
/*! Установка времени */
struct SetDateTimeMessage:
/*! Установка времени */
struct SetDateTimeMessage:
public ModbusHeader
{
{
ModbusByte hour = { 0 }; /*!< часы [0..23] */
ModbusByte min = { 0 }; /*!< минуты [0..59] */
ModbusByte sec = { 0 }; /*!< секунды [0..59] */
......@@ -1406,16 +1406,16 @@ namespace ModbusRTU
return sizeof(ModbusByte) * 7 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, SetDateTimeMessage& m );
std::ostream& operator<<(std::ostream& os, SetDateTimeMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, SetDateTimeMessage& m );
std::ostream& operator<<(std::ostream& os, SetDateTimeMessage* m );
// -----------------------------------------------------------------------
/*! Ответ (просто повторяет запрос) */
struct SetDateTimeRetMessage:
/*! Ответ (просто повторяет запрос) */
struct SetDateTimeRetMessage:
public SetDateTimeMessage
{
{
// ------- from slave -------
SetDateTimeRetMessage( const ModbusMessage& m );
......@@ -1429,13 +1429,13 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
ModbusMessage transport_msg();
};
// -----------------------------------------------------------------------
};
// -----------------------------------------------------------------------
/*! Вызов удалённого сервиса */
struct RemoteServiceMessage:
/*! Вызов удалённого сервиса */
struct RemoteServiceMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< количество байт */
/*! данные */
......@@ -1461,14 +1461,14 @@ namespace ModbusRTU
/*! узнать длину данных следующий за предварительным заголовком ( в байтах ) */
static size_t getDataLen( const ModbusMessage& m );
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, RemoteServiceMessage& m );
std::ostream& operator<<(std::ostream& os, RemoteServiceMessage* m );
// -----------------------------------------------------------------------
struct RemoteServiceRetMessage:
std::ostream& operator<<(std::ostream& os, RemoteServiceMessage& m );
std::ostream& operator<<(std::ostream& os, RemoteServiceMessage* m );
// -----------------------------------------------------------------------
struct RemoteServiceRetMessage:
public ModbusHeader
{
{
ModbusByte bcnt = { 0 }; /*!< количество байт */
/*! данные */
ModbusByte data[MAXLENPACKET - sizeof(ModbusByte)];
......@@ -1502,12 +1502,12 @@ namespace ModbusRTU
// оно вспомогательное и игнорируется при
// преобразовании в ModbusMessage.
size_t count = { 0 }; /*!< фактическое количество данных в сообщении */
};
// -----------------------------------------------------------------------
};
// -----------------------------------------------------------------------
struct ReadFileRecordMessage:
struct ReadFileRecordMessage:
public ModbusHeader
{
{
struct SubRequest
{
ModbusByte reftype; /*!< referens type 06 */
......@@ -1546,15 +1546,15 @@ namespace ModbusRTU
// это поле служебное и не используется в релальном обмене
size_t count = { 0 }; /*!< фактическое количество данных */
};
};
std::ostream& operator<<(std::ostream& os, ReadFileRecordMessage& m );
std::ostream& operator<<(std::ostream& os, ReadFileRecordMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, ReadFileRecordMessage& m );
std::ostream& operator<<(std::ostream& os, ReadFileRecordMessage* m );
// -----------------------------------------------------------------------
struct FileTransferMessage:
struct FileTransferMessage:
public ModbusHeader
{
{
ModbusData numfile = { 0 }; /*!< file number 0x0000 to 0xFFFF */
ModbusData numpacket = { 0 }; /*!< number of packet */
ModbusCRC crc = { 0 }; /*!< контрольная сумма */
......@@ -1574,15 +1574,15 @@ namespace ModbusRTU
return sizeof(ModbusData) * 2 + szCRC;
}
} __attribute__((packed));
} __attribute__((packed));
std::ostream& operator<<(std::ostream& os, FileTransferMessage& m );
std::ostream& operator<<(std::ostream& os, FileTransferMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, FileTransferMessage& m );
std::ostream& operator<<(std::ostream& os, FileTransferMessage* m );
// -----------------------------------------------------------------------
struct FileTransferRetMessage:
struct FileTransferRetMessage:
public ModbusHeader
{
{
// 255 - max of bcnt...(1 byte)
// static const int MaxDataLen = 255 - szCRC - szModbusHeader - sizeof(ModbusData)*3 - sizeof(ModbusByte)*2;
static const size_t MaxDataLen = MAXLENPACKET - sizeof(ModbusData) * 3 - sizeof(ModbusByte) * 2;
......@@ -1622,11 +1622,11 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
ModbusMessage transport_msg();
};
};
std::ostream& operator<<(std::ostream& os, FileTransferRetMessage& m );
std::ostream& operator<<(std::ostream& os, FileTransferRetMessage* m );
// -----------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, FileTransferRetMessage& m );
std::ostream& operator<<(std::ostream& os, FileTransferRetMessage* m );
// -----------------------------------------------------------------------
} // end of ModbusRTU namespace
// -------------------------------------------------------------------------
} // 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) );
......
......@@ -73,33 +73,33 @@ ostream& uniset::Configuration::help(ostream& os)
// -------------------------------------------------------------------------
namespace uniset
{
static shared_ptr<Configuration> uconf;
static std::shared_ptr<DebugStream> _ulog = nullptr;
static shared_ptr<Configuration> uconf;
static std::shared_ptr<DebugStream> _ulog = nullptr;
std::shared_ptr<DebugStream> ulog() noexcept
{
std::shared_ptr<DebugStream> ulog() noexcept
{
if( _ulog )
return _ulog;
_ulog = make_shared<DebugStream>();
_ulog->setLogName("ulog");
return _ulog;
}
}
std::shared_ptr<Configuration> uniset_conf() noexcept
{
std::shared_ptr<Configuration> uniset_conf() noexcept
{
// if( uconf == nullptr )
// throw SystemError("Don`t init uniset configuration! First use uniset_init().");
return uconf; // см. uniset_init..
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
Configuration::Configuration():
Configuration::Configuration():
oind(NULL),
// _argc(0),
// _argv(nullptr),
// _argc(0),
// _argv(nullptr),
NSName("NameService"),
repeatCount(2), repeatTimeout(100),
localDBServer(uniset::DefaultObjectId),
......@@ -107,76 +107,76 @@ namespace uniset
localNodeName(""),
fileConfName(""),
heartbeat_msec(3000)
{
{
// ulog.crit()<< " configuration FAILED!!!!!!!!!!!!!!!!!" << endl;
// throw Exception();
}
}
Configuration::~Configuration()
{
Configuration::~Configuration()
{
if( oind )
oind.reset();
if( unixml )
unixml.reset();
for( int i=0; i<_argc; i++ )
for( int i = 0; i < _argc; i++ )
delete[] _argv[i];
delete[] _argv;
}
// ---------------------------------------------------------------------------------
}
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string& xmlfile ):
Configuration::Configuration( int argc, const char* const* argv, const string& xmlfile ):
oind(nullptr),
unixml(nullptr),
// _argc(argc),
// _argv(argv),
// _argc(argc),
// _argv(argv),
NSName("NameService"),
repeatCount(2), repeatTimeout(100),
localDBServer(uniset::DefaultObjectId),
localNode(uniset::DefaultObjectId),
localNodeName(""),
fileConfName(xmlfile)
{
{
if( xmlfile.empty() )
setConfFileName();
initConfiguration(argc, argv);
}
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, shared_ptr<ObjectIndex> _oind,
}
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, shared_ptr<ObjectIndex> _oind,
const string& fileConf ):
oind(nullptr),
unixml(nullptr),
// _argc(argc),
// _argv(argv),
// _argc(argc),
// _argv(argv),
NSName("NameService"),
repeatCount(2), repeatTimeout(100),
localDBServer(uniset::DefaultObjectId),
localNode(uniset::DefaultObjectId),
localNodeName(""),
fileConfName(fileConf)
{
{
if( fileConf.empty() )
setConfFileName();
oind = _oind;
initConfiguration(argc, argv);
}
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string& fileConf,
}
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string& fileConf,
uniset::ObjectInfo* omap ):
oind(NULL),
// _argc(argc),
// _argv(argv),
// _argc(argc),
// _argv(argv),
NSName("NameService"),
repeatCount(2), repeatTimeout(100),
localDBServer(uniset::DefaultObjectId),
localNode(uniset::DefaultObjectId),
localNodeName(""),
fileConfName(fileConf)
{
{
if( fileConf.empty() )
setConfFileName();
......@@ -184,18 +184,19 @@ namespace uniset
oind = static_pointer_cast<ObjectIndex>(_oi);
initConfiguration(argc, argv);
}
// ---------------------------------------------------------------------------------
void Configuration::initConfiguration( int argc, const char* const* argv )
{
}
// ---------------------------------------------------------------------------------
void Configuration::initConfiguration( int argc, const char* const* argv )
{
// PassiveTimer pt(UniSetTimer::WaitUpTime);
ulogsys << "*** configure from file: " << fileConfName << endl;
// т.к. мы не знаем откуда эти argc и argv и может они будут удалены сразу после завершения функции
// то надёжнее скопировать себе всё..
_argc = argc;
_argv = new const char*[argc];
for( int i=0; i<argc; i++ )
_argv = new const char* [argc];
for( int i = 0; i < argc; i++ )
_argv[i] = uniset::uni_strdup(argv[i]);
iorfile = make_shared<IORFile>();
......@@ -476,11 +477,11 @@ namespace uniset
}
// cerr << "*************** initConfiguration: " << pt.getCurrent() << " msec " << endl;
}
}
// -------------------------------------------------------------------------
std::string Configuration::getArg2Param( const std::string& name, const std::string& defval, const std::string& defval2 ) const noexcept
{
// -------------------------------------------------------------------------
std::string Configuration::getArg2Param( const std::string& name, const std::string& defval, const std::string& defval2 ) const noexcept
{
string s(uniset::getArgParam(name, _argc, _argv, ""));
if( !s.empty() )
......@@ -490,42 +491,42 @@ namespace uniset
return defval;
return defval2;
}
}
string Configuration::getArgParam( const string& name, const string& defval ) const noexcept
{
string Configuration::getArgParam( const string& name, const string& defval ) const noexcept
{
return uniset::getArgParam(name, _argc, _argv, defval);
}
}
int Configuration::getArgInt( const string& name, const string& defval ) const noexcept
{
int Configuration::getArgInt( const string& name, const string& defval ) const noexcept
{
return uniset::uni_atoi(getArgParam( name, defval ));
}
}
int Configuration::getArgPInt( const string& name, int defval ) const noexcept
{
int Configuration::getArgPInt( const string& name, int defval ) const noexcept
{
string param = getArgParam(name, "");
if( param.empty() )
return defval;
return uniset::uni_atoi(param);
}
}
int Configuration::getArgPInt( const string& name, const string& strdefval, int defval ) const noexcept
{
int Configuration::getArgPInt( const string& name, const string& strdefval, int defval ) const noexcept
{
string param = getArgParam(name, strdefval);
if( param.empty() && strdefval.empty() )
return defval;
return uniset::uni_atoi(param);
}
}
// -------------------------------------------------------------------------
void Configuration::initParameters()
{
// -------------------------------------------------------------------------
void Configuration::initParameters()
{
xmlNode* root = unixml->findNode( unixml->getFirstNode(), "UniSet" );
if( !root )
......@@ -641,10 +642,10 @@ namespace uniset
if( heartbeat_msec <= 0 )
heartbeat_msec = 3000;
}
}
// -------------------------------------------------------------------------
void Configuration::setLocalNode( const string& nodename )
{
}
// -------------------------------------------------------------------------
void Configuration::setLocalNode( const string& nodename )
{
localNode = oind->getIdByName(nodename);
if( localNode == DefaultObjectId )
......@@ -657,121 +658,121 @@ namespace uniset
localNodeName = nodename;
oind->initLocalNode(localNode);
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getNode(const string& path) const noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getNode(const string& path) const noexcept
{
return unixml->findNode(unixml->getFirstNode(), path);
}
// -------------------------------------------------------------------------
string Configuration::getProp(xmlNode* node, const string& name) const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getProp(xmlNode* node, const string& name) const noexcept
{
return UniXML::getProp(node, name);
}
int Configuration::getIntProp(xmlNode* node, const string& name) const noexcept
{
}
int Configuration::getIntProp(xmlNode* node, const string& name) const noexcept
{
return UniXML::getIntProp(node, name);
}
int Configuration::getPIntProp(xmlNode* node, const string& name, int def) const noexcept
{
}
int Configuration::getPIntProp(xmlNode* node, const string& name, int def) const noexcept
{
return UniXML::getPIntProp(node, name, def);
}
}
// -------------------------------------------------------------------------
string Configuration::getField(const string& path) const noexcept
{
// -------------------------------------------------------------------------
string Configuration::getField(const string& path) const noexcept
{
return getProp(getNode(path), "name");
}
}
// -------------------------------------------------------------------------
int Configuration::getIntField(const std::string& path) const noexcept
{
// -------------------------------------------------------------------------
int Configuration::getIntField(const std::string& path) const noexcept
{
return unixml->getIntProp(getNode(path), "name");
}
}
// -------------------------------------------------------------------------
int Configuration::getPIntField(const std::string& path, int def) const noexcept
{
// -------------------------------------------------------------------------
int Configuration::getPIntField(const std::string& path, int def) const noexcept
{
int i = getIntField(path);;
if (i <= 0)
return def;
return i;
}
}
// -------------------------------------------------------------------------
xmlNode* Configuration::findNode(xmlNode* node, const std::string& snode, const std::string& sname) const noexcept
{
// -------------------------------------------------------------------------
xmlNode* Configuration::findNode(xmlNode* node, const std::string& snode, const std::string& sname) const noexcept
{
if( !unixml->isOpen() )
return 0;
return unixml->findNode(node, snode, sname);
}
// -------------------------------------------------------------------------
string Configuration::getRootDir() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getRootDir() const noexcept
{
return rootDir;
}
// -------------------------------------------------------------------------
int Configuration::getArgc() const noexcept
{
}
// -------------------------------------------------------------------------
int Configuration::getArgc() const noexcept
{
return _argc;
}
// -------------------------------------------------------------------------
const char* const* Configuration::getArgv() const noexcept
{
}
// -------------------------------------------------------------------------
const char* const* Configuration::getArgv() const noexcept
{
return _argv;
}
// -------------------------------------------------------------------------
ObjectId Configuration::getDBServer() const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getDBServer() const noexcept
{
return localDBServer; /*!< получение идентификатора DBServer-а */
}
// -------------------------------------------------------------------------
ObjectId Configuration::getLocalNode() const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getLocalNode() const noexcept
{
return localNode; /*!< получение идентификатора локального узла */
}
// -------------------------------------------------------------------------
string Configuration::getLocalNodeName() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getLocalNodeName() const noexcept
{
return localNodeName; /*!< получение название локального узла */
}
// -------------------------------------------------------------------------
const string Configuration::getNSName() const noexcept
{
}
// -------------------------------------------------------------------------
const string Configuration::getNSName() const noexcept
{
return NSName;
}
// -------------------------------------------------------------------------
string Configuration::getRootSection() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getRootSection() const noexcept
{
return secRoot;
}
// -------------------------------------------------------------------------
string Configuration::getSensorsSection() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getSensorsSection() const noexcept
{
return secSensors;
}
// -------------------------------------------------------------------------
string Configuration::getObjectsSection() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getObjectsSection() const noexcept
{
return secObjects;
}
// -------------------------------------------------------------------------
string Configuration::getControllersSection() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getControllersSection() const noexcept
{
return secControlles;
}
// -------------------------------------------------------------------------
string Configuration::getServicesSection() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getServicesSection() const noexcept
{
return secServices;
}
}
// -------------------------------------------------------------------------
void Configuration::createNodesList()
{
// -------------------------------------------------------------------------
void Configuration::createNodesList()
{
xmlNode* omapnode = unixml->findNode(unixml->getFirstNode(), "ObjectsMap");
if( !omapnode )
......@@ -856,41 +857,41 @@ namespace uniset
}
uinfo << "Configuration(createNodesList): size of node list " << lnodes.size() << endl;
}
// -------------------------------------------------------------------------
void Configuration::initNode( uniset::NodeInfo& ninfo, UniXML::iterator& it ) noexcept
{
}
// -------------------------------------------------------------------------
void Configuration::initNode( uniset::NodeInfo& ninfo, UniXML::iterator& it ) noexcept
{
if( ninfo.id == getLocalNode() )
ninfo.connected = true;
else
ninfo.connected = false;
}
// -------------------------------------------------------------------------
string Configuration::getPropByNodeName(const string& nodename, const string& prop) const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getPropByNodeName(const string& nodename, const string& prop) const noexcept
{
xmlNode* node = getNode(nodename);
if(node == NULL)
return "";
return getProp(node, prop);
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( std::shared_ptr<DebugStream> deb, const string& _debname ) noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( std::shared_ptr<DebugStream> deb, const string& _debname ) noexcept
{
if( !deb )
return NULL;
return initLogStream( deb.get(), _debname );
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( DebugStream& deb, const string& _debname ) noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( DebugStream& deb, const string& _debname ) noexcept
{
return initLogStream(&deb, _debname);
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( DebugStream* deb, const string& _debname ) noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( DebugStream* deb, const string& _debname ) noexcept
{
if( !deb )
return nullptr;
......@@ -978,42 +979,42 @@ namespace uniset
deb->logFile(debug_file);
return dnode;
}
// -------------------------------------------------------------------------
uniset::ListOfNode::const_iterator Configuration::listNodesBegin() const noexcept
{
}
// -------------------------------------------------------------------------
uniset::ListOfNode::const_iterator Configuration::listNodesBegin() const noexcept
{
return lnodes.begin();
}
// -------------------------------------------------------------------------
uniset::ListOfNode::const_iterator Configuration::listNodesEnd() const noexcept
{
}
// -------------------------------------------------------------------------
uniset::ListOfNode::const_iterator Configuration::listNodesEnd() const noexcept
{
return lnodes.end();
}
// -------------------------------------------------------------------------
const std::shared_ptr<UniXML> Configuration::getConfXML() const noexcept
{
}
// -------------------------------------------------------------------------
const std::shared_ptr<UniXML> Configuration::getConfXML() const noexcept
{
return unixml;
}
// -------------------------------------------------------------------------
CORBA::ORB_ptr Configuration::getORB() const
{
}
// -------------------------------------------------------------------------
CORBA::ORB_ptr Configuration::getORB() const
{
return CORBA::ORB::_duplicate(orb);
}
// -------------------------------------------------------------------------
const CORBA::PolicyList Configuration::getPolicy() const noexcept
{
}
// -------------------------------------------------------------------------
const CORBA::PolicyList Configuration::getPolicy() const noexcept
{
return policyList;
}
// -------------------------------------------------------------------------
static std::string makeSecName( const std::string& sec, const std::string& name ) noexcept
{
}
// -------------------------------------------------------------------------
static std::string makeSecName( const std::string& sec, const std::string& name ) noexcept
{
ostringstream n;
n << sec << "/" << name;
return std::move(n.str());
}
// -------------------------------------------------------------------------
void Configuration::initRepSections()
{
}
// -------------------------------------------------------------------------
void Configuration::initRepSections()
{
// Реализация под жёсткую структуру репозитория
xmlNode* node( unixml->findNode(unixml->getFirstNode(), "RootSection") );
......@@ -1030,12 +1031,12 @@ namespace uniset
secObjects = makeSecName(secRoot, getRepSectionName("objects", xmlObjectsSec));
secControlles = makeSecName(secRoot, getRepSectionName("controllers", xmlControllersSec));
secServices = makeSecName(secRoot, getRepSectionName("services", xmlServicesSec));
}
// -------------------------------------------------------------------------
// второй параметр намеренно передаётся и переопредеяется
// это просто такой способ вернуть и строку и указатель на узел (одним махом)
string Configuration::getRepSectionName( const string& sec, xmlNode* secnode )
{
}
// -------------------------------------------------------------------------
// второй параметр намеренно передаётся и переопредеяется
// это просто такой способ вернуть и строку и указатель на узел (одним махом)
string Configuration::getRepSectionName( const string& sec, xmlNode* secnode )
{
secnode = unixml->findNode(unixml->getFirstNode(), sec);
if( secnode == NULL )
......@@ -1052,10 +1053,10 @@ namespace uniset
ret = unixml->getProp(secnode, "name");
return std::move(ret);
}
// -------------------------------------------------------------------------
void Configuration::setConfFileName( const string& fn )
{
}
// -------------------------------------------------------------------------
void Configuration::setConfFileName( const string& fn )
{
if( !fn.empty() )
{
fileConfName = fn;
......@@ -1085,10 +1086,10 @@ namespace uniset
ucrit << msg.str();
throw uniset::SystemError(msg.str());
}
}
// -------------------------------------------------------------------------
string Configuration::getPort( const string& port ) const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getPort( const string& port ) const noexcept
{
// Порт задан в параметрах программы
string defport(getArgParam("--uniset-port"));
......@@ -1108,162 +1109,162 @@ namespace uniset
// Порт по умолчанию
return UniSetDefaultPort;
}
// -------------------------------------------------------------------------
ObjectId Configuration::getSensorID( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getSensorID( const std::string& name ) const noexcept
{
if( name.empty() )
return DefaultObjectId;
return oind->getIdByName(getSensorsSection() + "/" + name);
}
// -------------------------------------------------------------------------
ObjectId Configuration::getControllerID( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getControllerID( const std::string& name ) const noexcept
{
if( name.empty() )
return DefaultObjectId;
return oind->getIdByName(getControllersSection() + "/" + name);
}
// -------------------------------------------------------------------------
ObjectId Configuration::getObjectID( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getObjectID( const std::string& name ) const noexcept
{
if( name.empty() )
return DefaultObjectId;
return oind->getIdByName(getObjectsSection() + "/" + name);
}
// -------------------------------------------------------------------------
ObjectId Configuration::getServiceID( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
ObjectId Configuration::getServiceID( const std::string& name ) const noexcept
{
if( name.empty() )
return DefaultObjectId;
return oind->getIdByName(getServicesSection() + "/" + name);
}
// -------------------------------------------------------------------------
uniset::ObjectId Configuration::getNodeID( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
uniset::ObjectId Configuration::getNodeID( const std::string& name ) const noexcept
{
if( name.empty() )
return DefaultObjectId;
return oind->getNodeId( name );
}
// -------------------------------------------------------------------------
const string Configuration::getConfFileName() const noexcept
{
}
// -------------------------------------------------------------------------
const string Configuration::getConfFileName() const noexcept
{
return fileConfName;
}
// -------------------------------------------------------------------------
string Configuration::getImagesDir() const noexcept
{
}
// -------------------------------------------------------------------------
string Configuration::getImagesDir() const noexcept
{
return imagesDir; // временно
}
// -------------------------------------------------------------------------
timeout_t Configuration::getHeartBeatTime() const noexcept
{
}
// -------------------------------------------------------------------------
timeout_t Configuration::getHeartBeatTime() const noexcept
{
return heartbeat_msec;
}
// -------------------------------------------------------------------------
const string Configuration::getConfDir() const noexcept
{
}
// -------------------------------------------------------------------------
const string Configuration::getConfDir() const noexcept
{
return confDir;
}
}
const string Configuration::getDataDir() const noexcept
{
const string Configuration::getDataDir() const noexcept
{
return dataDir;
}
}
const string Configuration::getBinDir() const noexcept
{
const string Configuration::getBinDir() const noexcept
{
return binDir;
}
}
const string Configuration::getLogDir() const noexcept
{
const string Configuration::getLogDir() const noexcept
{
return logDir;
}
}
const string Configuration::getLockDir() const noexcept
{
const string Configuration::getLockDir() const noexcept
{
return lockDir;
}
}
const string Configuration::getDocDir() const noexcept
{
const string Configuration::getDocDir() const noexcept
{
return docDir;
}
}
bool Configuration::isLocalIOR() const noexcept
{
bool Configuration::isLocalIOR() const noexcept
{
return localIOR;
}
}
bool Configuration::isTransientIOR() const noexcept
{
bool Configuration::isTransientIOR() const noexcept
{
return transientIOR;
}
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLSensorsSection() noexcept
{
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLSensorsSection() noexcept
{
if( xmlSensorsSec )
return xmlSensorsSec;
xmlSensorsSec = unixml->findNode(unixml->getFirstNode(), "sensors");
return xmlSensorsSec;
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLObjectsSection() noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLObjectsSection() noexcept
{
if( xmlObjectsSec )
return xmlObjectsSec;
xmlObjectsSec = unixml->findNode(unixml->getFirstNode(), "objects");
return xmlObjectsSec;
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLControllersSection() noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLControllersSection() noexcept
{
if( xmlControllersSec )
return xmlControllersSec;
xmlControllersSec = unixml->findNode(unixml->getFirstNode(), "controllers");
return xmlControllersSec;
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLServicesSection() noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLServicesSection() noexcept
{
if( xmlServicesSec )
return xmlServicesSec;
xmlServicesSec = unixml->findNode(unixml->getFirstNode(), "services");
return xmlServicesSec;
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLNodesSection() noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLNodesSection() noexcept
{
if( xmlNodesSec )
return xmlNodesSec;
xmlNodesSec = unixml->findNode(unixml->getFirstNode(), "nodes");
return xmlNodesSec;
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLObjectNode( uniset::ObjectId id ) const noexcept
{
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLObjectNode( uniset::ObjectId id ) const noexcept
{
const ObjectInfo* i = oind->getObjectInfo(id);
if( i )
return (xmlNode*)(i->data);
return 0;
}
// -------------------------------------------------------------------------
UniversalIO::IOType Configuration::getIOType( uniset::ObjectId id ) const noexcept
{
}
// -------------------------------------------------------------------------
UniversalIO::IOType Configuration::getIOType( uniset::ObjectId id ) const noexcept
{
const ObjectInfo* i = oind->getObjectInfo(id);
if( i && (xmlNode*)(i->data) )
......@@ -1273,10 +1274,10 @@ namespace uniset
}
return UniversalIO::UnknownIOType;
}
// -------------------------------------------------------------------------
UniversalIO::IOType Configuration::getIOType( const std::string& name ) const noexcept
{
}
// -------------------------------------------------------------------------
UniversalIO::IOType Configuration::getIOType( const std::string& name ) const noexcept
{
// Если указано "короткое" имя
// то просто сперва ищём ID, а потом по нему
// iotype
......@@ -1296,25 +1297,25 @@ namespace uniset
}
return UniversalIO::UnknownIOType;
}
// -------------------------------------------------------------------------
size_t Configuration::getCountOfNet() const noexcept
{
}
// -------------------------------------------------------------------------
size_t Configuration::getCountOfNet() const noexcept
{
return countOfNet;
}
// -------------------------------------------------------------------------
size_t Configuration::getRepeatTimeout() const noexcept
{
}
// -------------------------------------------------------------------------
size_t Configuration::getRepeatTimeout() const noexcept
{
return repeatTimeout;
}
// -------------------------------------------------------------------------
size_t Configuration::getRepeatCount() const noexcept
{
}
// -------------------------------------------------------------------------
size_t Configuration::getRepeatCount() const noexcept
{
return repeatCount;
}
// -------------------------------------------------------------------------
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile )
{
if( uniset::uconf )
{
cerr << "Reusable call uniset_init... ignore.." << endl;
......@@ -1328,9 +1329,9 @@ namespace uniset
uniset::uconf = make_shared<Configuration>(argc, argv, confile);
return uniset::uconf;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
} // end of UniSetTypes namespace
......@@ -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