Commit 92f74164 authored by Pavel Vainerman's avatar Pavel Vainerman

make style

parent b372950f
......@@ -29,8 +29,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
//------------------------------------------------------------------------------------------
/*!
//------------------------------------------------------------------------------------------
/*!
\page page_DBServer_MySQL (DBServer_MySQL) Реализация сервиса ведения БД на основе MySQL
- \ref sec_DBS_Comm
......@@ -84,9 +84,9 @@ namespace uniset
\section sec_DBS_Tables Таблицы MySQL
К основным таблицам относятся следующие:
\code
DROP TABLE IF EXISTS `main_history`;
CREATE TABLE `main_history` (
\code
DROP TABLE IF EXISTS `main_history`;
CREATE TABLE `main_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -98,10 +98,10 @@ CREATE TABLE `main_history` (
PRIMARY KEY (`id`),
KEY `main_history_sensor_id` (`sensor_id`),
CONSTRAINT `sensor_id_refs_id_3d679168` FOREIGN KEY (`sensor_id`) REFERENCES `main_sensor` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `main_emergencylog`;
CREATE TABLE `main_emergencylog` (
DROP TABLE IF EXISTS `main_emergencylog`;
CREATE TABLE `main_emergencylog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -110,11 +110,11 @@ CREATE TABLE `main_emergencylog` (
PRIMARY KEY (`id`),
KEY `main_emergencylog_type_id` (`type_id`),
CONSTRAINT `type_id_refs_id_a3133ca` FOREIGN KEY (`type_id`) REFERENCES `main_emergencytype` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `main_emergencyrecords`;
CREATE TABLE `main_emergencyrecords` (
DROP TABLE IF EXISTS `main_emergencyrecords`;
CREATE TABLE `main_emergencyrecords` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -127,16 +127,16 @@ CREATE TABLE `main_emergencyrecords` (
KEY `main_emergencyrecords_sensor_id` (`sensor_id`),
CONSTRAINT `log_id_refs_id_77a37ea9` FOREIGN KEY (`log_id`) REFERENCES `main_emergencylog` (`id`),
CONSTRAINT `sensor_id_refs_id_436bab5e` FOREIGN KEY (`sensor_id`) REFERENCES `main_sensor` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
\endcode
\endcode
\warning Временно, для обратной совместимости поле 'time_usec' в таблицах оставлено с таким названием,
хотя фактически туда сейчас сохраняется значение в наносекундах!
*/
class DBServer_MySQL:
\warning Временно, для обратной совместимости поле 'time_usec' в таблицах оставлено с таким названием,
хотя фактически туда сейчас сохраняется значение в наносекундах!
*/
class DBServer_MySQL:
public DBServer
{
{
public:
DBServer_MySQL( uniset::ObjectId id, const std::string& prefix );
explicit DBServer_MySQL( const std::string& prefix );
......@@ -204,8 +204,8 @@ class DBServer_MySQL:
private:
DBTableMap tblMap;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
//------------------------------------------------------------------------------------------
#endif
......@@ -32,10 +32,10 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
class MySQLInterface:
// ----------------------------------------------------------------------------
class MySQLInterface:
public DBNetInterface
{
{
public:
MySQLInterface();
......@@ -80,8 +80,8 @@ class MySQLInterface:
MYSQL* mysql;
std::string lastQ;
bool connected;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------------
#endif
......@@ -25,8 +25,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
//------------------------------------------------------------------------------------------
/*!
//------------------------------------------------------------------------------------------
/*!
* \brief The DBServer_PostgreSQL class
* Реализация работы с PostgreSQL.
*
......@@ -51,9 +51,9 @@ namespace uniset
* \warning Временно, для обратной совместимости поле 'time_usec' в таблицах оставлено с таким названием,
* хотя фактически туда сейчас сохраняется значение в наносекундах!
*/
class DBServer_PostgreSQL:
class DBServer_PostgreSQL:
public DBServer
{
{
public:
DBServer_PostgreSQL( uniset::ObjectId id, const std::string& prefix );
DBServer_PostgreSQL();
......@@ -133,8 +133,8 @@ class DBServer_PostgreSQL:
private:
DBTableMap tblMap;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
//------------------------------------------------------------------------------------------
#endif
......@@ -28,10 +28,10 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
class PostgreSQLInterface:
// ----------------------------------------------------------------------------
class PostgreSQLInterface:
public DBNetInterface
{
{
public:
PostgreSQLInterface();
......@@ -69,8 +69,8 @@ class PostgreSQLInterface:
std::string lastQ;
std::string lastE;
double last_inserted_id;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------
#endif
......
......@@ -29,8 +29,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
//------------------------------------------------------------------------------------------
/*!
//------------------------------------------------------------------------------------------
/*!
\page page_DBServer_SQLite (DBServer_SQLite) Реализация сервиса ведения БД на основе SQLite
- \ref sec_DBS_Comm
......@@ -84,9 +84,9 @@ namespace uniset
\section sec_DBS_Tables Таблицы SQLite
К основным таблицам относятся следующие (описание в формате MySQL!):
\code
DROP TABLE IF EXISTS `main_history`;
CREATE TABLE `main_history` (
\code
DROP TABLE IF EXISTS `main_history`;
CREATE TABLE `main_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -98,10 +98,10 @@ CREATE TABLE `main_history` (
PRIMARY KEY (`id`),
KEY `main_history_sensor_id` (`sensor_id`),
CONSTRAINT `sensor_id_refs_id_3d679168` FOREIGN KEY (`sensor_id`) REFERENCES `main_sensor` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `main_emergencylog`;
CREATE TABLE `main_emergencylog` (
DROP TABLE IF EXISTS `main_emergencylog`;
CREATE TABLE `main_emergencylog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -110,11 +110,11 @@ CREATE TABLE `main_emergencylog` (
PRIMARY KEY (`id`),
KEY `main_emergencylog_type_id` (`type_id`),
CONSTRAINT `type_id_refs_id_a3133ca` FOREIGN KEY (`type_id`) REFERENCES `main_emergencytype` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `main_emergencyrecords`;
CREATE TABLE `main_emergencyrecords` (
DROP TABLE IF EXISTS `main_emergencyrecords`;
CREATE TABLE `main_emergencyrecords` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` time NOT NULL,
......@@ -127,16 +127,16 @@ CREATE TABLE `main_emergencyrecords` (
KEY `main_emergencyrecords_sensor_id` (`sensor_id`),
CONSTRAINT `log_id_refs_id_77a37ea9` FOREIGN KEY (`log_id`) REFERENCES `main_emergencylog` (`id`),
CONSTRAINT `sensor_id_refs_id_436bab5e` FOREIGN KEY (`sensor_id`) REFERENCES `main_sensor` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
\endcode
\endcode
\warning Временно, для обратной совместимости поле 'time_usec' в таблицах оставлено с таким названием,
хотя фактически туда сейчас сохраняется значение в наносекундах!
*/
class DBServer_SQLite:
\warning Временно, для обратной совместимости поле 'time_usec' в таблицах оставлено с таким названием,
хотя фактически туда сейчас сохраняется значение в наносекундах!
*/
class DBServer_SQLite:
public DBServer
{
{
public:
DBServer_SQLite( uniset::ObjectId id, const std::string& prefix );
explicit DBServer_SQLite( const std::string& prefix );
......@@ -204,8 +204,8 @@ class DBServer_SQLite:
private:
DBTableMap tblMap;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
//------------------------------------------------------------------------------------------
#endif
......@@ -31,11 +31,11 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
/*! \page SQLiteIntarface Интерфейс к SQLite
// ----------------------------------------------------------------------------
/*! \page SQLiteIntarface Интерфейс к SQLite
Пример использования:
\code
\code
try
{
SQLiteInterface db;
......@@ -74,17 +74,17 @@ namespace uniset
{
cerr << "(test): catch ..." << endl;
}
\endcode
*/
// ----------------------------------------------------------------------------
// Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY
// При этом конечно есть риск потерять данные при выключении..
// ----------------------------------------------------------------------------
class SQLiteInterface:
\endcode
*/
// ----------------------------------------------------------------------------
// Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY
// При этом конечно есть риск потерять данные при выключении..
// ----------------------------------------------------------------------------
class SQLiteInterface:
public DBInterface
{
{
public:
SQLiteInterface();
......@@ -137,8 +137,8 @@ class SQLiteInterface:
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------
#endif
......
......@@ -23,10 +23,10 @@
//--------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*! Интерфейс для работы с в/в */
class ComediInterface
{
// -----------------------------------------------------------------------------
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
explicit ComediInterface( const std::string& dev );
~ComediInterface();
......@@ -81,8 +81,8 @@ class ComediInterface
std::string dname;
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // ComediInterface_H_
......
......@@ -42,8 +42,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_IOControl (IOControl) Реализация процесса ввода/вывода
- \ref sec_IOC_Comm
......@@ -180,13 +180,13 @@ namespace uniset
указан параметр disable_testmode="1".
<br>\b "4" - Режим "только входы"
<br>\b "5" - Режим "только выходы"
*/
// -----------------------------------------------------------------------------
/*! \todo (IOControl): Сделать обработку сигналов завершения */
*/
// -----------------------------------------------------------------------------
/*! \todo (IOControl): Сделать обработку сигналов завершения */
class CardList:
class CardList:
public std::vector<ComediInterface*>
{
{
public:
explicit CardList( size_t size ) : std::vector<ComediInterface * >(size) { }
......@@ -205,9 +205,9 @@ class CardList:
return NULL;
}
};
};
/*!
/*!
Процесс работы с картами в/в.
Задачи:
- опрос дискретных и аналоговых входов, выходов
......@@ -221,10 +221,10 @@ class CardList:
- определение обрыва провода (для аналоговых сигналов)
- мигание лампочками
- тест ламп
*/
class IOControl:
*/
class IOControl:
public UniSetObject
{
{
public:
IOControl( uniset::ObjectId id, uniset::ObjectId icID, const std::shared_ptr<SharedMemory>& shm = nullptr, int numcards = 2, const std::string& prefix = "io" );
virtual ~IOControl();
......@@ -418,8 +418,8 @@ class IOControl:
int logserv_port = {0};
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // IOControl_H_
......
......@@ -20,14 +20,14 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------------------
const Element::ElementID Element::DefaultElementID = "?id?";
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------------------
const Element::ElementID Element::DefaultElementID = "?id?";
// -------------------------------------------------------------------------
void Element::addChildOut( std::shared_ptr<Element> el, size_t num )
{
void Element::addChildOut( std::shared_ptr<Element> el, size_t num )
{
if( el.get() == this )
{
ostringstream msg;
......@@ -57,10 +57,10 @@ void Element::addChildOut( std::shared_ptr<Element> el, size_t num )
}
outs.emplace_front(el, num);
}
// -------------------------------------------------------------------------
void Element::delChildOut( std::shared_ptr<Element> el )
{
}
// -------------------------------------------------------------------------
void Element::delChildOut( std::shared_ptr<Element> el )
{
for( auto it = outs.begin(); it != outs.end(); ++it )
{
if( it->el == el )
......@@ -69,19 +69,19 @@ void Element::delChildOut( std::shared_ptr<Element> el )
return;
}
}
}
}
// -------------------------------------------------------------------------
void Element::setChildOut()
{
// -------------------------------------------------------------------------
void Element::setChildOut()
{
bool _myout = getOut();
for( auto && it : outs )
it.el->setIn(it.num, _myout);
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Element::find(const ElementID& id )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Element::find(const ElementID& id )
{
for( const auto& it : outs )
{
if( it.el->getId() == id )
......@@ -91,10 +91,10 @@ std::shared_ptr<Element> Element::find(const ElementID& id )
}
return nullptr;
}
// -------------------------------------------------------------------------
void Element::addInput(size_t num, bool state)
{
}
// -------------------------------------------------------------------------
void Element::addInput(size_t num, bool state)
{
for( auto& it : ins )
{
if( it.num == num )
......@@ -106,10 +106,10 @@ void Element::addInput(size_t num, bool state)
}
ins.emplace_front(num, state);
}
// -------------------------------------------------------------------------
void Element::delInput(size_t num )
{
}
// -------------------------------------------------------------------------
void Element::delInput(size_t num )
{
for( auto it = ins.begin(); it != ins.end(); ++it )
{
if( it->num == num )
......@@ -118,6 +118,6 @@ void Element::delInput(size_t num )
return;
}
}
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -25,19 +25,19 @@
//--------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class LogicException:
class LogicException:
public uniset::Exception
{
{
public:
LogicException(): uniset::Exception("LogicException") {}
explicit LogicException( const std::string& err): uniset::Exception(err) {}
};
};
class Element
{
class Element
{
public:
typedef std::string ElementID;
......@@ -135,11 +135,11 @@ class Element
private:
};
// ---------------------------------------------------------------------------
class TOR:
};
// ---------------------------------------------------------------------------
class TOR:
public Element
{
{
public:
TOR( ElementID id, size_t numbers = 0, bool st = false );
......@@ -162,11 +162,11 @@ class TOR:
private:
};
// ---------------------------------------------------------------------------
class TAND:
};
// ---------------------------------------------------------------------------
class TAND:
public TOR
{
{
public:
TAND(ElementID id, size_t numbers = 0, bool st = false );
......@@ -182,13 +182,13 @@ class TAND:
TAND() {}
private:
};
};
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
public Element
{
{
public:
TNOT( ElementID id, bool out_default );
......@@ -214,8 +214,8 @@ class TNOT:
bool myout;
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -110,9 +110,9 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class LProcessor
{
// --------------------------------------------------------------------------
class LProcessor
{
public:
explicit LProcessor( const std::string& name = "" );
virtual ~LProcessor();
......@@ -186,8 +186,8 @@ class LProcessor
std::string fSchema = {""};
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -29,12 +29,12 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
/*! Реализация LogicProccessor основанная на заказе датчиков */
class PassiveLProcessor:
// -------------------------------------------------------------------------
/*! Реализация LogicProccessor основанная на заказе датчиков */
class PassiveLProcessor:
public UniSetObject,
protected LProcessor
{
{
public:
PassiveLProcessor(uniset::ObjectId objId,
......@@ -78,8 +78,8 @@ class PassiveLProcessor:
int maxHeartBeat = { 10 };
IOController::IOStateList::iterator itHeartBeat;
std::mutex mutex_start;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -21,21 +21,21 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
Schema::Schema()
{
}
Schema::Schema()
{
}
Schema::~Schema()
{
}
// -------------------------------------------------------------------------
void Schema::link( Element::ElementID rootID, Element::ElementID childID, int numIn )
{
Schema::~Schema()
{
}
// -------------------------------------------------------------------------
void Schema::link( Element::ElementID rootID, Element::ElementID childID, int numIn )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
......@@ -65,10 +65,10 @@ void Schema::link( Element::ElementID rootID, Element::ElementID childID, int nu
// сохраняем в список соединений
inLinks.emplace_front(e1, e2, numIn);
}
// -------------------------------------------------------------------------
void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
{
}
// -------------------------------------------------------------------------
void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
......@@ -105,10 +105,10 @@ void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
break;
}
}
}
// -------------------------------------------------------------------------
void Schema::extlink( const string& name, Element::ElementID childID, int numIn )
{
}
// -------------------------------------------------------------------------
void Schema::extlink( const string& name, Element::ElementID childID, int numIn )
{
auto it = emap.find(childID);
if( it == emap.end() )
......@@ -126,20 +126,20 @@ void Schema::extlink( const string& name, Element::ElementID childID, int numIn
// заносим в список
extLinks.emplace_front(name, el, numIn);
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::manage( std::shared_ptr<Element> el )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::manage( std::shared_ptr<Element> el )
{
dinfo << "Schema: manage new element id=" << el->getId()
<< " type=" << el->getType()
<< " inputs=" << el->inCount() << endl;
emap[el->getId()] = el;
return el;
}
// -------------------------------------------------------------------------
void Schema::remove( std::shared_ptr<Element> el )
{
}
// -------------------------------------------------------------------------
void Schema::remove( std::shared_ptr<Element> el )
{
for( auto && it = emap.begin(); it != emap.end(); ++it )
{
if( it->second == el )
......@@ -166,18 +166,18 @@ void Schema::remove( std::shared_ptr<Element> el )
lit.to = 0;
}
}
// -------------------------------------------------------------------------
void Schema::setIn( Element::ElementID ID, int inNum, bool state )
{
}
// -------------------------------------------------------------------------
void Schema::setIn( Element::ElementID ID, int inNum, bool state )
{
auto it = emap.find(ID);
if( it != emap.end() )
it->second->setIn(inNum, state);
}
// -------------------------------------------------------------------------
bool Schema::getOut( Element::ElementID ID )
{
}
// -------------------------------------------------------------------------
bool Schema::getOut( Element::ElementID ID )
{
auto it = emap.find(ID);
if( it != emap.end() )
......@@ -186,20 +186,20 @@ bool Schema::getOut( Element::ElementID ID )
ostringstream msg;
msg << "Schema: element id=" << ID << " NOT FOUND!";
throw LogicException(msg.str());
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::find( Element::ElementID id )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::find( Element::ElementID id )
{
auto it = emap.find(id);
if( it != emap.end() )
return it->second;
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findExtLink( const string& name )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findExtLink( const string& name )
{
// помечаем внешние связи
for( const auto& it : extLinks )
{
......@@ -208,10 +208,10 @@ std::shared_ptr<Element> Schema::findExtLink( const string& name )
}
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findOut( const string& name )
{
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findOut( const string& name )
{
// помечаем внешние связи
for( const auto& it : outList )
{
......@@ -220,6 +220,6 @@ std::shared_ptr<Element> Schema::findOut( const string& name )
}
return nullptr;
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -24,9 +24,9 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class Schema
{
// --------------------------------------------------------------------------
class Schema
{
public:
Schema();
virtual ~Schema();
......@@ -177,11 +177,11 @@ class Schema
OutputsList outList;
private:
};
// ---------------------------------------------------------------------------
class SchemaXML:
};
// ---------------------------------------------------------------------------
class SchemaXML:
public Schema
{
{
public:
SchemaXML();
virtual ~SchemaXML();
......@@ -189,8 +189,8 @@ class SchemaXML:
void read( const std::string& xmlfile );
protected:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -23,20 +23,20 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
SchemaXML::SchemaXML()
{
}
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
SchemaXML::SchemaXML()
{
}
SchemaXML::~SchemaXML()
{
}
// -------------------------------------------------------------------------
void SchemaXML::read( const string& xmlfile )
{
SchemaXML::~SchemaXML()
{
}
// -------------------------------------------------------------------------
void SchemaXML::read( const string& xmlfile )
{
UniXML xml;
const string sec("elements");
......@@ -146,6 +146,6 @@ void SchemaXML::read( const string& xmlfile )
outList.emplace_front(tID, el);
}
}
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -20,21 +20,21 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TAND::TAND(ElementID id, size_t num, bool st):
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TAND::TAND(ElementID id, size_t num, bool st):
TOR(id, num, st)
{
}
{
}
TAND::~TAND()
{
}
// -------------------------------------------------------------------------
void TAND::setIn(size_t num, bool state )
{
TAND::~TAND()
{
}
// -------------------------------------------------------------------------
void TAND::setIn(size_t num, bool state )
{
// cout << this << ": input " << num << " set " << state << endl;
for( auto& it : ins )
{
......@@ -70,6 +70,6 @@ void TAND::setIn(size_t num, bool state )
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -20,29 +20,29 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TDelay::TDelay(Element::ElementID id, timeout_t delayMS, size_t inCount):
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TDelay::TDelay(Element::ElementID id, timeout_t delayMS, size_t inCount):
Element(id),
myout(false),
delay(delayMS)
{
{
if( inCount != 0 )
{
// создаём заданное количество входов
for( unsigned int i = 1; i <= inCount; i++ )
ins.emplace_front(i, false); // addInput(i,st);
}
}
}
TDelay::~TDelay()
{
}
// -------------------------------------------------------------------------
void TDelay::setIn( size_t num, bool state )
{
TDelay::~TDelay()
{
}
// -------------------------------------------------------------------------
void TDelay::setIn( size_t num, bool state )
{
bool prev = myout;
// сбрасываем сразу
......@@ -79,10 +79,10 @@ void TDelay::setIn( size_t num, bool state )
dinfo << this << ": set timer " << delay << " [msec]" << endl;
pt.setTiming(delay);
}
}
// -------------------------------------------------------------------------
void TDelay::tick()
{
}
// -------------------------------------------------------------------------
void TDelay::tick()
{
if( pt.getInterval() != 0 && pt.checkTime() )
{
myout = true;
......@@ -90,16 +90,16 @@ void TDelay::tick()
dinfo << getType() << "(" << myid << "): TIMER!!!! myout=" << myout << endl;
Element::setChildOut();
}
}
// -------------------------------------------------------------------------
bool TDelay::getOut() const
{
}
// -------------------------------------------------------------------------
bool TDelay::getOut() const
{
return myout;
}
// -------------------------------------------------------------------------
void TDelay::setDelay( timeout_t timeMS )
{
}
// -------------------------------------------------------------------------
void TDelay::setDelay( timeout_t timeMS )
{
delay = timeMS;
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -22,12 +22,12 @@
// --------------------------------------------------------------------------
namespace uniset
{
// ---------------------------------------------------------------------------
// "ON" delay element
// Сбрасывается без задержки.. а срабатывает с задержкой.
class TDelay:
// ---------------------------------------------------------------------------
// "ON" delay element
// Сбрасывается без задержки.. а срабатывает с задержкой.
class TDelay:
public Element
{
{
public:
TDelay( Element::ElementID id, timeout_t delayMS = 0, size_t inCount = 0 );
......@@ -55,8 +55,8 @@ class TDelay:
timeout_t delay;
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......
......@@ -21,28 +21,28 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TNOT::TNOT( ElementID id, bool out_default ):
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TNOT::TNOT( ElementID id, bool out_default ):
Element(id),
myout(out_default)
{
{
ins.emplace_front(1, !out_default);
}
// -------------------------------------------------------------------------
TNOT::~TNOT()
{
}
// -------------------------------------------------------------------------
void TNOT::setIn( size_t num, bool state )
{
}
// -------------------------------------------------------------------------
TNOT::~TNOT()
{
}
// -------------------------------------------------------------------------
void TNOT::setIn( size_t num, bool state )
{
bool prev = myout;
myout = !state;
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -21,14 +21,14 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TOR::TOR(ElementID id, size_t num, bool st):
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TOR::TOR(ElementID id, size_t num, bool st):
Element(id),
myout(false)
{
{
if( num != 0 )
{
// создаём заданное количество входов
......@@ -40,14 +40,14 @@ TOR::TOR(ElementID id, size_t num, bool st):
myout = true;
}
}
}
}
TOR::~TOR()
{
}
// -------------------------------------------------------------------------
void TOR::setIn( size_t num, bool state )
{
TOR::~TOR()
{
}
// -------------------------------------------------------------------------
void TOR::setIn( size_t num, bool state )
{
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto& it : ins )
......@@ -84,6 +84,6 @@ void TOR::setIn( size_t num, bool state )
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -28,8 +28,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_MQTTPublisher Реализация MQTT издателя
- \ref sec_MQTT_Comm
......@@ -102,11 +102,11 @@ namespace uniset
\note Если заданные "одиночные" значения совпадают с диапазоном, то будет сгенерировано несколько сообщений. Т.е. диапазоны могут пересекатся.
*/
class MQTTPublisher:
*/
class MQTTPublisher:
protected mosqpp::mosquittopp,
public UObject_SK
{
{
public:
MQTTPublisher( uniset::ObjectId objId, xmlNode* cnode, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "mqtt" );
......@@ -185,8 +185,8 @@ class MQTTPublisher:
std::string host = { "localhost" };
int port = { 1883 };
int keepalive = { 60 };
};
// ----------------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _MQTTPublisher_H_
......
......@@ -48,13 +48,13 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\par Базовый класс для реализация обмена по протоколу Modbus [RTU|TCP].
*/
class MBExchange:
*/
class MBExchange:
public UniSetObject
{
{
public:
MBExchange( uniset::ObjectId objId, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "mb" );
......@@ -407,8 +407,8 @@ class MBExchange:
private:
MBExchange();
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _MBExchange_H_
......
......@@ -27,8 +27,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_ModbusTCP Реализация ModbusTCP master
- \ref sec_MBTCP_Comm
......@@ -150,7 +150,7 @@ namespace uniset
/>
...
</sensors>
\endcode
\endcode
\warning По умолчанию для свойств используется префикс "tcp_". Но если задано поле \b filter-field,
то для свойств будет использован префикс <b>"filter-fileld"_</b>.
......@@ -207,9 +207,9 @@ namespace uniset
Режимы переключаются при помощи датчика, который можно задать либо аргументом командной строки
\b --prefix-exchange-mode-id либо в конф. файле параметром \b exchangeModeID="". Константы определяющие режимы объявлены в MBTCPMaster::ExchangeMode.
*/
// -----------------------------------------------------------------------------
/*!
*/
// -----------------------------------------------------------------------------
/*!
\par Реализация Modbus TCP Master для обмена с многими ModbusRTU устройствами
через один modbus tcp шлюз.
......@@ -217,10 +217,10 @@ namespace uniset
на создании соединения с недоступным хостом. Обмен вынесен в отдельный поток.
При этом в этом же потоке обновляются данные в SM. В свою очередь информация о датчиках
связи обновляется в основном потоке (чтобы не зависеть от TCP).
*/
class MBTCPMaster:
*/
class MBTCPMaster:
public MBExchange
{
{
public:
MBTCPMaster( uniset::ObjectId objId, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "mbtcp" );
......@@ -257,8 +257,8 @@ class MBTCPMaster:
// т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке
std::shared_ptr<ThreadCreator<MBTCPMaster>> pollThread; /*!< поток опроса */
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _MBTCPMaster_H_
......
......@@ -26,8 +26,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_ModbusTCPMulti Реализация ModbusTCP 'multi' master
- \ref sec_MBTCPM_Comm
......@@ -182,7 +182,7 @@ namespace uniset
/>
...
</sensors>
\endcode
\endcode
\warning По умолчанию для свойств используется префикс "tcp_". Но если задано поле \b filter-field,
то для свойств будет использован префикс <b>"filter-fileld"_</b>.
......@@ -271,9 +271,9 @@ namespace uniset
постоянным, в отличие от "первого способа" при котором оно создаётся и сразу рвётся и если проверка
настроена достаточно часто ( < TIME_WAIT для сокетов), то при длительной работе могут закончится дескрипторы
на создание сокетов.
*/
// -----------------------------------------------------------------------------
/*!
*/
// -----------------------------------------------------------------------------
/*!
\par Реализация Modbus TCP MultiMaster для обмена с многими ModbusRTU устройствами
через один modbus tcp шлюз, доступный по нескольким ip-адресам.
......@@ -281,10 +281,10 @@ namespace uniset
на создании соединения с недоступным хостом. Обмен вынесен в отдельный поток.
При этом в этом же потоке обновляются данные в SM. В свою очередь информация о датчиках
связи обновляется в основном потоке (чтобы не зависеть от TCP).
*/
class MBTCPMultiMaster:
*/
class MBTCPMultiMaster:
public MBExchange
{
{
public:
MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "mbtcp" );
......@@ -381,8 +381,8 @@ class MBTCPMultiMaster:
// делаем опрос в отдельном потоке
std::shared_ptr< ThreadCreator<MBTCPMultiMaster> > pollThread; /*!< поток опроса */
std::shared_ptr< ThreadCreator<MBTCPMultiMaster> > checkThread; /*!< поток проверки связи по другим каналам */
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _MBTCPMultiMaster_H_
......
......@@ -27,10 +27,10 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
class RTUExchange:
// -----------------------------------------------------------------------------
class RTUExchange:
public MBExchange
{
{
public:
RTUExchange( uniset::ObjectId objId, uniset::ObjectId shmID,
const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "rs" );
......@@ -62,8 +62,8 @@ class RTUExchange:
RTUExchange();
bool rs_pre_clean;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _RS_EXCHANGE_H_
......
......@@ -23,17 +23,17 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
using namespace std;
// -----------------------------------------------------------------------------
RTUStorage::RTUStorage( ModbusRTU::ModbusAddr a ):
// -----------------------------------------------------------------------------
using namespace std;
// -----------------------------------------------------------------------------
RTUStorage::RTUStorage( ModbusRTU::ModbusAddr a ):
addr(a),
pingOK(false),
pollADC(true),
pollDI(true),
pollDIO(true),
pollUNIO(true)
{
{
memset(adc, 0, sizeof(adc));
memset(di, 0, sizeof(di));
memset(dio_do, 0, sizeof(dio_do));
......@@ -44,15 +44,15 @@ RTUStorage::RTUStorage( ModbusRTU::ModbusAddr a ):
memset(unio_do, 0, sizeof(unio_do));
memset(unio_ai, 0, sizeof(unio_ai));
memset(unio_ao, 0, sizeof(unio_ao));
}
// -----------------------------------------------------------------------------
RTUStorage::~RTUStorage()
{
}
// -----------------------------------------------------------------------------
RTUStorage::~RTUStorage()
{
}
// -----------------------------------------------------------------------------
void RTUStorage::poll( const std::shared_ptr<ModbusRTUMaster>& mb ) throw( ModbusRTU::mbException )
{
}
// -----------------------------------------------------------------------------
void RTUStorage::poll( const std::shared_ptr<ModbusRTUMaster>& mb ) throw( ModbusRTU::mbException )
{
try
{
pingOK = true;
......@@ -206,15 +206,15 @@ void RTUStorage::poll( const std::shared_ptr<ModbusRTUMaster>& mb ) throw( Modbu
pingOK = false;
throw;
}
}
// -----------------------------------------------------------------------------
long RTUStorage::getInt( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
}
// -----------------------------------------------------------------------------
long RTUStorage::getInt( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
return lroundf( getFloat(jack, chan, t) );
}
// -----------------------------------------------------------------------------
float RTUStorage::getFloat( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
}
// -----------------------------------------------------------------------------
float RTUStorage::getFloat( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
if( t == UniversalIO::AI )
{
switch( jack )
......@@ -268,10 +268,10 @@ float RTUStorage::getFloat( RTUJack jack, unsigned short int chan, UniversalIO::
}
return 0;
}
// -----------------------------------------------------------------------------
bool RTUStorage::getState( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
}
// -----------------------------------------------------------------------------
bool RTUStorage::getState( RTUJack jack, unsigned short int chan, UniversalIO::IOType t )
{
if( t == UniversalIO::DI )
{
switch( jack )
......@@ -319,10 +319,10 @@ bool RTUStorage::getState( RTUJack jack, unsigned short int chan, UniversalIO::I
}
return false;
}
// -----------------------------------------------------------------------------
ModbusRTU::ModbusData RTUStorage::getRegister( RTUJack jack, unsigned short chan, UniversalIO::IOType t )
{
}
// -----------------------------------------------------------------------------
ModbusRTU::ModbusData RTUStorage::getRegister( RTUJack jack, unsigned short chan, UniversalIO::IOType t )
{
if( t == UniversalIO::AI )
{
switch( jack )
......@@ -422,10 +422,10 @@ ModbusRTU::ModbusData RTUStorage::getRegister( RTUJack jack, unsigned short chan
}
return -1;
}
// -----------------------------------------------------------------------------
ModbusRTU::SlaveFunctionCode RTUStorage::getFunction( RTUJack jack, unsigned short chan, UniversalIO::IOType t )
{
}
// -----------------------------------------------------------------------------
ModbusRTU::SlaveFunctionCode RTUStorage::getFunction( RTUJack jack, unsigned short chan, UniversalIO::IOType t )
{
if( t == UniversalIO::AI )
{
switch( jack )
......@@ -499,11 +499,11 @@ ModbusRTU::SlaveFunctionCode RTUStorage::getFunction( RTUJack jack, unsigned sho
}
return ModbusRTU::fnUnknown;
}
// -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, RTUStorage& m )
{
std::ostream& operator<<(std::ostream& os, RTUStorage& m )
{
os << "-------------------" << endl
<< " АЦП (8 каналов): " << endl;
......@@ -674,20 +674,20 @@ std::ostream& operator<<(std::ostream& os, RTUStorage& m )
os << endl;
return os;
}
// -----------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, RTUStorage* m )
{
}
// -----------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, RTUStorage* m )
{
return os << (*m);
}
// -----------------------------------------------------------------------------
void RTUStorage::print()
{
}
// -----------------------------------------------------------------------------
void RTUStorage::print()
{
cout << this;
}
// -----------------------------------------------------------------------------
RTUStorage::RTUJack RTUStorage::s2j( const std::string& jack )
{
}
// -----------------------------------------------------------------------------
RTUStorage::RTUJack RTUStorage::s2j( const std::string& jack )
{
if( jack == "J1" || jack == "j1" )
return nJ1;
......@@ -710,10 +710,10 @@ RTUStorage::RTUJack RTUStorage::s2j( const std::string& jack )
return nX5;
return nUnknown;
}
// -----------------------------------------------------------------------------
std::string RTUStorage::j2s( RTUStorage::RTUJack jack )
{
}
// -----------------------------------------------------------------------------
std::string RTUStorage::j2s( RTUStorage::RTUJack jack )
{
if( jack == nJ1 )
return "J1";
......@@ -736,6 +736,6 @@ std::string RTUStorage::j2s( RTUStorage::RTUJack jack )
return "X5";
return "";
}
// -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // end of namespace uniset
......@@ -25,11 +25,11 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
class ModbusRTUMaster;
// -----------------------------------------------------------------------------
class RTUStorage
{
// -----------------------------------------------------------------------------
class ModbusRTUMaster;
// -----------------------------------------------------------------------------
class RTUStorage
{
public:
explicit RTUStorage( ModbusRTU::ModbusAddr addr );
~RTUStorage();
......@@ -112,8 +112,8 @@ class RTUStorage
bool unio_di[48]; // Порт UNIO48 DI
float unio_ai[24]; // Порт UNIO48 AI
float unio_ao[24]; // Порт UNIO48 AO
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// --------------------------------------------------------------------------
#endif // _RTUSTORAGE_H_
......
......@@ -49,8 +49,8 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_ModbusSlave Реализация Modbus slave
- \ref sec_MBSlave_Comm
......@@ -206,7 +206,7 @@ namespace uniset
/>
...
</sensors>
\endcode
\endcode
\warning По умолчанию для свойств используется заданный в конструктроре префикс "mbs_".
......@@ -303,12 +303,12 @@ namespace uniset
</MBTCPPersistentSlave>
\endcode
*/
// -----------------------------------------------------------------------------
/*! Реализация slave-интерфейса */
class MBSlave:
*/
// -----------------------------------------------------------------------------
/*! Реализация slave-интерфейса */
class MBSlave:
public UniSetObject
{
{
public:
MBSlave( uniset::ObjectId objId, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "mbs" );
virtual ~MBSlave();
......@@ -622,8 +622,8 @@ class MBSlave:
IOController::IOStateList::iterator sesscount_it;
std::atomic_bool tcpCancelled = { true };
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _MBSlave_H_
......
......@@ -27,8 +27,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page page_RRDServer Реализация RRD хранилища
- \ref sec_RRD_Comm
......@@ -44,7 +44,7 @@ namespace uniset
\section sec_RRD_Conf Настройка RRDServer
Пример секции конфигурации:
\code
\code
<RRDServer1 name="RRDServer1">
<rrd filename="rrdtest.rrd" filter_field="rrd" filter_value="1" step="5" ds_field="rrd1_ds" overwrite="0">
<item rra="RRA:AVERAGE:0.5:1:4320"/>
......@@ -55,7 +55,7 @@ namespace uniset
<item rra="RRA:MAX:0.5:1:4320"/>
</rrd>
</RRDServer1>
\endcode
\endcode
Где:
- \b filename - имя создаваемого rrd-файла
- \b filter_field - поле у датчика, определяющее, что его нужно сохранять в БД
......@@ -66,7 +66,7 @@ namespace uniset
- \b overwrite - [0,1]. Пересоздавать ли БД, если файл уже существует.
При этом в секции <sensors> у датчиков прописываются параметры относящиеся к источнику:
\code
\code
<sensors>
...
<item id="54" iotype="AI" name="AI54_S" textname="AI sensor 54" rrd="1" rrd1_ds="GAUGE:20:U:U"/>
......@@ -75,15 +75,15 @@ namespace uniset
<item id="57" iotype="AI" name="AI57_S" rrd2_ds_dsname='A57MyRRDName' textname="AI sensor 57" rrd="2" rrd2_ds="DERIVE:20:U:U"/>
...
</sensors>
\endcode
\endcode
\section sec_RRD_DSName Именование параметров
По умолчанию в качестве имени параметра берётся поле \b 'ds_field'_dsname='', если это поле не указано, то берётся \b name датчика.
\warning Имя не может превышать RRDServer::RRD_MAX_DSNAME_LEN.
*/
class RRDServer:
*/
class RRDServer:
public UObject_SK
{
{
public:
RRDServer( uniset::ObjectId objId, xmlNode* cnode, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "rrd" );
......@@ -157,8 +157,8 @@ class RRDServer:
private:
std::string prefix;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _RRDServer_H_
......
......@@ -38,9 +38,9 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/*! \page page_SharedMemory Реализация разделямой между процессами памяти (SharedMemory)
/*! \page page_SharedMemory Реализация разделямой между процессами памяти (SharedMemory)
\section sec_SM_Common Задачи решаемые объектом SharedMemory
......@@ -199,7 +199,7 @@ namespace uniset
<br>_31_04_AS - аналоговый (счётчик)
<br>_41_04_S - дискретный ("доступность процесса")
\code
\code
<item default="10" heartbeat="1" heartbeat_ds_name="_41_04_S" heartbeat_node="ses" heartbeat_reboot_msec="10000"
id="103104" iotype="AI" name="_31_04_AS" textname="SES: IO heartbeat"/>
......@@ -208,7 +208,7 @@ namespace uniset
<msg mtype="1" text="КСЭС: отключился ввод/вывод" value="0"/>
</MessagesList>
</item>
\endcode
\endcode
\section sec_SM_History Механизм аварийного дампа
......@@ -318,10 +318,10 @@ namespace uniset
Не обязательные параметры:
sens1,... - список по каким датчикам выдать ответ
/lost - получить список заказчиков с которыми терялась связь (и они удалялись из списка)
*/
class SharedMemory:
*/
class SharedMemory:
public IONotifyController
{
{
public:
SharedMemory( uniset::ObjectId id, const std::string& datafile, const std::string& confname = "" );
virtual ~SharedMemory();
......@@ -532,8 +532,8 @@ class SharedMemory:
private:
HistorySlot m_historySignal;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // SharedMemory_H_
......
......@@ -24,10 +24,10 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
namespace UniSetUDP
{
/*! Для оптимизации размера передаваемх данных, но с учётом того, что ID могут идти не подряд.
// -----------------------------------------------------------------------------
namespace UniSetUDP
{
/*! Для оптимизации размера передаваемх данных, но с учётом того, что 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 @@ struct UDPHeader
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 @@ struct UDPAData
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,11 +168,11 @@ struct UDPMessage:
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
// -----------------------------------------------------------------------------
#endif // UDPPacket_H_
......
......@@ -41,8 +41,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page pageUNetExchangeUDP Сетевой обмен на основе UDP (UNetUDP)
- \ref pgUNetUDP_Common
......@@ -120,11 +120,11 @@ namespace uniset
При загрузке все датчики (относщиеся к данному процессу) разбиваются на группы пакетов согласно своей частоте посылки.
При этом внутри одной группы датчики разбиваются по пакетам согласно заданному максимальному размеру пакета
(см. конструктор класса UNetSender()).
*/
// -----------------------------------------------------------------------------
class UNetExchange:
*/
// -----------------------------------------------------------------------------
class UNetExchange:
public UniSetObject
{
{
public:
UNetExchange( uniset::ObjectId objId, uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "unet" );
virtual ~UNetExchange();
......@@ -267,8 +267,8 @@ class UNetExchange:
int logserv_port = {0};
VMonitor vmon;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // UNetExchange_H_
......
......@@ -35,8 +35,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/* Основная идея: сделать проверку очерёдности пакетов, но при этом использовать UDP.
// -----------------------------------------------------------------------------
/* Основная идея: сделать проверку очерёдности пакетов, но при этом использовать UDP.
* ===============
* Собственно реализация сделана так:
* В данных передаётся номер пакета. На случай если несколько пакетов придут не в той последовательности
......@@ -94,12 +94,12 @@ namespace uniset
* Поддерживается два варианта:
* 'thread' - отдельный поток обновления
* 'evloop' - использование общего с приёмом event loop (libev)
*/
// -----------------------------------------------------------------------------
class UNetReceiver:
*/
// -----------------------------------------------------------------------------
class UNetReceiver:
protected EvWatcher,
public std::enable_shared_from_this<UNetReceiver>
{
{
public:
UNetReceiver( const std::string& host, int port, const std::shared_ptr<SMInterface>& smi, bool nocheckConnection = false );
virtual ~UNetReceiver();
......@@ -343,8 +343,8 @@ class UNetReceiver:
void initDCache( UniSetUDP::UDPMessage& pack, bool force = false ) noexcept;
void initACache( UniSetUDP::UDPMessage& pack, bool force = false ) noexcept;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // UNetReceiver_H_
......
......@@ -24,11 +24,11 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -----------------------------------------------------------------------------
UNetSender::UNetSender(const std::string& _host, const int _port, const std::shared_ptr<SMInterface>& smi,
// -----------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -----------------------------------------------------------------------------
UNetSender::UNetSender(const std::string& _host, const int _port, const std::shared_ptr<SMInterface>& smi,
bool nocheckConnection, const std::string& s_f, const std::string& s_val,
const std::string& s_prefix, size_t maxDCount, size_t maxACount ):
s_field(s_f),
......@@ -45,7 +45,7 @@ UNetSender::UNetSender(const std::string& _host, const int _port, const std::sha
lastcrc(0),
maxAData(maxACount),
maxDData(maxDCount)
{
{
items.reserve(100);
{
......@@ -102,14 +102,14 @@ UNetSender::UNetSender(const std::string& _host, const int _port, const std::sha
unetinfo << myname << "(init): dlist size = " << items.size() << endl;
}
}
}
// -----------------------------------------------------------------------------
UNetSender::~UNetSender()
{
}
// -----------------------------------------------------------------------------
bool UNetSender::createConnection( bool throwEx )
{
}
// -----------------------------------------------------------------------------
UNetSender::~UNetSender()
{
}
// -----------------------------------------------------------------------------
bool UNetSender::createConnection( bool throwEx )
{
unetinfo << myname << "(createConnection): .." << endl;
try
......@@ -144,20 +144,20 @@ bool UNetSender::createConnection( bool throwEx )
}
return (udp != nullptr);
}
// -----------------------------------------------------------------------------
void UNetSender::updateFromSM()
{
}
// -----------------------------------------------------------------------------
void UNetSender::updateFromSM()
{
for( auto && it : items )
{
UItem& i = it.second;
long value = shm->localGetValue(i.ioit, i.id);
updateItem(i, value);
}
}
// -----------------------------------------------------------------------------
void UNetSender::updateSensor( uniset::ObjectId id, long value )
{
}
// -----------------------------------------------------------------------------
void UNetSender::updateSensor( uniset::ObjectId id, long value )
{
if( !shm->isLocalwork() )
return;
......@@ -165,10 +165,10 @@ void UNetSender::updateSensor( uniset::ObjectId id, long value )
if( it != items.end() )
updateItem( it->second, value );
}
// -----------------------------------------------------------------------------
void UNetSender::updateItem( UItem& it, long value )
{
}
// -----------------------------------------------------------------------------
void UNetSender::updateItem( UItem& it, long value )
{
auto& pk = mypacks[it.pack_sendfactor];
auto& mypack(pk[it.pack_num]);
......@@ -178,16 +178,16 @@ void UNetSender::updateItem( UItem& it, long value )
mypack.msg.setDData(it.pack_ind, value);
else if( it.iotype == UniversalIO::AI || it.iotype == UniversalIO::AO )
mypack.msg.setAData(it.pack_ind, value);
}
// -----------------------------------------------------------------------------
void UNetSender::setCheckConnectionPause( int msec )
{
}
// -----------------------------------------------------------------------------
void UNetSender::setCheckConnectionPause( int msec )
{
if( msec > 0 )
ptCheckConnection.setTiming(msec);
}
// -----------------------------------------------------------------------------
void UNetSender::send() noexcept
{
}
// -----------------------------------------------------------------------------
void UNetSender::send() noexcept
{
unetinfo << myname << "(send): dlist size = " << items.size() << endl;
ncycle = 0;
......@@ -265,12 +265,12 @@ void UNetSender::send() noexcept
}
unetinfo << "************* execute FINISH **********" << endl;
}
// -----------------------------------------------------------------------------
// #define UNETUDP_DISABLE_OPTIMIZATION_N1
}
// -----------------------------------------------------------------------------
// #define UNETUDP_DISABLE_OPTIMIZATION_N1
void UNetSender::real_send( PackMessage& mypack ) noexcept
{
void UNetSender::real_send( PackMessage& mypack ) noexcept
{
try
{
uniset::uniset_rwmutex_rlock l(mypack.mut);
......@@ -311,28 +311,28 @@ void UNetSender::real_send( PackMessage& mypack ) noexcept
{
unetcrit << myname << "(real_send): error: " << ex.what() << endl;
}
}
// -----------------------------------------------------------------------------
void UNetSender::stop()
{
}
// -----------------------------------------------------------------------------
void UNetSender::stop()
{
activated = false;
// s_thr->stop();
if( s_thr )
s_thr->join();
}
// -----------------------------------------------------------------------------
void UNetSender::start()
{
}
// -----------------------------------------------------------------------------
void UNetSender::start()
{
if( !activated )
{
activated = true;
s_thr->start();
}
}
// -----------------------------------------------------------------------------
void UNetSender::readConfiguration()
{
}
// -----------------------------------------------------------------------------
void UNetSender::readConfiguration()
{
xmlNode* root = uniset_conf()->getXMLSensorsSection();
if(!root)
......@@ -355,18 +355,18 @@ void UNetSender::readConfiguration()
if( check_filter(it, s_field, s_fvalue) )
initItem(it);
}
}
// ------------------------------------------------------------------------------------------
bool UNetSender::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec )
{
}
// ------------------------------------------------------------------------------------------
bool UNetSender::readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec )
{
if( uniset::check_filter(it, s_field, s_fvalue) )
initItem(it);
return true;
}
// ------------------------------------------------------------------------------------------
bool UNetSender::initItem( UniXML::iterator& it )
{
}
// ------------------------------------------------------------------------------------------
bool UNetSender::initItem( UniXML::iterator& it )
{
string sname( it.getProp("name") );
string tid(it.getProp("id"));
......@@ -498,33 +498,33 @@ bool UNetSender::initItem( UniXML::iterator& it )
items.emplace(p.id, std::move(p));
return true;
}
}
// ------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, UNetSender::UItem& p )
{
// ------------------------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, UNetSender::UItem& p )
{
return os << " sid=" << p.id;
}
// -----------------------------------------------------------------------------
void UNetSender::initIterators()
{
}
// -----------------------------------------------------------------------------
void UNetSender::initIterators()
{
for( auto && it : items )
shm->initIterator(it.second.ioit);
}
// -----------------------------------------------------------------------------
void UNetSender::askSensors( UniversalIO::UIOCommand cmd )
{
}
// -----------------------------------------------------------------------------
void UNetSender::askSensors( UniversalIO::UIOCommand cmd )
{
for( auto && it : items )
shm->askSensor(it.second.id, cmd);
}
// -----------------------------------------------------------------------------
size_t UNetSender::getDataPackCount() const
{
}
// -----------------------------------------------------------------------------
size_t UNetSender::getDataPackCount() const
{
return mypacks.size();
}
// -----------------------------------------------------------------------------
const std::string UNetSender::getShortInfo() const
{
}
// -----------------------------------------------------------------------------
const std::string UNetSender::getShortInfo() const
{
// warning: будет вызываться из другого потока
// (считаем что чтение безопасно)
......@@ -553,6 +553,6 @@ const std::string UNetSender::getShortInfo() const
}
return std::move(s.str());
}
// -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // end of namespace uniset
......@@ -32,8 +32,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*
// -----------------------------------------------------------------------------
/*
* Распределение датчиков по пакетам
* =========================================================================
* Все пересылаемые данные разбиваются на группы по частоте посылки("sendfactor").
......@@ -65,8 +65,8 @@ namespace uniset
* выкинуто исключение при неудачной попытке создания соединения.
* \warning setCheckConnectionPause(msec) должно быть кратно sendpause!
*/
class UNetSender
{
class UNetSender
{
public:
UNetSender( const std::string& host, const int port, const std::shared_ptr<SMInterface>& smi, bool nocheckConnection = false,
const std::string& s_field = "", const std::string& s_fvalue = "", const std::string& prefix = "unet",
......@@ -218,8 +218,8 @@ class UNetSender
size_t ncycle = { 0 }; /*!< номер цикла посылки */
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // UNetSender_H_
......
......@@ -27,8 +27,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
\page pageUniExchange Обмен между узлами на основе TCP.
\par Обмен построен на основе функций IOControl-ера получения списка дискретных
......@@ -49,11 +49,11 @@ namespace uniset
</UniExchange>
\endcode
Запись можно делать по "id" или по "name"
*/
// -----------------------------------------------------------------------------
class UniExchange:
*/
// -----------------------------------------------------------------------------
class UniExchange:
public IOController
{
{
public:
UniExchange( uniset::ObjectId id, uniset::ObjectId shmID,
const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "unet" );
......@@ -145,8 +145,8 @@ class UniExchange:
timeout_t smReadyTimeout = { 15000 }; // msec
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // UniExchange_H_
......@@ -25,12 +25,12 @@
//--------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
// -----------------------------------------------------------------------------
/*!
Класс позволяющий загружать калибровочную
характеристику из конфигурационного (xml)файла и получать по ней точки.
\code
C, калиброванное значение
характеристику из конфигурационного (xml)файла и получать по ней точки.
\code
C, калиброванное значение
^
|
|
......@@ -38,13 +38,13 @@ C, калиброванное значение
|
-------->
R(raw value), сырое значение
\endcode
\endcode
Сами диаграммы представляют из себя следующую секцию в xml
x - сырое значение (по которому ведётся поиск)
y - калиброванное значение
\code
<Calibrations name="Calibrations">
Сами диаграммы представляют из себя следующую секцию в xml
x - сырое значение (по которому ведётся поиск)
y - калиброванное значение
\code
<Calibrations name="Calibrations">
<diagram name="testcal">
<point x="-200" y="-60"/>
<point x="-100" y="-60"/>
......@@ -61,23 +61,23 @@ y - калиброванное значение
...
</diagram>
...
</Calibrations>
\endcode
</Calibrations>
\endcode
Диаграмма позволяет задать множество точек. На отрезках между точками используется линейная аппроксимация.
Диаграмма позволяет задать множество точек. На отрезках между точками используется линейная аппроксимация.
Т.е. часто большую часть времени (во многих задачах) аналоговое значение, меняется в небольших пределах,
то добавлен кэш ( rawValue --> calValue ) по умолчанию на 5 значений. Размер кэша можно задать
(поменять или отключить) при помощи Calibration::setCacheSize().
\note Слишком большим задавать кэш не рекомендуется, т.к. тогда поиск по кэшу будет сопоставим с поиском по диаграмме.
Т.е. часто большую часть времени (во многих задачах) аналоговое значение, меняется в небольших пределах,
то добавлен кэш ( rawValue --> calValue ) по умолчанию на 5 значений. Размер кэша можно задать
(поменять или отключить) при помощи Calibration::setCacheSize().
\note Слишком большим задавать кэш не рекомендуется, т.к. тогда поиск по кэшу будет сопоставим с поиском по диаграмме.
Помимо этого, с учётом того, что каждое попадание в кэш обновляет счётчик обращений к значению, необходимо
пересортировывать весь кэш (чтобы наиболее часто используемые были в начале). Чтобы не делать эту операцию каждый
раз, сделан счётчик циклов. Т.е. через какое количество обращений к кэшу, производить принудительную пересортировку.
Значение по умолчанию - 5(размер кэша). Задать можно при помощи Calibration::setCacheResortCycle()
*/
class Calibration
{
пересортировывать весь кэш (чтобы наиболее часто используемые были в начале). Чтобы не делать эту операцию каждый
раз, сделан счётчик циклов. Т.е. через какое количество обращений к кэшу, производить принудительную пересортировку.
Значение по умолчанию - 5(размер кэша). Задать можно при помощи Calibration::setCacheResortCycle()
*/
class Calibration
{
public:
Calibration();
Calibration( const std::string& name, const std::string& confile = "calibration.xml", size_t reserv = 50 );
......@@ -316,8 +316,8 @@ class Calibration
ValueCache cache;
size_t numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша..
size_t numCallToCache; // текущий счётчик обращений к кэшу
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // Calibration_H_
......
......@@ -26,9 +26,9 @@
//--------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
class DigitalFilter
{
//--------------------------------------------------------------------------
class DigitalFilter
{
public:
DigitalFilter ( unsigned int bufsize = 5, double T = 0, double lsq = 0.2,
int iir_thr = 10000, double iir_coeff_prev = 0.5,
......@@ -121,8 +121,8 @@ class DigitalFilter
// Коэффициенты для рекурсивного фильтра
double coeff_prev;
double coeff_new;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of namespace uniset
//--------------------------------------------------------------------------
#endif // DigitalFilter_H_
......
......@@ -25,30 +25,30 @@
// -------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
namespace extensions
{
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
uniset::ObjectId getSharedMemoryID();
//--------------------------------------------------------------------------
namespace extensions
{
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
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();
}
// -------------------------------------------------------------------------
// "синтаксический сахар"..для логов
#define dinfo if( uniset::extensions::dlog()->debugging(Debug::INFO) ) uniset::extensions::dlog()->info()
#define dwarn if( uniset::extensions::dlog()->debugging(Debug::WARN) ) uniset::extensions::dlog()->warn()
#define dcrit if( uniset::extensions::dlog()->debugging(Debug::CRIT) ) uniset::extensions::dlog()->crit()
......@@ -64,7 +64,7 @@ std::shared_ptr<DebugStream> dlog();
#define dlogsys if( uniset::extensions::dlog()->debugging(Debug::SYSTEM) ) uniset::extensions::dlog()->system()
#define dlogrep if( uniset::extensions::dlog()->debugging(Debug::REPOSITORY) ) uniset::extensions::dlog()->repository()
#define dlogany uniset::extensions::dlog()->any()
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
} // end of namespace uniset
// -------------------------------------------------------------------------
......
......@@ -29,14 +29,14 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
static const int DefaultSubdev = -1;
static const int DefaultChannel = -1;
static const int NoSafety = -1;
// -----------------------------------------------------------------------------
/*! Свойства переменной в/в */
struct IOBase
{
// -----------------------------------------------------------------------------
static const int DefaultSubdev = -1;
static const int DefaultChannel = -1;
static const int NoSafety = -1;
// -----------------------------------------------------------------------------
/*! Свойства переменной в/в */
struct IOBase
{
// т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
IOBase( const IOBase& r ) = delete;
......@@ -198,8 +198,8 @@ struct IOBase
static std::string initProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const std::string& defval = "" );
static int initIntProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const int defval = 0 );
static timeout_t initTimeoutProp( UniXML::iterator& it, const std::string& prop, const std::string& prefix, bool prefonly, const timeout_t defval);
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // IOBase_H_
......
......@@ -22,17 +22,17 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*! ПИД
// -----------------------------------------------------------------------------
/*! ПИД
Формулы выведены на основе разностных уравнений
см. http://atm.h1.ru/root/theory/theory33.html
Он даёт неплохой результат и опимальнее по расчётам
(содержит только умножение, не переполняется
т.к. учитывает только два последних шага)
*/
class PID
{
*/
class PID
{
public:
PID();
~PID();
......@@ -76,8 +76,8 @@ class PID
protected:
private:
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // PID_H_
......
......@@ -26,9 +26,9 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class SMInterface
{
// --------------------------------------------------------------------------
class SMInterface
{
public:
SMInterface( uniset::ObjectId _shmID, const std::shared_ptr<UInterface>& ui,
......@@ -92,8 +92,8 @@ class SMInterface
uniset::ObjectId shmID;
uniset::ObjectId myid;
uniset::uniset_rwmutex shmMutex;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
//--------------------------------------------------------------------------
#endif
......@@ -21,13 +21,13 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
/*! Базовый класс для одиночных процессов.
// --------------------------------------------------------------------------
/*! Базовый класс для одиночных процессов.
Обеспечивает корректное завершение процесса,
даже по сигналам...
*/
class SingleProcess
{
*/
class SingleProcess
{
public:
SingleProcess();
virtual ~SingleProcess();
......@@ -42,8 +42,8 @@ class SingleProcess
static void terminated( int signo );
static void finishterm( int signo );
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// --------------------------------------------------------------------------
#endif // SingleProcess_H_
......
......@@ -26,12 +26,12 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
namespace VTypes
{
/*! Тип переменной для Modbus[RTU|TCP] */
enum VType
{
// -----------------------------------------------------------------------------
namespace VTypes
{
/*! Тип переменной для Modbus[RTU|TCP] */
enum VType
{
vtUnknown,
vtF2, /*!< двойное слово float(4 байта). В виде строки задаётся как \b "F2". */
vtF2r, /*!< двойное слово float(4 байта). С перевёрнутой (reverse) последовательностью слов. \b "F2r". */
......@@ -43,17 +43,17 @@ enum VType
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 @@ class F2
}
F2mem raw;
};
// --------------------------------------------------------------------------
class F2r:
};
// --------------------------------------------------------------------------
class F2r:
public F2
{
{
public:
// ------------------------------------------
......@@ -137,10 +137,10 @@ class F2r:
~F2r() noexcept {}
F2mem raw_backorder;
};
// --------------------------------------------------------------------------
class F4
{
};
// --------------------------------------------------------------------------
class F4
{
public:
// ------------------------------------------
static const size_t f4Size = 4;
......@@ -190,10 +190,10 @@ class F4
}
F4mem raw;
};
// --------------------------------------------------------------------------
class Byte
{
};
// --------------------------------------------------------------------------
class Byte
{
public:
static const size_t bsize = 2;
......@@ -255,10 +255,10 @@ class Byte
}
Bytemem raw;
};
// --------------------------------------------------------------------------
class Unsigned
{
};
// --------------------------------------------------------------------------
class Unsigned
{
public:
// ------------------------------------------
......@@ -294,10 +294,10 @@ class Unsigned
}
unsigned short raw;
};
// --------------------------------------------------------------------------
class Signed
{
};
// --------------------------------------------------------------------------
class Signed
{
public:
// ------------------------------------------
......@@ -333,10 +333,10 @@ class Signed
}
signed short raw;
};
// --------------------------------------------------------------------------
class I2
{
};
// --------------------------------------------------------------------------
class I2
{
public:
// ------------------------------------------
......@@ -383,11 +383,11 @@ class I2
}
I2mem raw;
};
// --------------------------------------------------------------------------
class I2r:
};
// --------------------------------------------------------------------------
class I2r:
public I2
{
{
public:
I2r() noexcept
{
......@@ -410,10 +410,10 @@ class I2r:
~I2r() noexcept {}
I2mem raw_backorder;
};
// --------------------------------------------------------------------------
class U2
{
};
// --------------------------------------------------------------------------
class U2
{
public:
// ------------------------------------------
......@@ -460,11 +460,11 @@ class U2
}
U2mem raw;
};
// --------------------------------------------------------------------------
class U2r:
};
// --------------------------------------------------------------------------
class U2r:
public U2
{
{
public:
U2r() noexcept
{
......@@ -487,11 +487,11 @@ class U2r:
~U2r() {}
U2mem raw_backorder;
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace VTypes
// --------------------------------------------------------------------------
} // end of namespace VTypes
// --------------------------------------------------------------------------
} // end of namespace uniset
// --------------------------------------------------------------------------
#endif // _RTUTypes_H_
......
......@@ -25,8 +25,8 @@ using namespace std;
//--------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
//--------------------------------------------------------------------------
DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
int iir_thr, double iir_coeff_prev,
double iir_coeff_new ):
Ti(T),
......@@ -43,20 +43,20 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
prev(0),
coeff_prev(iir_coeff_prev),
coeff_new(iir_coeff_new)
{
{
buf.resize(maxsize);
mvec.reserve(maxsize);
init(val);
}
//--------------------------------------------------------------------------
DigitalFilter::~DigitalFilter()
{
}
//--------------------------------------------------------------------------
void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
}
//--------------------------------------------------------------------------
DigitalFilter::~DigitalFilter()
{
}
//--------------------------------------------------------------------------
void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
int iir_thr, double iir_coeff_prev,
double iir_coeff_new )
{
{
Ti = T;
maxsize = bufsize;
......@@ -85,10 +85,10 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
lsparam = lsq;
mvec.resize(maxsize);
}
//--------------------------------------------------------------------------
void DigitalFilter::init( int val )
{
}
//--------------------------------------------------------------------------
void DigitalFilter::init( int val )
{
buf.clear();
for( size_t i = 0; i < maxsize; i++ )
......@@ -98,10 +98,10 @@ void DigitalFilter::init( int val )
tmr.reset();
this->val = val;
}
//--------------------------------------------------------------------------
double DigitalFilter::firstLevel()
{
}
//--------------------------------------------------------------------------
double DigitalFilter::firstLevel()
{
// считаем среднее арифметическое
M = 0;
......@@ -143,19 +143,19 @@ double DigitalFilter::firstLevel()
return M;
return ( val / n );
}
//--------------------------------------------------------------------------
int DigitalFilter::filterRC( int rawval )
{
}
//--------------------------------------------------------------------------
int DigitalFilter::filterRC( int rawval )
{
if( Ti <= 0 )
return rawval;
return lroundf(secondLevel(rawval));
}
//--------------------------------------------------------------------------
}
//--------------------------------------------------------------------------
double DigitalFilter::secondLevel( double rawval )
{
double DigitalFilter::secondLevel( double rawval )
{
if( Ti <= 0 )
return rawval;
......@@ -171,19 +171,19 @@ double DigitalFilter::secondLevel( double rawval )
val = (rawval + Ti * val / dt) / (Ti / dt + 1);
return val;
}
//--------------------------------------------------------------------------
int DigitalFilter::filter1( int newval )
{
}
//--------------------------------------------------------------------------
int DigitalFilter::filter1( int newval )
{
if( maxsize < 1 )
return newval;
add(newval);
return lroundf(firstLevel());
}
//--------------------------------------------------------------------------
void DigitalFilter::add( int newval )
{
}
//--------------------------------------------------------------------------
void DigitalFilter::add( int newval )
{
// помещаем очередное значение в буфер
// удаляя при этом старое (FIFO)
......@@ -193,20 +193,20 @@ void DigitalFilter::add( int newval )
// buf.pop_front();
buf.pop_front();
buf.push_back(newval);
}
//--------------------------------------------------------------------------
int DigitalFilter::current1()
{
}
//--------------------------------------------------------------------------
int DigitalFilter::current1()
{
return lroundf(firstLevel());
}
//--------------------------------------------------------------------------
int DigitalFilter::currentRC()
{
}
//--------------------------------------------------------------------------
int DigitalFilter::currentRC()
{
return lroundf(secondLevel(current1()));
}
//--------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const DigitalFilter& d )
{
}
//--------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const DigitalFilter& d )
{
os << "(" << d.buf.size() << ")[";
for( auto& i : d.buf )
......@@ -214,15 +214,15 @@ std::ostream& operator<<(std::ostream& os, const DigitalFilter& d )
os << " ]";
return os;
}
//--------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const DigitalFilter* d)
{
}
//--------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const DigitalFilter* d)
{
return os << (*d);
}
//--------------------------------------------------------------------------
int DigitalFilter::median( int newval )
{
}
//--------------------------------------------------------------------------
int DigitalFilter::median( int newval )
{
if( maxsize < 1 )
return newval;
......@@ -233,10 +233,10 @@ int DigitalFilter::median( int newval )
mvec_sorted = true;
return mvec[maxsize / 2];
}
//--------------------------------------------------------------------------
int DigitalFilter::currentMedian()
{
}
//--------------------------------------------------------------------------
int DigitalFilter::currentMedian()
{
if( !mvec_sorted )
{
mvec.assign(buf.begin(), buf.end());
......@@ -245,10 +245,10 @@ int DigitalFilter::currentMedian()
}
return mvec[maxsize / 2];
}
//--------------------------------------------------------------------------
int DigitalFilter::leastsqr( int newval )
{
}
//--------------------------------------------------------------------------
int DigitalFilter::leastsqr( int newval )
{
ls = 0;
add(newval);
......@@ -270,15 +270,15 @@ int DigitalFilter::leastsqr( int newval )
w[i] = w[i] + *it * u;
return lroundf(ls);
}
//--------------------------------------------------------------------------
int DigitalFilter::currentLS()
{
}
//--------------------------------------------------------------------------
int DigitalFilter::currentLS()
{
return lroundf(ls);
}
//--------------------------------------------------------------------------
int DigitalFilter::filterIIR( int newval )
{
}
//--------------------------------------------------------------------------
int DigitalFilter::filterIIR( int newval )
{
if( newval > prev + thr || newval < prev - thr || maxsize < 1 )
{
if( maxsize > 0 )
......@@ -300,11 +300,11 @@ int DigitalFilter::filterIIR( int newval )
}
return prev;
}
//--------------------------------------------------------------------------
int DigitalFilter::currentIIR()
{
}
//--------------------------------------------------------------------------
int DigitalFilter::currentIIR()
{
return prev;
}
//--------------------------------------------------------------------------
}
//--------------------------------------------------------------------------
} // end of namespace uniset
......@@ -24,13 +24,13 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
namespace extensions
{
static std::shared_ptr<DebugStream> _dlog;
// -------------------------------------------------------------------------
namespace extensions
{
static std::shared_ptr<DebugStream> _dlog;
std::shared_ptr<DebugStream> dlog()
{
std::shared_ptr<DebugStream> dlog()
{
if( _dlog )
return _dlog;
......@@ -44,12 +44,12 @@ std::shared_ptr<DebugStream> dlog()
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 @@ uniset::ObjectId getSharedMemoryID()
// 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 @@ void escape_string( string& s )
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 @@ xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
}
return 0;
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
xmlNode* root = getCalibrationsSection();
if( !root )
......@@ -139,10 +139,10 @@ Calibration* buildCalibrationDiagram( const std::string& dname )
}
return new Calibration(dnode);
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
while(1)
{
int istatus;
......@@ -152,8 +152,8 @@ void on_sigchild( int sig )
if( pid <= 0 ) break;
}
}
// --------------------------------------------------------------------------
} // end of namespace extensions
}
// --------------------------------------------------------------------------
} // end of namespace extensions
} // end of namespace uniset
// -------------------------------------------------------------------------
......@@ -21,8 +21,8 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
PID::PID():
// -----------------------------------------------------------------------------
PID::PID():
Y(0), Kc(0),
Ti(0), Td(0),
vlim(2.0),
......@@ -30,20 +30,20 @@ PID::PID():
d1(0),
d2(0),
prevTs(0)
{
{
reset();
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
PID::~PID()
{
PID::~PID()
{
}
}
// -----------------------------------------------------------------------------
void PID::step( const double& X, const double& Z, const double& Ts )
{
// -----------------------------------------------------------------------------
void PID::step( const double& X, const double& Z, const double& Ts )
{
// Чтобы не пересчитывать коэффициенты на каждом шаге
// сделан пересчёт только по изменению
......@@ -69,15 +69,15 @@ void PID::step( const double& X, const double& Z, const double& Ts )
if( Y > vlim ) Y = vlim;
else if ( Y < -vlim ) Y = -vlim;
}
// -----------------------------------------------------------------------------
void PID::reset()
{
}
// -----------------------------------------------------------------------------
void PID::reset()
{
sub2 = sub1 = sub = Y = 0;
}
// -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, PID& p )
{
}
// -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, PID& p )
{
return os << "Kc=" << std::setw(4) << p.Kc
<< " Ti=" << std::setw(4) << p.Ti
<< " Td=" << std::setw(4) << p.Td
......@@ -86,16 +86,16 @@ std::ostream& operator<<( std::ostream& os, PID& p )
<< " sub2=" << setw(4) << p.sub2
<< " sub1=" << setw(4) << p.sub1
<< " sub=" << setw(4) << p.sub;
}
// --------------------------------------------------------------------------
}
// --------------------------------------------------------------------------
void PID::recalc()
{
void PID::recalc()
{
// d0 = 1+prevTs/Ti+Td/prevTs;
// d1 = -1-2*Td/prevTs;
d2 = Td / prevTs;
d1 = -1 - 2 * d2;
d0 = 1 + prevTs / Ti + d2;
}
// --------------------------------------------------------------------------
}
// --------------------------------------------------------------------------
} // end of namespace uniset
......@@ -24,27 +24,27 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------------
using namespace std;
// --------------------------------------------------------------------------------
/*! замок для блокирования совместного доступа к функции обрабтки сигналов */
static std::atomic_bool procterm;
static std::atomic_bool doneterm;
static SingleProcess* gMain = NULL;
static const int TERMINATE_TIMEOUT = 2; // время отведенное на завершение процесса [сек]
// --------------------------------------------------------------------------------
SingleProcess::SingleProcess()
{
// --------------------------------------------------------------------------------
using namespace std;
// --------------------------------------------------------------------------------
/*! замок для блокирования совместного доступа к функции обрабтки сигналов */
static std::atomic_bool procterm;
static std::atomic_bool doneterm;
static SingleProcess* gMain = NULL;
static const int TERMINATE_TIMEOUT = 2; // время отведенное на завершение процесса [сек]
// --------------------------------------------------------------------------------
SingleProcess::SingleProcess()
{
gMain = this;
}
}
// --------------------------------------------------------------------------------
SingleProcess::~SingleProcess()
{
}
// --------------------------------------------------------------------------------
void SingleProcess::finishterm( int signo )
{
// --------------------------------------------------------------------------------
SingleProcess::~SingleProcess()
{
}
// --------------------------------------------------------------------------------
void SingleProcess::finishterm( int signo )
{
if( !doneterm )
{
cerr << "(SingleProcess:finishterm): прерываем процесс завершения...!" << endl << flush;
......@@ -53,10 +53,10 @@ void SingleProcess::finishterm( int signo )
doneterm = 1;
raise(SIGKILL);
}
}
// ------------------------------------------------------------------------------------------
void SingleProcess::terminated( int signo )
{
}
// ------------------------------------------------------------------------------------------
void SingleProcess::terminated( int signo )
{
if( !signo || doneterm || !gMain || procterm )
return;
......@@ -77,10 +77,10 @@ void SingleProcess::terminated( int signo )
raise(signo);
}
}
}
// --------------------------------------------------------------------------------
void SingleProcess::set_signals( bool ask )
{
}
// --------------------------------------------------------------------------------
void SingleProcess::set_signals( bool ask )
{
struct sigaction act, oact;
sigemptyset(&act.sa_mask);
......@@ -110,6 +110,6 @@ void SingleProcess::set_signals( bool ask )
sigaction(SIGQUIT, &act, &oact);
// sigaction(SIGSEGV, &act, &oact);
}
// --------------------------------------------------------------------------------
}
// --------------------------------------------------------------------------------
} // end of namespace uniset
......@@ -21,17 +21,17 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
namespace VTypes
{
// --------------------------------------------------------------------------
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 @@ VType str2type( const std::string& s ) noexcept
return vtU2r;
return vtUnknown;
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
if( t == vtByte )
return "Byte";
......@@ -98,10 +98,10 @@ string type2str( VType t ) noexcept
return "U2r";
return "vtUnknown";
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
if( t == vtByte )
return Byte::wsize();
......@@ -124,9 +124,9 @@ int wsize( const VType t ) noexcept
return U2::wsize();
return 1;
}
// -----------------------------------------------------------------------------
} // end of namespace VTypes
// -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // end of namespace VTypes
// -----------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
......@@ -28,18 +28,18 @@
//-----------------------------------------------------------------------------
namespace uniset
{
class LimitTimers:
class LimitTimers:
public uniset::Exception
{
{
public:
LimitTimers(): Exception("LimitTimers") {}
/*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */
LimitTimers(const std::string& err): Exception(err) {}
};
//----------------------------------------------------------------------------------------
};
//----------------------------------------------------------------------------------------
/*!
/*!
* \brief Таймер
* \author Pavel Vainerman
* \par
......@@ -65,11 +65,11 @@ class LimitTimers:
*
* \note Каждый экземпляр класса CallbackTimer создает поток, поэтому \b желательно не создавать больше одного экземпляра,
* для одного процесса (чтобы не порождать много потоков).
*/
template <class Caller>
class CallbackTimer
// public PassiveTimer
{
*/
template <class Caller>
class CallbackTimer
// public PassiveTimer
{
public:
/*! Максимальное количество таймеров */
......@@ -135,10 +135,10 @@ class CallbackTimer
}
size_t id;
};
};
//----------------------------------------------------------------------------------------
};
//----------------------------------------------------------------------------------------
#include "CallbackTimer.tcc"
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
} // end of uniset namespace
//----------------------------------------------------------------------------------------
# endif //CallbackTimer_H_
......@@ -26,8 +26,8 @@
namespace uniset
{
class ComPort
{
class ComPort
{
public:
enum Speed
{
......@@ -143,8 +143,8 @@ class ComPort
private:
struct termios oldTermios = { 0 };
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
#endif // _COMPORT_H_
......
......@@ -23,7 +23,7 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*!
/*!
Класс для обмена через 485 интерфейс СПЕЦИАЛЬНО
для контроллеров фирмы Fastwel.
Управляет приёмо/передатчиком. Удаляет "эхо"
......@@ -33,10 +33,10 @@ namespace uniset
module 8250_pnp
gpio_num=5 dev: /dev/ttyS2
gpio_num=6 dev: /dev/ttyS3
*/
class ComPort485F:
*/
class ComPort485F:
public ComPort
{
{
public:
ComPort485F( const std::string& comDevice, int gpio_num, bool tmit_ctrl = false );
......@@ -65,8 +65,8 @@ class ComPort485F:
bool tmit_ctrl_on;
PassiveTimer ptRecv;
timeout_t tout_msec = { 2000 };
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
#endif // COMPORT_485F_H_
......
......@@ -13,8 +13,8 @@ namespace uniset
{
class EvWatcher
{
class EvWatcher
{
public:
EvWatcher() {}
virtual ~EvWatcher() {}
......@@ -31,9 +31,9 @@ class EvWatcher
{
return "";
}
};
// -------------------------------------------------------------------------
/*!
};
// -------------------------------------------------------------------------
/*!
* \brief The CommonEventLoop class
* Реализация механизма "один eventloop, много подписчиков" (libev).
* Создаётся один CommonEventLoop который обслуживает множество EvWatcher-ов.
......@@ -49,8 +49,8 @@ class EvWatcher
* запуска event loop, то задействован механизм асинхронного уведомления (см. evprep, onPrepapre) и ожидания
* на condition_variable, когда произойдёт инициализация (см. реализацию evrun()).
*/
class CommonEventLoop
{
class CommonEventLoop
{
public:
CommonEventLoop() noexcept;
......@@ -108,8 +108,8 @@ class CommonEventLoop
std::condition_variable prep_event;
std::mutex prep_mutex;
std::atomic_bool prep_notify = { false };
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // CommonEventLoop_H_
......
......@@ -37,13 +37,13 @@
*/
namespace uniset
{
/*!
/*!
Конфигуратор системы
\note В случае обнаружения критической ошибки в настроечном файле файле.
Вырабатывает исключение и прекращает работу.
*/
class Configuration
{
*/
class Configuration
{
public:
virtual ~Configuration();
......@@ -227,17 +227,17 @@ class Configuration
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
// --------------------------------------------------------------------------
// "синтаксический сахар"..для логов
......
......@@ -8,11 +8,11 @@
// --------------------------------------------------------------------------
namespace uniset
{
class DBResult;
class DBResult;
/*! Абстрактный класс для доступа к БД */
class DBInterface
{
/*! Абстрактный класс для доступа к БД */
class DBInterface
{
public:
DBInterface() {};
......@@ -29,10 +29,10 @@ class DBInterface
virtual bool insert( const std::string& q ) = 0;
virtual double insert_id() = 0;
virtual const std::string error() = 0;
};
// ----------------------------------------------------------------------------------
class DBNetInterface : public DBInterface
{
};
// ----------------------------------------------------------------------------------
class DBNetInterface : public DBInterface
{
public:
DBNetInterface() {};
......@@ -42,10 +42,10 @@ class DBNetInterface : public DBInterface
virtual bool connect( const std::string& param );
virtual bool nconnect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname, unsigned int port ) = 0;
};
// ----------------------------------------------------------------------------------
class DBResult
{
};
// ----------------------------------------------------------------------------------
class DBResult
{
public:
DBResult() {}
......@@ -78,10 +78,10 @@ class DBResult
protected:
ROW row_;
};
// ----------------------------------------------------------------------------------
struct DBInterfaceDeleter
{
};
// ----------------------------------------------------------------------------------
struct DBInterfaceDeleter
{
void operator()(DBInterface* p) const
{
try
......@@ -90,11 +90,11 @@ struct DBInterfaceDeleter
}
catch(...) {}
}
};
// ----------------------------------------------------------------------------------
// the types of the class factories
typedef std::shared_ptr<DBInterface> create_dbinterface_t();
// --------------------------------------------------------------------------
};
// ----------------------------------------------------------------------------------
// the types of the class factories
typedef std::shared_ptr<DBInterface> create_dbinterface_t();
// --------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // DBInterface_H_
......
......@@ -29,7 +29,7 @@
//------------------------------------------------------------------------------------------
namespace uniset
{
/*!
/*!
\page ServicesPage
\section secDBServer Сервис ведения БД
\subsection subDBS_common Общие сведения
......@@ -45,12 +45,12 @@ namespace uniset
uniset::Configuration::getDBServer() объекта uniset::conf.
Реализацию см. \ref page_DBServer_MySQL и \ref page_DBServer_SQLite
*/
*/
/*! Прототип реализации сервиса ведения БД */
class DBServer:
/*! Прототип реализации сервиса ведения БД */
class DBServer:
public UniSetObject
{
{
public:
DBServer( uniset::ObjectId id, const std::string& prefix = "db" );
DBServer( const std::string& prefix = "db" );
......@@ -77,8 +77,8 @@ class DBServer:
const std::string prefix = { "db" };
private:
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
//------------------------------------------------------------------------------------------
#endif
......@@ -21,13 +21,13 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*! Таймер реализующий задержку на срабатывание и отпускание сигнала.
/*! Таймер реализующий задержку на срабатывание и отпускание сигнала.
Для проверки вызывается функция check( state ), где state - это текущее состояние
сигнала, а функция check() возвращает сигнал с задержкой.
Чтобы состояние переключилось, оно должно продержаться не менее заданного времени.
*/
class DelayTimer
{
*/
class DelayTimer
{
public:
DelayTimer() {}
......@@ -153,8 +153,8 @@ class DelayTimer
timeout_t offDelay = { 0 };
bool waiting_on = { false };
bool waiting_off = { false };
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
#endif
......
......@@ -8,13 +8,13 @@
// -------------------------------------------------------------------------
namespace uniset
{
/*!
/*!
* \brief The EventLoopServer class
* Реализация общей части всех процессов использующих libev.
* Содержит свой (динамический) eventloop;
*/
class EventLoopServer
{
class EventLoopServer
{
public:
EventLoopServer();
......@@ -47,8 +47,8 @@ class EventLoopServer
ev::async evterm;
std::shared_ptr<std::thread> thr;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // EventLoopServer_H_
......
......@@ -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 @@ class Exception:
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_
......
......@@ -24,7 +24,7 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*! Песочные часы. Класс реализующий логику песочных часов.
/*! Песочные часы. Класс реализующий логику песочных часов.
Удобен для создания задержек на срабатывание и на отпускание
(как фильтр от кратковременных изменений) с "накоплением времени".
Аналогия с песочными часами:
......@@ -46,7 +46,7 @@ namespace uniset
Если температура станет меньше порога через 6 секунд ("песок начнёт обратно пересыпаться"),
а потом опять станет выше, то до срабатывания check() == true уже останется 4 сек, а не 10 сек.
Получается, что для срабатывания check()=true сигнал должен не колеблясь держаться больше заданного времени.
\code
\code
HourGlass hg;
hg.run(10000); // настраиваем часы на 10 сек..
......@@ -56,10 +56,10 @@ namespace uniset
isOverheating = hg.check();
}
\endcode
*/
class HourGlass
{
\endcode
*/
class HourGlass
{
public:
HourGlass() noexcept {}
~HourGlass() noexcept {}
......@@ -191,8 +191,8 @@ class HourGlass
bool _state = { false }; /*!< текущее "положение часов", true - прямое, false - обратное (перевёрнутое) */
timeout_t _sand = { 0 }; /*!< сколько песка ещё осталось.. */
timeout_t _size = { 0 }; /*!< размер часов */
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
#endif
......
......@@ -33,11 +33,11 @@
//---------------------------------------------------------------------------
namespace uniset
{
/*! Реализация интерфейса IOController-а */
class IOController:
/*! Реализация интерфейса IOController-а */
class IOController:
public UniSetManager,
public POA_IOController_i
{
{
public:
IOController( const std::string& name, const std::string& section );
......@@ -350,8 +350,8 @@ class IOController:
return std::move(sm);
}
};
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// --------------------------------------------------------------------------
#endif
......
......@@ -27,11 +27,11 @@
// --------------------------------------------------------------------------
namespace uniset
{
/*! Класс работы с файлами содержащими IOR объекта
/*! Класс работы с файлами содержащими IOR объекта
\todo Для оптимизации можно сделать кэширование id:node > filename
*/
class IORFile
{
*/
class IORFile
{
public:
IORFile();
......@@ -44,8 +44,8 @@ class IORFile
protected:
private:
};
// -----------------------------------------------------------------------------------------
};
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
......@@ -29,10 +29,10 @@
//---------------------------------------------------------------------------
namespace uniset
{
class UniSetObject;
class UniSetObject;
//---------------------------------------------------------------------------
/*! \class LT_Object
//---------------------------------------------------------------------------
/*! \class LT_Object
\note '_LT' - это "local timers".
Класс реализующий механиз локальных таймеров. Обеспечивает более надёжную работу
......@@ -92,9 +92,9 @@ class UniSetObject;
\sa TimerService
\todo Подумать.. может перейти на unordered_map
*/
class LT_Object
{
*/
class LT_Object
{
public:
LT_Object();
virtual ~LT_Object();
......@@ -203,8 +203,8 @@ class LT_Object
/*! замок для блокирования совместного доступа к cписку таймеров */
uniset::uniset_rwmutex lstMutex;
PassiveTimer tmLast;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
//--------------------------------------------------------------------------
#endif
......@@ -28,7 +28,7 @@
// -------------------------------------------------------------------------
namespace uniset
{
/*!
/*!
\page page_LogAgregator Агрегатор логов (LogAgregator)
- \ref sec_LogA_Comm
......@@ -123,15 +123,15 @@ namespace uniset
}
\endcode
\note Полнота и формат поддерживаемых регулярных выражений зависит от поддержки компилятором стандарта с++11 (класс <regex>).
*/
// -------------------------------------------------------------------------
/* Т.к. в других агрегаторах может тоже встречаться такие же логи, приходится отдельно вести
*/
// -------------------------------------------------------------------------
/* Т.к. в других агрегаторах может тоже встречаться такие же логи, приходится отдельно вести
* учёт подключений (conmap) и подключаться к потокам напрямую, а не к агрегатору
* иначе будет происходить дублирование информации на экране (логи смешиваются от разных агрегаторов)
*/
class LogAgregator:
*/
class LogAgregator:
public DebugStream
{
{
public:
const std::string sep = {"/"}; /*< раздедитель для имён подчинённых агрегаторов */
......@@ -203,8 +203,8 @@ class LogAgregator:
typedef std::unordered_map<std::shared_ptr<DebugStream>, sigc::connection> ConnectionMap;
ConnectionMap conmap;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // LogAgregator_H_
......
......@@ -28,8 +28,8 @@
namespace uniset
{
class LogReader
{
class LogReader
{
public:
LogReader();
......@@ -106,8 +106,8 @@ class LogReader
std::shared_ptr<DebugStream> outlog; // рабочий лог в который выводиться полученная информация..
DebugStream::StreamEvent_Signal m_logsig;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // LogReader_H_
......
......@@ -36,18 +36,18 @@
// -------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
class LogSession;
class LogAgregator;
class NullLogSession;
// -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер
// -------------------------------------------------------------------------
class LogSession;
class LogAgregator;
class NullLogSession;
// -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер
Лог сервер предназначен для возможности удалённого чтения логов (DebugStream).
Ему указывается host и port для прослушивания запросов, которые можно делать при помощи
LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession).
При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов,
записью, отключением записи или ротацией файла с логами. DebugStream за которым ведётся "слежение"
задаётся в конструкторе для LogServer.
Ему указывается host и port для прослушивания запросов, которые можно делать при помощи
LogReader. Читающих клиентов может быть скольугодно много, на каждого создаётся своя "сессия"(LogSession).
При этом через лог сервер имеется возможность управлять включением или отключением определённых уровней логов,
записью, отключением записи или ротацией файла с логами. DebugStream за которым ведётся "слежение"
задаётся в конструкторе для LogServer.
По умолчанию, при завершении \b ВСЕХ подключений, LogServer автоматически восстанавливает уровни логов,
которые были на момент \b первого \b подключения.
......@@ -56,16 +56,16 @@ LogReader. Читающих клиентов может быть скольуг
Для этого LogServer подключается к сигналу на получение команд у каждой сессии и сам обрабатывает команды,
на сохранение, восстановление и показ текущих "умолчательных" логов.
\code
\code
DebugStream mylog;
LogServer logsrv(mylog);
...
logsrv.run(host,port,create_thread);
...
\endcode
\endcode
При этом если необходимо управлять или читать сразу несколько логов можно воспользоваться специальным классом LogAgregator.
\code
При этом если необходимо управлять или читать сразу несколько логов можно воспользоваться специальным классом LogAgregator.
\code
auto log1 = make_shared<DebugStream>();
log1->setLogName("log1");
......@@ -80,18 +80,18 @@ LogReader. Читающих клиентов может быть скольуг
...
logsrv.run(host,port,create_thread);
...
\endcode
\endcode
\warning Логи отдаются "клиентам" только целоиком строкой. Т.е. по сети информация передаваться не будет пока не будет записан "endl".
\warning Логи отдаются "клиентам" только целоиком строкой. Т.е. по сети информация передаваться не будет пока не будет записан "endl".
Это сделано для "оптимизации передачи" (чтобы не передавать каждый байт)
\warning Т.к. LogServer в основном только отдаёт "клиентам" логи, то он реализован с использованием CommonEventLoop,
т.е. у всех LogServer будет ОДИН ОБЩИЙ event loop.
*/
// -------------------------------------------------------------------------
class LogServer:
\warning Т.к. LogServer в основном только отдаёт "клиентам" логи, то он реализован с использованием CommonEventLoop,
т.е. у всех LogServer будет ОДИН ОБЩИЙ event loop.
*/
// -------------------------------------------------------------------------
class LogServer:
protected EvWatcher
{
{
public:
LogServer( std::shared_ptr<DebugStream> log );
......@@ -179,8 +179,8 @@ class LogServer:
Poco::UInt16 port = { 0 };
std::atomic_bool isrunning = { false };
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // LogServer_H_
......
......@@ -23,11 +23,11 @@
namespace uniset
{
namespace LogServerTypes
{
const unsigned int MAGICNUM = 0x20160417;
enum Command
{
namespace LogServerTypes
{
const unsigned int MAGICNUM = 0x20160417;
enum Command
{
cmdNOP, /*!< отсутствие команды */
cmdSetLevel, /*!< установить уровень вывода */
cmdAddLevel, /*!< добавить уровень вывода */
......@@ -45,12 +45,12 @@ enum Command
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,11 +67,11 @@ struct lsMessage
// для команды '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
// -------------------------------------------------------------------------
#endif // LogServerTypes_H_
......
......@@ -34,9 +34,9 @@
namespace uniset
{
/*! Реализация "сессии" для клиентов LogServer. */
class LogSession
{
/*! Реализация "сессии" для клиентов LogServer. */
class LogSession
{
public:
LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugStream>& log, timeout_t cmdTimeout = 2000, timeout_t checkConnectionTime = 10000 );
......@@ -146,8 +146,8 @@ class LogSession
LogSessionCommand_Signal m_command_sig;
DebugStream mylog;
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
// -------------------------------------------------------------------------
#endif // LogSession_H_
......
......@@ -27,7 +27,7 @@ typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//--------------------------------------------------------------------------
namespace uniset
{
/*! \class MQAtomic
/*! \class MQAtomic
* Очередь сообщений на основе atomic переменных.
*
* Чтобы избежать работы с mutex, очередь построена по принципу циклического буфера,
......@@ -58,9 +58,9 @@ namespace uniset
* --------------------------------
* ЭТА ОЧЕРЕДЬ ПОКАЗЫВАЕТ В ТРИ РАЗА ЛУЧШУЮ СКОРОСТЬ ПО СРАВНЕНИЮ С MQMutex
* --------------------------------
*/
class MQAtomic
{
*/
class MQAtomic
{
public:
MQAtomic( size_t qsize = 2000 );
......@@ -130,8 +130,8 @@ class MQAtomic
// статистическая информация
size_t stMaxQueueMessages = { 0 }; /*!< Максимальное число сообщений хранившихся в очереди */
size_t stCountOfLostMessages = { 0 }; /*!< количество переполнений очереди сообщений */
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
//---------------------------------------------------------------------------
#endif
......
......@@ -25,11 +25,11 @@
//--------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//--------------------------------------------------------------------------
/*! \class MQMutex
/*! \class MQMutex
* Простая "многопоточная" очередь сообщений с использованием std::mutex.
* Максимальное ограничение на размер очереди сообщений задаётся функцией setMaxSizeOfMessageQueue().
*
......@@ -39,9 +39,9 @@ typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
* lostNewData - в случае переполнения теряются новые данные (т.е. не будут помещаться в очередь)
* lostOldData - в случае переполнения очереди, старые данные затираются новыми.
*
*/
class MQMutex
{
*/
class MQMutex
{
public:
MQMutex( size_t qsize = 2000 );
......@@ -102,8 +102,8 @@ class MQMutex
// статистическая информация
size_t stMaxQueueMessages = { 0 }; /*!< Максимальное число сообщений хранившихся в очереди */
size_t stCountOfLostMessages = { 0 }; /*!< количество переполнений очереди сообщений */
};
// -------------------------------------------------------------------------
};
// -------------------------------------------------------------------------
} // end of uniset namespace
//---------------------------------------------------------------------------
#endif
......
......@@ -30,8 +30,8 @@
// --------------------------------------------------------------------------
namespace uniset
{
class Message
{
class Message
{
public:
enum TypeOfMessage
{
......@@ -78,13 +78,13 @@ class Message
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 @@ class VoidMessage : public Message
}
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 @@ class SensorMessage : public Message
{
return transport(*this);
}
};
};
// ------------------------------------------------------------------------
/*! Системное сообщение */
class SystemMessage : public Message
{
// ------------------------------------------------------------------------
/*! Системное сообщение */
class SystemMessage : public Message
{
public:
enum Command
{
......@@ -200,14 +200,14 @@ class SystemMessage : public Message
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 @@ class TimerMessage : public Message
}
uniset::TimerId id; /*!< id сработавшего таймера */
};
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Подтверждение(квитирование) сообщения */
class ConfirmMessage: public Message
{
/*! Подтверждение(квитирование) сообщения */
class ConfirmMessage: public Message
{
public:
inline TransportMessage transport_msg() const noexcept
......@@ -267,7 +267,7 @@ class ConfirmMessage: public Message
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 @@ class uniset_rwmutex
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 @@ class uniset_rwmutex_wrlock
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 @@ class uniset_rwmutex_rlock
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
This source diff could not be displayed because it is too large. You can view the blob instead.
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