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

make style

parent b372950f
......@@ -107,7 +107,7 @@ void MBSlave::sigterm( int signo )
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply )
ReadCoilRetMessage& reply )
{
if( verbose )
cout << "(readCoilStatus): " << query << endl;
......@@ -136,7 +136,7 @@ ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query,
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::readInputStatus( ReadInputStatusMessage& query,
ReadInputStatusRetMessage& reply )
ReadInputStatusRetMessage& reply )
{
if( verbose )
cout << "(readInputStatus): " << query << endl;
......@@ -276,7 +276,7 @@ ModbusRTU::mbErrCode MBSlave::readOutputRegisters(
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply )
ModbusRTU::ForceCoilsRetMessage& reply )
{
if( verbose )
cout << "(forceMultipleCoils): " << query << endl;
......@@ -310,7 +310,7 @@ ModbusRTU::mbErrCode MBSlave::writeOutputSingleRegister( ModbusRTU::WriteSingleO
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply )
ModbusRTU::ForceSingleCoilRetMessage& reply )
{
if( verbose )
cout << "(forceSingleCoil): " << query << endl;
......@@ -322,7 +322,7 @@ ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply )
ModbusRTU::JournalCommandRetMessage& reply )
{
if( verbose )
cout << "(journalCommand): " << query << endl;
......@@ -359,7 +359,7 @@ ModbusRTU::mbErrCode MBSlave::journalCommand( ModbusRTU::JournalCommandMessage&
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply )
ModbusRTU::SetDateTimeRetMessage& reply )
{
if( verbose )
cout << "(setDateTime): " << query << endl;
......@@ -371,14 +371,14 @@ ModbusRTU::mbErrCode MBSlave::setDateTime( ModbusRTU::SetDateTimeMessage& query,
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply )
ModbusRTU::RemoteServiceRetMessage& reply )
{
cerr << "(remoteService): " << query << endl;
return ModbusRTU::erOperationFailed;
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply )
ModbusRTU::FileTransferRetMessage& reply )
{
if( verbose )
cout << "(fileTransfer): " << query << endl;
......@@ -459,7 +459,7 @@ ModbusRTU::mbErrCode MBSlave::fileTransfer( ModbusRTU::FileTransferMessage& quer
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply )
ModbusRTU::DiagnosticRetMessage& reply )
{
if( verbose )
cout << "(diagnostics): " << query << endl;
......
......@@ -43,26 +43,26 @@ class MBSlave
/*! обработка 0x01 */
uniset::ModbusRTU::mbErrCode readCoilStatus( uniset::ModbusRTU::ReadCoilMessage& query,
uniset::ModbusRTU::ReadCoilRetMessage& reply );
uniset::ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
uniset::ModbusRTU::mbErrCode readInputStatus( uniset::ModbusRTU::ReadInputStatusMessage& query,
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
uniset::ModbusRTU::mbErrCode readOutputRegisters( uniset::ModbusRTU::ReadOutputMessage& query,
uniset::ModbusRTU::ReadOutputRetMessage& reply );
uniset::ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
uniset::ModbusRTU::mbErrCode readInputRegisters( uniset::ModbusRTU::ReadInputMessage& query,
uniset::ModbusRTU::ReadInputRetMessage& reply );
uniset::ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
uniset::ModbusRTU::mbErrCode forceSingleCoil( uniset::ModbusRTU::ForceSingleCoilMessage& query,
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
uniset::ModbusRTU::mbErrCode forceMultipleCoils( uniset::ModbusRTU::ForceCoilsMessage& query,
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
......@@ -75,21 +75,21 @@ class MBSlave
/*! обработка запросов на чтение ошибок */
uniset::ModbusRTU::mbErrCode journalCommand( uniset::ModbusRTU::JournalCommandMessage& query,
uniset::ModbusRTU::JournalCommandRetMessage& reply );
uniset::ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
uniset::ModbusRTU::mbErrCode setDateTime( uniset::ModbusRTU::SetDateTimeMessage& query,
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
uniset::ModbusRTU::mbErrCode remoteService( uniset::ModbusRTU::RemoteServiceMessage& query,
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::mbErrCode fileTransfer( uniset::ModbusRTU::FileTransferMessage& query,
uniset::ModbusRTU::FileTransferRetMessage& reply );
uniset::ModbusRTU::FileTransferRetMessage& reply );
uniset::ModbusRTU::mbErrCode diagnostics( uniset::ModbusRTU::DiagnosticMessage& query,
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::mbErrCode read4314( uniset::ModbusRTU::MEIMessageRDI& query,
uniset::ModbusRTU::MEIMessageRetRDI& reply );
......
......@@ -83,7 +83,7 @@ void MBTCPServer::sigterm( int signo )
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply )
ReadCoilRetMessage& reply )
{
if( verbose )
cout << "(readCoilStatus): " << query << endl;
......@@ -168,7 +168,7 @@ ModbusRTU::mbErrCode MBTCPServer::readInputStatus( ReadInputStatusMessage& query
}
// -------------------------------------------------------------------------
mbErrCode MBTCPServer::readInputRegisters( ReadInputMessage& query,
ReadInputRetMessage& reply )
ReadInputRetMessage& reply )
{
if( verbose )
cout << "(readInputRegisters): " << query << endl;
......@@ -296,7 +296,7 @@ ModbusRTU::mbErrCode MBTCPServer::forceSingleCoil( ModbusRTU::ForceSingleCoilMes
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply )
ModbusRTU::JournalCommandRetMessage& reply )
{
if( verbose )
cout << "(journalCommand): " << query << endl;
......@@ -333,7 +333,7 @@ ModbusRTU::mbErrCode MBTCPServer::journalCommand( ModbusRTU::JournalCommandMessa
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply )
ModbusRTU::SetDateTimeRetMessage& reply )
{
if( verbose )
cout << "(setDateTime): " << query << endl;
......@@ -345,14 +345,14 @@ ModbusRTU::mbErrCode MBTCPServer::setDateTime( ModbusRTU::SetDateTimeMessage& qu
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply )
ModbusRTU::RemoteServiceRetMessage& reply )
{
cerr << "(remoteService): " << query << endl;
return ModbusRTU::erOperationFailed;
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply )
ModbusRTU::FileTransferRetMessage& reply )
{
if( verbose )
cout << "(fileTransfer): " << query << endl;
......@@ -433,7 +433,7 @@ ModbusRTU::mbErrCode MBTCPServer::fileTransfer( ModbusRTU::FileTransferMessage&
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply )
ModbusRTU::DiagnosticRetMessage& reply )
{
if( query.subf == ModbusRTU::subEcho )
{
......@@ -472,7 +472,7 @@ ModbusRTU::mbErrCode MBTCPServer::diagnostics( ModbusRTU::DiagnosticMessage& que
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPServer::read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply )
ModbusRTU::MEIMessageRetRDI& reply )
{
if( verbose )
cout << "(read4314): " << query << endl;
......
......@@ -39,26 +39,26 @@ class MBTCPServer
/*! обработка 0x01 */
uniset::ModbusRTU::mbErrCode readCoilStatus( uniset::ModbusRTU::ReadCoilMessage& query,
uniset::ModbusRTU::ReadCoilRetMessage& reply );
uniset::ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
uniset::ModbusRTU::mbErrCode readInputStatus( uniset::ModbusRTU::ReadInputStatusMessage& query,
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
uniset::ModbusRTU::mbErrCode readOutputRegisters( uniset::ModbusRTU::ReadOutputMessage& query,
uniset::ModbusRTU::ReadOutputRetMessage& reply );
uniset::ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
uniset::ModbusRTU::mbErrCode readInputRegisters( uniset::ModbusRTU::ReadInputMessage& query,
uniset::ModbusRTU::ReadInputRetMessage& reply );
uniset::ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
uniset::ModbusRTU::mbErrCode forceSingleCoil( uniset::ModbusRTU::ForceSingleCoilMessage& query,
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
uniset::ModbusRTU::mbErrCode forceMultipleCoils( uniset::ModbusRTU::ForceCoilsMessage& query,
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
......@@ -71,25 +71,25 @@ class MBTCPServer
uniset::ModbusRTU::mbErrCode diagnostics( uniset::ModbusRTU::DiagnosticMessage& query,
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::mbErrCode read4314( uniset::ModbusRTU::MEIMessageRDI& query,
uniset::ModbusRTU::MEIMessageRetRDI& reply );
/*! обработка запросов на чтение ошибок */
uniset::ModbusRTU::mbErrCode journalCommand( uniset::ModbusRTU::JournalCommandMessage& query,
uniset::ModbusRTU::JournalCommandRetMessage& reply );
uniset::ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
uniset::ModbusRTU::mbErrCode setDateTime( uniset::ModbusRTU::SetDateTimeMessage& query,
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
uniset::ModbusRTU::mbErrCode remoteService( uniset::ModbusRTU::RemoteServiceMessage& query,
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::mbErrCode fileTransfer( uniset::ModbusRTU::FileTransferMessage& query,
uniset::ModbusRTU::FileTransferRetMessage& reply );
uniset::ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
......
......@@ -32,56 +32,56 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
class MySQLInterface:
public DBNetInterface
{
public:
// ----------------------------------------------------------------------------
class MySQLInterface:
public DBNetInterface
{
public:
MySQLInterface();
~MySQLInterface();
MySQLInterface();
~MySQLInterface();
// DBResult listFields( const std::string& table, const std::string& wild );
// DBResult listFields( const std::string& table, const std::string& wild );
virtual bool nconnect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname, unsigned int port = 0 ) override;
virtual bool close() override;
virtual bool nconnect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname, unsigned int port = 0 ) override;
virtual bool close() override;
bool query_ok( const std::string& q );
bool query_ok( const std::string& q );
// \param finalize - освободить буфер после запроса
virtual DBResult query( const std::string& q ) override;
// \param finalize - освободить буфер после запроса
virtual DBResult query( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual bool insert( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual bool insert( const std::string& q ) override;
std::string addslashes(const std::string& str);
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
virtual bool ping() const override;
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
virtual bool ping() const override;
/*! связь с БД установлена (была) */
virtual bool isConnection() const override;
/*! связь с БД установлена (была) */
virtual bool isConnection() const override;
virtual double insert_id() override;
virtual double insert_id() override;
virtual const std::string error() override;
virtual const std::string error() override;
// *******************
const char* gethostinfo() const;
protected:
// *******************
const char* gethostinfo() const;
protected:
private:
private:
void makeResult(DBResult& dbres, MYSQL_RES* r, bool finalize = true );
MYSQL* mysql;
std::string lastQ;
bool connected;
};
// ----------------------------------------------------------------------------------
void makeResult(DBResult& dbres, MYSQL_RES* r, bool finalize = true );
MYSQL* mysql;
std::string lastQ;
bool connected;
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------------
#endif
......@@ -28,49 +28,49 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
class PostgreSQLInterface:
public DBNetInterface
{
public:
// ----------------------------------------------------------------------------
class PostgreSQLInterface:
public DBNetInterface
{
public:
PostgreSQLInterface();
~PostgreSQLInterface();
PostgreSQLInterface();
~PostgreSQLInterface();
virtual bool nconnect( const std::string& host, const std::string& user,
const std::string& pswd, const std::string& dbname,
unsigned int port = 5432) override;
virtual bool close() override;
virtual bool isConnection() const override;
virtual bool ping() const override;
virtual bool nconnect( const std::string& host, const std::string& user,
const std::string& pswd, const std::string& dbname,
unsigned int port = 5432) override;
virtual bool close() override;
virtual bool isConnection() const override;
virtual bool ping() const override;
virtual DBResult query( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual DBResult query( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual bool insert( const std::string& q ) override;
bool insertAndSaveRowid( const std::string& q );
virtual double insert_id() override;
void save_inserted_id( const pqxx::result& res );
virtual bool insert( const std::string& q ) override;
bool insertAndSaveRowid( const std::string& q );
virtual double insert_id() override;
void save_inserted_id( const pqxx::result& res );
typedef std::list<std::string> Record;
typedef std::vector<Record> Data;
typedef std::list<std::string> Record;
typedef std::vector<Record> Data;
// fast insert: Use COPY..from SDTIN..
bool copy( const std::string& tblname, const std::list<std::string>& cols, const Data& data );
// fast insert: Use COPY..from SDTIN..
bool copy( const std::string& tblname, const std::list<std::string>& cols, const Data& data );
virtual const std::string error() override;
virtual const std::string error() override;
protected:
protected:
private:
private:
void makeResult(DBResult& dbres, const pqxx::result& res );
std::shared_ptr<pqxx::connection> db;
std::string lastQ;
std::string lastE;
double last_inserted_id;
};
// ----------------------------------------------------------------------------------
void makeResult(DBResult& dbres, const pqxx::result& res );
std::shared_ptr<pqxx::connection> db;
std::string lastQ;
std::string lastE;
double last_inserted_id;
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------
#endif
......
......@@ -31,114 +31,114 @@
// -------------------------------------------------------------------------
namespace uniset
{
// ----------------------------------------------------------------------------
/*! \page SQLiteIntarface Интерфейс к SQLite
Пример использования:
\code
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
DBResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( DBResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
DBResult::COL col(*it);
for( DBResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
\endcode
*/
// ----------------------------------------------------------------------------
// Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY
// При этом конечно есть риск потерять данные при выключении..
// ----------------------------------------------------------------------------
class SQLiteInterface:
public DBInterface
{
public:
SQLiteInterface();
~SQLiteInterface();
virtual bool connect( const std::string& param ) override;
bool connect( const std::string& dbfile, bool create );
virtual bool close() override;
virtual bool isConnection() const override;
virtual bool ping() const override;
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout()
{
return opTimeout;
}
inline void setOperationCheckPause( timeout_t msec )
{
opCheckPause = msec;
}
inline timeout_t getOperationCheckPause()
{
return opCheckPause;
}
virtual DBResult query( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual bool insert( const std::string& q ) override;
virtual double insert_id() override;
virtual const std::string error() override;
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
void makeResult(DBResult& dbres, sqlite3_stmt* s, bool finalize = true );
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/*! \page SQLiteIntarface Интерфейс к SQLite
Пример использования:
\code
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
DBResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( DBResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
DBResult::COL col(*it);
for( DBResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << DBResult::as_string(cit) << "(" << DBResult::as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch(Exception& ex)
{
cerr << "(test): " << ex << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
\endcode
*/
// ----------------------------------------------------------------------------
// Памятка:
// Включение режима для журнала - "вести в памяти" (чтобы поберечь CompactFlash)
// PRAGMA journal_mode = MEMORY
// При этом конечно есть риск потерять данные при выключении..
// ----------------------------------------------------------------------------
class SQLiteInterface:
public DBInterface
{
public:
SQLiteInterface();
~SQLiteInterface();
virtual bool connect( const std::string& param ) override;
bool connect( const std::string& dbfile, bool create );
virtual bool close() override;
virtual bool isConnection() const override;
virtual bool ping() const override;
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout()
{
return opTimeout;
}
inline void setOperationCheckPause( timeout_t msec )
{
opCheckPause = msec;
}
inline timeout_t getOperationCheckPause()
{
return opCheckPause;
}
virtual DBResult query( const std::string& q ) override;
virtual const std::string lastQuery() override;
virtual bool insert( const std::string& q ) override;
virtual double insert_id() override;
virtual const std::string error() override;
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
void makeResult(DBResult& dbres, sqlite3_stmt* s, bool finalize = true );
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
// ----------------------------------------------------------------------------
#endif
......
......@@ -23,66 +23,66 @@
//--------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
explicit ComediInterface( const std::string& dev );
~ComediInterface();
// -----------------------------------------------------------------------------
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
explicit ComediInterface( const std::string& dev );
~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range = 0, int aref = AREF_GROUND )
throw(uniset::Exception);
int getAnalogChannel( int subdev, int channel, int range = 0, int aref = AREF_GROUND )
throw(uniset::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range = 0, int aref = AREF_GROUND )
throw(uniset::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range = 0, int aref = AREF_GROUND )
throw(uniset::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(uniset::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(uniset::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(uniset::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(uniset::Exception);
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
void configureSubdev( int subdev, SubdevType type ) throw(uniset::Exception);
void configureSubdev( int subdev, SubdevType type ) throw(uniset::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range = 0, int aref = 0 )
throw(uniset::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range = 0, int aref = 0 )
throw(uniset::Exception);
inline const std::string devname()
{
return dname;
}
inline const std::string devname()
{
return dname;
}
protected:
protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
private:
};
// --------------------------------------------------------------------------
private:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // ComediInterface_H_
......
......@@ -20,104 +20,104 @@
// -----------------------------------------------------------------------------
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 )
{
if( el.get() == this )
void Element::addChildOut( std::shared_ptr<Element> el, size_t num )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
if( el.get() == this )
{
ostringstream msg;
msg << "(" << myid << "): ПОПТКА СДЕЛАТь ССЫЛКУ НА САМОГО СЕБЯ!!!";
throw LogicException(msg.str());
}
for( const auto& it : outs )
{
if( it.el == el )
for( const auto& it : outs )
{
if( it.el == el )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
throw LogicException(msg.str());
}
}
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "):" << el->getId() << " уже есть в списке дочерних(такое соединение уже есть)...";
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
}
}
// проверка на циклическую зависимость
// el не должен содержать в своих потомках myid
if( el->find(myid) != NULL )
{
ostringstream msg;
msg << "(" << myid << "): ПОПЫТКА СОЗДАТЬ ЦИКЛИЧЕКУЮ ЗАВИСИМОСТЬ!!!\n";
msg << " id" << el->getId() << " имеет в своих 'потомках' Element id=" << myid << endl;
throw LogicException(msg.str());
outs.emplace_front(el, num);
}
outs.emplace_front(el, num);
}
// -------------------------------------------------------------------------
void Element::delChildOut( std::shared_ptr<Element> el )
{
for( auto it = outs.begin(); it != outs.end(); ++it )
// -------------------------------------------------------------------------
void Element::delChildOut( std::shared_ptr<Element> el )
{
if( it->el == el )
for( auto it = outs.begin(); it != outs.end(); ++it )
{
outs.erase(it);
return;
if( it->el == el )
{
outs.erase(it);
return;
}
}
}
}
// -------------------------------------------------------------------------
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 )
{
for( const auto& it : outs )
// -------------------------------------------------------------------------
void Element::setChildOut()
{
if( it.el->getId() == id )
return it.el;
bool _myout = getOut();
return it.el->find(id);
for( auto && it : outs )
it.el->setIn(it.num, _myout);
}
return nullptr;
}
// -------------------------------------------------------------------------
void Element::addInput(size_t num, bool state)
{
for( auto& it : ins )
// -------------------------------------------------------------------------
std::shared_ptr<Element> Element::find(const ElementID& id )
{
if( it.num == num )
for( const auto& it : outs )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
if( it.el->getId() == id )
return it.el;
return it.el->find(id);
}
return nullptr;
}
// -------------------------------------------------------------------------
void Element::addInput(size_t num, bool state)
{
for( auto& it : ins )
{
if( it.num == num )
{
ostringstream msg;
msg << "(" << myid << "): попытка второй раз добавить input N" << num;
throw LogicException(msg.str());
}
}
ins.emplace_front(num, state);
}
// -------------------------------------------------------------------------
void Element::delInput(size_t num )
{
for( auto it = ins.begin(); it != ins.end(); ++it )
ins.emplace_front(num, state);
}
// -------------------------------------------------------------------------
void Element::delInput(size_t num )
{
if( it->num == num )
for( auto it = ins.begin(); it != ins.end(); ++it )
{
ins.erase(it);
return;
if( it->num == num )
{
ins.erase(it);
return;
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -25,197 +25,197 @@
//--------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class LogicException:
public uniset::Exception
{
public:
LogicException(): uniset::Exception("LogicException") {}
explicit LogicException( const std::string& err): uniset::Exception(err) {}
};
class Element
{
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
explicit Element( const ElementID& id ): myid(id) {};
virtual ~Element() {};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick() {}
virtual void setIn( size_t num, bool state ) = 0;
virtual bool getOut() const = 0;
inline ElementID getId() const
{
return myid;
}
virtual std::string getType() const
{
return "?type?";
}
virtual std::shared_ptr<Element> find( const ElementID& id );
virtual void addChildOut( std::shared_ptr<Element> el, size_t in_num );
virtual void delChildOut( std::shared_ptr<Element> el );
inline size_t outCount() const
{
return outs.size();
}
virtual void addInput( size_t num, bool state = false );
virtual void delInput( size_t num );
inline size_t inCount() const
{
return ins.size();
}
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << "[" << el.getType() << "]" << el.getId();
}
friend std::ostream& operator<<(std::ostream& os, std::shared_ptr<Element> el )
{
if( el )
return os << (*(el.get()));
return os;
}
protected:
Element(): myid(DefaultElementID) {}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(std::shared_ptr<Element> e, size_t n):
el(e), num(n) {}
ChildInfo(): el(0), num(0) {}
std::shared_ptr<Element> el;
size_t num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo(): num(0), state(false), type(unknown) {}
InputInfo(size_t n, bool s): num(n), state(s), type(unknown) {}
size_t num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
};
// ---------------------------------------------------------------------------
class TOR:
public Element
{
public:
TOR( ElementID id, size_t numbers = 0, bool st = false );
virtual ~TOR();
virtual void setIn( size_t num, bool state ) override;
virtual bool getOut() const override
{
return myout;
}
virtual std::string getType() const override
{
return "OR";
}
protected:
TOR(): myout(false) {}
bool myout;
private:
};
// ---------------------------------------------------------------------------
class TAND:
public TOR
{
public:
TAND(ElementID id, size_t numbers = 0, bool st = false );
virtual ~TAND();
virtual void setIn( size_t num, bool state ) override;
virtual std::string getType() const override
{
return "AND";
}
protected:
TAND() {}
private:
};
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
public Element
{
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut() const override
{
return myout;
}
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( size_t num, bool state ) override ;
virtual std::string getType() const override
{
return "NOT";
}
virtual void addInput( size_t num, bool state = false ) override {}
virtual void delInput( size_t num ) override {}
protected:
TNOT(): myout(false) {}
bool myout;
private:
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class LogicException:
public uniset::Exception
{
public:
LogicException(): uniset::Exception("LogicException") {}
explicit LogicException( const std::string& err): uniset::Exception(err) {}
};
class Element
{
public:
typedef std::string ElementID;
static const ElementID DefaultElementID;
enum InputType
{
unknown,
external,
internal
};
explicit Element( const ElementID& id ): myid(id) {};
virtual ~Element() {};
/*!< функция вызываемая мастером для элементов, которым требуется
работа во времени.
По умолчанию ничего не делает.
*/
virtual void tick() {}
virtual void setIn( size_t num, bool state ) = 0;
virtual bool getOut() const = 0;
inline ElementID getId() const
{
return myid;
}
virtual std::string getType() const
{
return "?type?";
}
virtual std::shared_ptr<Element> find( const ElementID& id );
virtual void addChildOut( std::shared_ptr<Element> el, size_t in_num );
virtual void delChildOut( std::shared_ptr<Element> el );
inline size_t outCount() const
{
return outs.size();
}
virtual void addInput( size_t num, bool state = false );
virtual void delInput( size_t num );
inline size_t inCount() const
{
return ins.size();
}
friend std::ostream& operator<<(std::ostream& os, Element& el )
{
return os << "[" << el.getType() << "]" << el.getId();
}
friend std::ostream& operator<<(std::ostream& os, std::shared_ptr<Element> el )
{
if( el )
return os << (*(el.get()));
return os;
}
protected:
Element(): myid(DefaultElementID) {}; // нельзя создать элемент без id
struct ChildInfo
{
ChildInfo(std::shared_ptr<Element> e, size_t n):
el(e), num(n) {}
ChildInfo(): el(0), num(0) {}
std::shared_ptr<Element> el;
size_t num;
};
typedef std::list<ChildInfo> OutputList;
OutputList outs;
virtual void setChildOut();
struct InputInfo
{
InputInfo(): num(0), state(false), type(unknown) {}
InputInfo(size_t n, bool s): num(n), state(s), type(unknown) {}
size_t num;
bool state;
InputType type;
};
typedef std::list<InputInfo> InputList;
InputList ins;
ElementID myid;
private:
};
// ---------------------------------------------------------------------------
class TOR:
public Element
{
public:
TOR( ElementID id, size_t numbers = 0, bool st = false );
virtual ~TOR();
virtual void setIn( size_t num, bool state ) override;
virtual bool getOut() const override
{
return myout;
}
virtual std::string getType() const override
{
return "OR";
}
protected:
TOR(): myout(false) {}
bool myout;
private:
};
// ---------------------------------------------------------------------------
class TAND:
public TOR
{
public:
TAND(ElementID id, size_t numbers = 0, bool st = false );
virtual ~TAND();
virtual void setIn( size_t num, bool state ) override;
virtual std::string getType() const override
{
return "AND";
}
protected:
TAND() {}
private:
};
// ---------------------------------------------------------------------------
// элемент с одним входом и выходом
class TNOT:
public Element
{
public:
TNOT( ElementID id, bool out_default );
virtual ~TNOT();
virtual bool getOut() const override
{
return myout;
}
/* num игнорируется, т.к. элемент с одним входом
*/
virtual void setIn( size_t num, bool state ) override ;
virtual std::string getType() const override
{
return "NOT";
}
virtual void addInput( size_t num, bool state = false ) override {}
virtual void delInput( size_t num ) override {}
protected:
TNOT(): myout(false) {}
bool myout;
private:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -110,84 +110,84 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class LProcessor
{
public:
explicit LProcessor( const std::string& name = "" );
virtual ~LProcessor();
// --------------------------------------------------------------------------
class LProcessor
{
public:
explicit LProcessor( const std::string& name = "" );
virtual ~LProcessor();
void open( const std::string& lfile );
void open( const std::string& lfile );
inline bool isOpen() const
{
return !fSchema.empty();
}
inline bool isOpen() const
{
return !fSchema.empty();
}
virtual void execute( const std::string& lfile = "" );
virtual void execute( const std::string& lfile = "" );
virtual void terminate()
{
canceled = true;
}
virtual void terminate()
{
canceled = true;
}
inline std::shared_ptr<SchemaXML> getSchema()
{
return sch;
}
inline std::shared_ptr<SchemaXML> getSchema()
{
return sch;
}
inline int getSleepTime() const
{
return sleepTime;
}
inline int getSleepTime() const
{
return sleepTime;
}
protected:
protected:
virtual void build( const string& lfile );
virtual void build( const string& lfile );
virtual void step();
virtual void step();
virtual void getInputs();
virtual void processing();
virtual void setOuts();
virtual void getInputs();
virtual void processing();
virtual void setOuts();
struct EXTInfo
{
uniset::ObjectId sid;
UniversalIO::IOType iotype;
bool state;
std::shared_ptr<Element> el;
int numInput = { -1};
};
struct EXTInfo
{
uniset::ObjectId sid;
UniversalIO::IOType iotype;
bool state;
std::shared_ptr<Element> el;
int numInput = { -1};
};
struct EXTOutInfo
{
uniset::ObjectId sid;
UniversalIO::IOType iotype;
std::shared_ptr<Element> el;
};
struct EXTOutInfo
{
uniset::ObjectId sid;
UniversalIO::IOType iotype;
std::shared_ptr<Element> el;
};
typedef std::list<EXTInfo> EXTList;
typedef std::list<EXTOutInfo> OUTList;
typedef std::list<EXTInfo> EXTList;
typedef std::list<EXTOutInfo> OUTList;
EXTList extInputs;
OUTList extOuts;
EXTList extInputs;
OUTList extOuts;
std::shared_ptr<SchemaXML> sch;
std::shared_ptr<SchemaXML> sch;
UInterface ui;
timeout_t sleepTime = { 200 };
timeout_t smReadyTimeout = { 30000 } ; /*!< время ожидания готовности SM, мсек */
UInterface ui;
timeout_t sleepTime = { 200 };
timeout_t smReadyTimeout = { 30000 } ; /*!< время ожидания готовности SM, мсек */
std::string logname = { "" };
std::string logname = { "" };
std::atomic_bool canceled = {false};
std::atomic_bool canceled = {false};
std::string fSchema = {""};
std::string fSchema = {""};
private:
};
// --------------------------------------------------------------------------
private:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -29,57 +29,57 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
/*! Реализация LogicProccessor основанная на заказе датчиков */
class PassiveLProcessor:
public UniSetObject,
protected LProcessor
{
public:
// -------------------------------------------------------------------------
/*! Реализация LogicProccessor основанная на заказе датчиков */
class PassiveLProcessor:
public UniSetObject,
protected LProcessor
{
public:
PassiveLProcessor(uniset::ObjectId objId,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "lproc" );
virtual ~PassiveLProcessor();
PassiveLProcessor(uniset::ObjectId objId,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "lproc" );
virtual ~PassiveLProcessor();
enum Timers
{
tidStep
};
enum Timers
{
tidStep
};
static void help_print( int argc, const char* const* argv );
static void help_print( int argc, const char* const* argv );
static std::shared_ptr<PassiveLProcessor> init_plproc( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "plproc" );
static std::shared_ptr<PassiveLProcessor> init_plproc( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "plproc" );
protected:
PassiveLProcessor(): shm(0), maxHeartBeat(0) {};
protected:
PassiveLProcessor(): shm(0), maxHeartBeat(0) {};
virtual void step();
virtual void getInputs();
virtual void setOuts();
virtual void step();
virtual void getInputs();
virtual void setOuts();
void sysCommand( const uniset::SystemMessage* msg ) override;
void sensorInfo( const uniset::SensorMessage* sm ) override;
void timerInfo( const uniset::TimerMessage* tm ) override;
void askSensors( const UniversalIO::UIOCommand cmd );
// void initOutput();
void sysCommand( const uniset::SystemMessage* msg ) override;
void sensorInfo( const uniset::SensorMessage* sm ) override;
void timerInfo( const uniset::TimerMessage* tm ) override;
void askSensors( const UniversalIO::UIOCommand cmd );
// void initOutput();
// действия при завершении работы
virtual void sigterm( int signo ) override;
void initIterators();
virtual bool activateObject() override;
// действия при завершении работы
virtual void sigterm( int signo ) override;
void initIterators();
virtual bool activateObject() override;
std::shared_ptr<SMInterface> shm;
std::shared_ptr<SMInterface> shm;
private:
PassiveTimer ptHeartBeat;
uniset::ObjectId sidHeartBeat = { uniset::DefaultObjectId };
int maxHeartBeat = { 10 };
IOController::IOStateList::iterator itHeartBeat;
std::mutex mutex_start;
};
// --------------------------------------------------------------------------
private:
PassiveTimer ptHeartBeat;
uniset::ObjectId sidHeartBeat = { uniset::DefaultObjectId };
int maxHeartBeat = { 10 };
IOController::IOStateList::iterator itHeartBeat;
std::mutex mutex_start;
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -21,205 +21,205 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
Schema::Schema()
{
}
Schema::~Schema()
{
}
// -------------------------------------------------------------------------
void Schema::link( Element::ElementID rootID, Element::ElementID childID, int numIn )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
auto it = emap.find(rootID);
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
if( it == emap.end() )
Schema::Schema()
{
ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str());
}
e1 = it->second;
it = emap.find(childID);
if( it == emap.end() )
Schema::~Schema()
{
ostringstream msg;
msg << "Schema: элемент id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
}
// -------------------------------------------------------------------------
void Schema::link( Element::ElementID rootID, Element::ElementID childID, int numIn )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
e2 = it->second;
auto it = emap.find(rootID);
e1->addChildOut(e2, numIn);
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str());
}
// сохраняем в список соединений
inLinks.emplace_front(e1, e2, numIn);
}
// -------------------------------------------------------------------------
void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
e1 = it->second;
auto it = emap.find(rootID);
it = emap.find(childID);
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str());
}
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: элемент id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
}
e1 = it->second;
e2 = it->second;
it = emap.find( childID );
e1->addChildOut(e2, numIn);
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: element id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
// сохраняем в список соединений
inLinks.emplace_front(e1, e2, numIn);
}
// -------------------------------------------------------------------------
void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
{
std::shared_ptr<Element> e1;
std::shared_ptr<Element> e2;
e2 = it->second;
e1->delChildOut(e2);
auto it = emap.find(rootID);
// удаляем из списка соединений
for( auto && lit = inLinks.begin(); lit != inLinks.end(); ++lit )
{
if( lit->from == e1 && lit->to == e2 )
if( it == emap.end() )
{
inLinks.erase(lit);
break;
ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str());
}
}
}
// -------------------------------------------------------------------------
void Schema::extlink( const string& name, Element::ElementID childID, int numIn )
{
auto it = emap.find(childID);
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: element id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
}
e1 = it->second;
auto el(it->second);
it = emap.find( childID );
// добавляем новое соединение
// el->addInput(numIn);
// уже должен быть
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: element id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
}
// заносим в список
extLinks.emplace_front(name, el, numIn);
}
// -------------------------------------------------------------------------
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;
e2 = it->second;
emap[el->getId()] = el;
return el;
}
// -------------------------------------------------------------------------
void Schema::remove( std::shared_ptr<Element> el )
{
for( auto && it = emap.begin(); it != emap.end(); ++it )
{
if( it->second == el )
e1->delChildOut(e2);
// удаляем из списка соединений
for( auto && lit = inLinks.begin(); lit != inLinks.end(); ++lit )
{
emap.erase(it);
break;
if( lit->from == e1 && lit->to == e2 )
{
inLinks.erase(lit);
break;
}
}
}
// помечаем внутренние связи
for( auto && lit : inLinks )
// -------------------------------------------------------------------------
void Schema::extlink( const string& name, Element::ElementID childID, int numIn )
{
if( lit.from == el )
lit.from = 0;
auto it = emap.find(childID);
if( lit.to == el )
lit.to = 0;
}
if( it == emap.end() )
{
ostringstream msg;
msg << "Schema: element id=" << childID << " NOT FOUND!";
throw LogicException(msg.str());
}
// помечаем внешние связи
for( auto && lit : extLinks )
{
if( lit.to == el )
lit.to = 0;
auto el(it->second);
// добавляем новое соединение
// el->addInput(numIn);
// уже должен быть
// заносим в список
extLinks.emplace_front(name, el, numIn);
}
// -------------------------------------------------------------------------
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;
}
// -------------------------------------------------------------------------
void Schema::setIn( Element::ElementID ID, int inNum, bool state )
{
auto it = emap.find(ID);
emap[el->getId()] = el;
return el;
}
// -------------------------------------------------------------------------
void Schema::remove( std::shared_ptr<Element> el )
{
for( auto && it = emap.begin(); it != emap.end(); ++it )
{
if( it->second == el )
{
emap.erase(it);
break;
}
}
if( it != emap.end() )
it->second->setIn(inNum, state);
}
// -------------------------------------------------------------------------
bool Schema::getOut( Element::ElementID ID )
{
auto it = emap.find(ID);
// помечаем внутренние связи
for( auto && lit : inLinks )
{
if( lit.from == el )
lit.from = 0;
if( it != emap.end() )
return it->second->getOut();
if( lit.to == el )
lit.to = 0;
}
ostringstream msg;
msg << "Schema: element id=" << ID << " NOT FOUND!";
throw LogicException(msg.str());
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::find( Element::ElementID id )
{
auto it = emap.find(id);
// помечаем внешние связи
for( auto && lit : extLinks )
{
if( lit.to == el )
lit.to = 0;
}
if( it != emap.end() )
return it->second;
}
// -------------------------------------------------------------------------
void Schema::setIn( Element::ElementID ID, int inNum, bool state )
{
auto it = emap.find(ID);
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findExtLink( const string& name )
{
// помечаем внешние связи
for( const auto& it : extLinks )
if( it != emap.end() )
it->second->setIn(inNum, state);
}
// -------------------------------------------------------------------------
bool Schema::getOut( Element::ElementID ID )
{
if( it.name == name )
return it.to;
auto it = emap.find(ID);
if( it != emap.end() )
return it->second->getOut();
ostringstream msg;
msg << "Schema: element id=" << ID << " NOT FOUND!";
throw LogicException(msg.str());
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::find( Element::ElementID id )
{
auto it = emap.find(id);
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findOut( const string& name )
{
// помечаем внешние связи
for( const auto& it : outList )
if( it != emap.end() )
return it->second;
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findExtLink( const string& name )
{
if( it.name == name )
return it.from;
// помечаем внешние связи
for( const auto& it : extLinks )
{
if( it.name == name )
return it.to;
}
return nullptr;
}
// -------------------------------------------------------------------------
std::shared_ptr<Element> Schema::findOut( const string& name )
{
// помечаем внешние связи
for( const auto& it : outList )
{
if( it.name == name )
return it.from;
}
return nullptr;
}
// -------------------------------------------------------------------------
return nullptr;
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -24,173 +24,173 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class Schema
{
public:
Schema();
virtual ~Schema();
std::shared_ptr<Element> manage( std::shared_ptr<Element> el );
void remove( std::shared_ptr<Element> el );
void link( Element::ElementID rootID, Element::ElementID childID, int numIn );
void unlink( Element::ElementID rootID, Element::ElementID childID );
void extlink( const std::string& name, Element::ElementID childID, int numIn );
void setIn( Element::ElementID ID, int inNum, bool state );
bool getOut( Element::ElementID ID );
struct INLink;
struct EXTLink;
struct EXTOut;
typedef std::unordered_map<Element::ElementID, std::shared_ptr<Element>> ElementMap;
typedef std::list<INLink> InternalList;
typedef std::list<EXTLink> ExternalList;
typedef std::list<EXTOut> OutputsList;
// map iterator
typedef ElementMap::const_iterator iterator;
inline Schema::iterator begin()
{
return emap.begin();
}
inline Schema::iterator end()
{
return emap.end();
}
inline int size()
{
return emap.size();
}
inline bool empty()
{
return emap.empty();
}
// int. list iterator
typedef InternalList::const_iterator INTiterator;
inline Schema::INTiterator intBegin()
{
return inLinks.begin();
}
inline Schema::INTiterator intEnd()
{
return inLinks.end();
}
inline int intSize()
{
return inLinks.size();
}
inline bool intEmpty()
{
return inLinks.empty();
}
// ext. list iterator
typedef ExternalList::const_iterator EXTiterator;
inline Schema::EXTiterator extBegin()
{
return extLinks.begin();
}
inline Schema::EXTiterator extEnd()
{
return extLinks.end();
}
inline int extSize()
{
return extLinks.size();
}
inline bool extEmpty()
{
return extLinks.empty();
}
// ext. out iterator
typedef OutputsList::const_iterator OUTiterator;
inline Schema::OUTiterator outBegin()
{
return outList.begin();
}
inline Schema::OUTiterator outEnd()
{
return outList.end();
}
inline int outSize()
{
return outList.size();
}
inline bool outEmpty()
{
return outList.empty();
}
// find
std::shared_ptr<Element> find(Element::ElementID id);
std::shared_ptr<Element> findExtLink(const std::string& name);
std::shared_ptr<Element> findOut(const std::string& name);
// -----------------------------------------------
// внутренее соединения
// между элементами
struct INLink
{
INLink(std::shared_ptr<Element> f, std::shared_ptr<Element> t, int ni):
numInput(ni) {}
INLink(): numInput(0) {}
std::shared_ptr<Element> from;
std::shared_ptr<Element> to;
int numInput;
};
// внешнее соединение
// что-то на вход элемента
struct EXTLink
{
EXTLink( const std::string& n, std::shared_ptr<Element> t, int ni):
name(n), to(t), numInput(ni) {}
EXTLink(): name(""), numInput(0) {}
std::string name;
std::shared_ptr<Element> to;
int numInput;
};
// наружный выход
struct EXTOut
{
EXTOut( const std::string& n, std::shared_ptr<Element>& f):
name(n), from(f) {}
EXTOut(): name("") {}
std::string name;
std::shared_ptr<Element> from;
};
protected:
ElementMap emap; // список элеметов
InternalList inLinks;
ExternalList extLinks;
OutputsList outList;
private:
};
// ---------------------------------------------------------------------------
class SchemaXML:
public Schema
{
public:
SchemaXML();
virtual ~SchemaXML();
void read( const std::string& xmlfile );
protected:
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class Schema
{
public:
Schema();
virtual ~Schema();
std::shared_ptr<Element> manage( std::shared_ptr<Element> el );
void remove( std::shared_ptr<Element> el );
void link( Element::ElementID rootID, Element::ElementID childID, int numIn );
void unlink( Element::ElementID rootID, Element::ElementID childID );
void extlink( const std::string& name, Element::ElementID childID, int numIn );
void setIn( Element::ElementID ID, int inNum, bool state );
bool getOut( Element::ElementID ID );
struct INLink;
struct EXTLink;
struct EXTOut;
typedef std::unordered_map<Element::ElementID, std::shared_ptr<Element>> ElementMap;
typedef std::list<INLink> InternalList;
typedef std::list<EXTLink> ExternalList;
typedef std::list<EXTOut> OutputsList;
// map iterator
typedef ElementMap::const_iterator iterator;
inline Schema::iterator begin()
{
return emap.begin();
}
inline Schema::iterator end()
{
return emap.end();
}
inline int size()
{
return emap.size();
}
inline bool empty()
{
return emap.empty();
}
// int. list iterator
typedef InternalList::const_iterator INTiterator;
inline Schema::INTiterator intBegin()
{
return inLinks.begin();
}
inline Schema::INTiterator intEnd()
{
return inLinks.end();
}
inline int intSize()
{
return inLinks.size();
}
inline bool intEmpty()
{
return inLinks.empty();
}
// ext. list iterator
typedef ExternalList::const_iterator EXTiterator;
inline Schema::EXTiterator extBegin()
{
return extLinks.begin();
}
inline Schema::EXTiterator extEnd()
{
return extLinks.end();
}
inline int extSize()
{
return extLinks.size();
}
inline bool extEmpty()
{
return extLinks.empty();
}
// ext. out iterator
typedef OutputsList::const_iterator OUTiterator;
inline Schema::OUTiterator outBegin()
{
return outList.begin();
}
inline Schema::OUTiterator outEnd()
{
return outList.end();
}
inline int outSize()
{
return outList.size();
}
inline bool outEmpty()
{
return outList.empty();
}
// find
std::shared_ptr<Element> find(Element::ElementID id);
std::shared_ptr<Element> findExtLink(const std::string& name);
std::shared_ptr<Element> findOut(const std::string& name);
// -----------------------------------------------
// внутренее соединения
// между элементами
struct INLink
{
INLink(std::shared_ptr<Element> f, std::shared_ptr<Element> t, int ni):
numInput(ni) {}
INLink(): numInput(0) {}
std::shared_ptr<Element> from;
std::shared_ptr<Element> to;
int numInput;
};
// внешнее соединение
// что-то на вход элемента
struct EXTLink
{
EXTLink( const std::string& n, std::shared_ptr<Element> t, int ni):
name(n), to(t), numInput(ni) {}
EXTLink(): name(""), numInput(0) {}
std::string name;
std::shared_ptr<Element> to;
int numInput;
};
// наружный выход
struct EXTOut
{
EXTOut( const std::string& n, std::shared_ptr<Element>& f):
name(n), from(f) {}
EXTOut(): name("") {}
std::string name;
std::shared_ptr<Element> from;
};
protected:
ElementMap emap; // список элеметов
InternalList inLinks;
ExternalList extLinks;
OutputsList outList;
private:
};
// ---------------------------------------------------------------------------
class SchemaXML:
public Schema
{
public:
SchemaXML();
virtual ~SchemaXML();
void read( const std::string& xmlfile );
protected:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// ---------------------------------------------------------------------------
#endif
......@@ -23,129 +23,129 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
SchemaXML::SchemaXML()
{
}
SchemaXML::~SchemaXML()
{
}
// -------------------------------------------------------------------------
void SchemaXML::read( const string& xmlfile )
{
UniXML xml;
const string sec("elements");
const string conn_sec("connections");
// try
// {
xml.open(xmlfile);
// }
// catch(...){}
xmlNode* root( xml.findNode(xml.getFirstNode(), sec) );
if( !root )
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
SchemaXML::SchemaXML()
{
ostringstream msg;
msg << "(SchemaXML::read): не нашли корневого раздела " << sec;
throw LogicException(msg.str());
}
// Считываем список элементов
UniXML::iterator it(root);
if( !it.goChildren() )
SchemaXML::~SchemaXML()
{
ostringstream msg;
msg << "(SchemaXML::read): не удалось перейти к списку элементов " << sec;
throw LogicException(msg.str());
}
for( ; it.getCurrent(); it.goNext() )
// -------------------------------------------------------------------------
void SchemaXML::read( const string& xmlfile )
{
string type(xml.getProp(it, "type"));
string ID(xml.getProp(it, "id"));
int inCount = xml.getPIntProp(it, "inCount", 1);
if( type == "OR" )
manage( make_shared<TOR>(ID, inCount) );
else if( type == "AND" )
manage( make_shared<TAND>(ID, inCount) );
else if( type == "Delay" )
{
int delayMS = xml.getIntProp(it, "delayMS");
manage( make_shared<TDelay>(ID, delayMS, inCount) );
}
else if( type == "NOT" )
{
bool defout = xml.getIntProp(it, "default_out_state");
manage( make_shared<TNOT>(ID, defout) );
}
else
UniXML xml;
const string sec("elements");
const string conn_sec("connections");
// try
// {
xml.open(xmlfile);
// }
// catch(...){}
xmlNode* root( xml.findNode(xml.getFirstNode(), sec) );
if( !root )
{
ostringstream msg;
msg << "(SchemaXML::read): НЕИЗВЕСТНЫЙ ТИП ЭЛЕМЕНТА -->" << type;
msg << "(SchemaXML::read): не нашли корневого раздела " << sec;
throw LogicException(msg.str());
}
}
// Строим связи
xmlNode* conNode( xml.findNode(xml.getFirstNode(), conn_sec) );
// Считываем список элементов
UniXML::iterator it(root);
if( !conNode )
{
ostringstream msg;
msg << "(SchemaXML::read): не нашли корневого раздела " << conn_sec;
throw LogicException(msg.str());
}
it = conNode;
if( !it.goChildren() )
{
ostringstream msg;
msg << "(SchemaXML::read): не удалось перейти к списку элементов " << sec;
throw LogicException(msg.str());
}
if( !it.goChildren() )
{
ostringstream msg;
msg << "(SchemaXML::read): не удалось перейти к списку элементов " << conn_sec;
throw LogicException(msg.str());
}
for( ; it.getCurrent(); it.goNext() )
{
string type(xml.getProp(it, "type"));
string ID(xml.getProp(it, "id"));
int inCount = xml.getPIntProp(it, "inCount", 1);
if( type == "OR" )
manage( make_shared<TOR>(ID, inCount) );
else if( type == "AND" )
manage( make_shared<TAND>(ID, inCount) );
else if( type == "Delay" )
{
int delayMS = xml.getIntProp(it, "delayMS");
manage( make_shared<TDelay>(ID, delayMS, inCount) );
}
else if( type == "NOT" )
{
bool defout = xml.getIntProp(it, "default_out_state");
manage( make_shared<TNOT>(ID, defout) );
}
else
{
ostringstream msg;
msg << "(SchemaXML::read): НЕИЗВЕСТНЫЙ ТИП ЭЛЕМЕНТА -->" << type;
throw LogicException(msg.str());
}
}
for( ; it.getCurrent(); it.goNext() )
{
string type(xml.getProp(it, "type"));
string fID(xml.getProp(it, "from"));
string tID(xml.getProp(it, "to"));
int toIn = xml.getIntProp(it, "toInput");
// Строим связи
xmlNode* conNode( xml.findNode(xml.getFirstNode(), conn_sec) );
if( type == "ext" )
if( !conNode )
{
dinfo << "SchemaXML: set EXTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
extlink(fID, tID, toIn);
ostringstream msg;
msg << "(SchemaXML::read): не нашли корневого раздела " << conn_sec;
throw LogicException(msg.str());
}
else if( type == "int" )
it = conNode;
if( !it.goChildren() )
{
dinfo << "SchemaXML: set INTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
link(fID, tID, toIn);
ostringstream msg;
msg << "(SchemaXML::read): не удалось перейти к списку элементов " << conn_sec;
throw LogicException(msg.str());
}
else if( type == "out" )
for( ; it.getCurrent(); it.goNext() )
{
auto el = find(fID);
string type(xml.getProp(it, "type"));
string fID(xml.getProp(it, "from"));
string tID(xml.getProp(it, "to"));
int toIn = xml.getIntProp(it, "toInput");
if( !el )
if( type == "ext" )
{
ostringstream msg;
msg << "(SchemaXML::read): НЕ НАЙДЕН ЭЛЕМЕНТ С ID=" << fID;
throw LogicException(msg.str());
dinfo << "SchemaXML: set EXTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
extlink(fID, tID, toIn);
}
else if( type == "int" )
{
dinfo << "SchemaXML: set INTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
link(fID, tID, toIn);
}
else if( type == "out" )
{
auto el = find(fID);
dinfo << "SchemaXML: set Out: from=" << fID << " to=" << tID << endl;
outList.emplace_front(tID, el);
if( !el )
{
ostringstream msg;
msg << "(SchemaXML::read): НЕ НАЙДЕН ЭЛЕМЕНТ С ID=" << fID;
throw LogicException(msg.str());
}
dinfo << "SchemaXML: set Out: from=" << fID << " to=" << tID << endl;
outList.emplace_front(tID, el);
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -20,56 +20,56 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TAND::TAND(ElementID id, size_t num, bool st):
TOR(id, num, 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 )
{
// cout << this << ": input " << num << " set " << state << endl;
for( auto& it : ins )
TAND::~TAND()
{
if( it.num == num )
}
// -------------------------------------------------------------------------
void TAND::setIn(size_t num, bool state )
{
// cout << this << ": input " << num << " set " << state << endl;
for( auto& it : ins )
{
if( it.state == state )
return; // вход не менялся можно вообще прервать проверку
if( it.num == num )
{
if( it.state == state )
return; // вход не менялся можно вообще прервать проверку
it.state = state;
break;
it.state = state;
break;
}
}
}
bool prev = myout;
bool brk = false; // признак досрочного завершения проверки
bool prev = myout;
bool brk = false; // признак досрочного завершения проверки
// проверяем изменился ли выход
// для тригера 'AND' проверка до первого 0
for( auto& it : ins )
{
if( !it.state )
// проверяем изменился ли выход
// для тригера 'AND' проверка до первого 0
for( auto& it : ins )
{
myout = false;
brk = true;
break;
if( !it.state )
{
myout = false;
brk = true;
break;
}
}
}
if( !brk )
myout = true;
if( !brk )
myout = true;
dinfo << this << ": myout " << myout << endl;
dinfo << this << ": myout " << myout << endl;
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -20,86 +20,86 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
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 )
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TDelay::TDelay(Element::ElementID id, timeout_t delayMS, size_t inCount):
Element(id),
myout(false),
delay(delayMS)
{
// создаём заданное количество входов
for( unsigned int i = 1; i <= inCount; i++ )
ins.emplace_front(i, false); // addInput(i,st);
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 )
{
bool prev = myout;
// сбрасываем сразу
if( !state )
TDelay::~TDelay()
{
pt.setTiming(0); // reset timer
myout = false;
dinfo << this << ": set " << myout << endl;
}
// -------------------------------------------------------------------------
void TDelay::setIn( size_t num, bool state )
{
bool prev = myout;
if( prev != myout )
Element::setChildOut();
// сбрасываем сразу
if( !state )
{
pt.setTiming(0); // reset timer
myout = false;
dinfo << this << ": set " << myout << endl;
return;
}
if( prev != myout )
Element::setChildOut();
// if( state )
return;
}
// выставляем без задержки
if( delay <= 0 )
{
pt.setTiming(0); // reset timer
myout = true;
dinfo << this << ": set " << myout << endl;
// if( state )
if( prev != myout )
Element::setChildOut();
// выставляем без задержки
if( delay <= 0 )
{
pt.setTiming(0); // reset timer
myout = true;
dinfo << this << ": set " << myout << endl;
return;
}
if( prev != myout )
Element::setChildOut();
return;
}
// засекаем, если ещё не установлен таймер
if( !myout && !prev ) // т.е. !myout && prev != myout
// засекаем, если ещё не установлен таймер
if( !myout && !prev ) // т.е. !myout && prev != myout
{
dinfo << this << ": set timer " << delay << " [msec]" << endl;
pt.setTiming(delay);
}
}
// -------------------------------------------------------------------------
void TDelay::tick()
{
dinfo << this << ": set timer " << delay << " [msec]" << endl;
pt.setTiming(delay);
if( pt.getInterval() != 0 && pt.checkTime() )
{
myout = true;
pt.setTiming(0); // reset timer
dinfo << getType() << "(" << myid << "): TIMER!!!! myout=" << myout << endl;
Element::setChildOut();
}
}
}
// -------------------------------------------------------------------------
void TDelay::tick()
{
if( pt.getInterval() != 0 && pt.checkTime() )
// -------------------------------------------------------------------------
bool TDelay::getOut() const
{
myout = true;
pt.setTiming(0); // reset timer
dinfo << getType() << "(" << myid << "): TIMER!!!! myout=" << myout << endl;
Element::setChildOut();
return myout;
}
}
// -------------------------------------------------------------------------
bool TDelay::getOut() const
{
return myout;
}
// -------------------------------------------------------------------------
void TDelay::setDelay( timeout_t timeMS )
{
delay = timeMS;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void TDelay::setDelay( timeout_t timeMS )
{
delay = timeMS;
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -22,41 +22,41 @@
// --------------------------------------------------------------------------
namespace uniset
{
// ---------------------------------------------------------------------------
// "ON" delay element
// Сбрасывается без задержки.. а срабатывает с задержкой.
class TDelay:
public Element
{
// ---------------------------------------------------------------------------
// "ON" delay element
// Сбрасывается без задержки.. а срабатывает с задержкой.
class TDelay:
public Element
{
public:
TDelay( Element::ElementID id, timeout_t delayMS = 0, size_t inCount = 0 );
virtual ~TDelay();
public:
TDelay( Element::ElementID id, timeout_t delayMS = 0, size_t inCount = 0 );
virtual ~TDelay();
virtual void tick() override;
virtual void setIn( size_t num, bool state ) override;
virtual bool getOut() const override;
virtual std::string getType() const override
{
return "Delay";
}
virtual void tick() override;
virtual void setIn( size_t num, bool state ) override;
virtual bool getOut() const override;
virtual std::string getType() const override
{
return "Delay";
}
void setDelay( timeout_t timeMS );
inline timeout_t getDelay() const
{
return delay;
}
void setDelay( timeout_t timeMS );
inline timeout_t getDelay() const
{
return delay;
}
protected:
TDelay(): myout(false), delay(0) {};
protected:
TDelay(): myout(false), delay(0) {};
bool myout;
PassiveTimer pt;
timeout_t delay;
bool myout;
PassiveTimer pt;
timeout_t delay;
private:
};
// --------------------------------------------------------------------------
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 ):
Element(id),
myout(out_default)
{
ins.emplace_front(1, !out_default);
}
// -------------------------------------------------------------------------
TNOT::~TNOT()
{
}
// -------------------------------------------------------------------------
void TNOT::setIn( size_t num, bool state )
{
bool prev = myout;
myout = !state;
// -------------------------------------------------------------------------
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 )
{
bool prev = myout;
myout = !state;
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
} // end of namespace uniset
......@@ -21,69 +21,69 @@
// -----------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TOR::TOR(ElementID id, size_t num, bool st):
Element(id),
myout(false)
{
if( num != 0 )
// -------------------------------------------------------------------------
using namespace std;
using namespace uniset::extensions;
// -------------------------------------------------------------------------
TOR::TOR(ElementID id, size_t num, bool st):
Element(id),
myout(false)
{
// создаём заданное количество входов
for( unsigned int i = 1; i <= num; i++ )
if( num != 0 )
{
ins.emplace_front(i, st); // addInput(i,st);
// создаём заданное количество входов
for( unsigned int i = 1; i <= num; i++ )
{
ins.emplace_front(i, st); // addInput(i,st);
if( st == true )
myout = true;
if( st == true )
myout = true;
}
}
}
}
TOR::~TOR()
{
}
// -------------------------------------------------------------------------
void TOR::setIn( size_t num, bool state )
{
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto& it : ins )
TOR::~TOR()
{
if( it.num == num )
}
// -------------------------------------------------------------------------
void TOR::setIn( size_t num, bool state )
{
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto& it : ins )
{
if( it.state == state )
return; // вход не менялся можно вообще прервать проверку
if( it.num == num )
{
if( it.state == state )
return; // вход не менялся можно вообще прервать проверку
it.state = state;
break;
it.state = state;
break;
}
}
}
bool prev = myout;
bool brk = false; // признак досрочного завершения проверки
bool prev = myout;
bool brk = false; // признак досрочного завершения проверки
// проверяем изменился ли выход
// для тригера 'OR' проверка до первой единицы
for( auto& it : ins )
{
if( it.state )
// проверяем изменился ли выход
// для тригера 'OR' проверка до первой единицы
for( auto& it : ins )
{
myout = true;
brk = true;
break;
if( it.state )
{
myout = true;
brk = true;
break;
}
}
}
if( !brk )
myout = false;
if( !brk )
myout = false;
dinfo << this << ": myout " << myout << endl;
dinfo << this << ": myout " << myout << endl;
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
if( prev != myout )
Element::setChildOut();
}
// -------------------------------------------------------------------------
} // end of namespace uniset
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -27,43 +27,43 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
class RTUExchange:
public MBExchange
{
public:
RTUExchange( uniset::ObjectId objId, uniset::ObjectId shmID,
const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "rs" );
virtual ~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" );
virtual ~RTUExchange();
/*! глобальная функция для инициализации объекта */
static std::shared_ptr<RTUExchange> init_rtuexchange( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "rs" );
/*! глобальная функция для инициализации объекта */
static std::shared_ptr<RTUExchange> init_rtuexchange( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "rs" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv );
protected:
std::shared_ptr<ModbusRTUMaster> mbrtu;
std::mutex mbMutex;
std::string devname;
ComPort::Speed defSpeed;
bool use485F;
bool transmitCtl;
protected:
std::shared_ptr<ModbusRTUMaster> mbrtu;
std::mutex mbMutex;
std::string devname;
ComPort::Speed defSpeed;
bool use485F;
bool transmitCtl;
virtual void step() override;
virtual bool poll() override;
virtual void step() override;
virtual bool poll() override;
virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override;
virtual bool initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it ) override;
virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override;
virtual bool initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it ) override;
private:
RTUExchange();
private:
RTUExchange();
bool rs_pre_clean;
};
// --------------------------------------------------------------------------
bool rs_pre_clean;
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // _RS_EXCHANGE_H_
......
......@@ -25,95 +25,95 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
class ModbusRTUMaster;
// -----------------------------------------------------------------------------
class RTUStorage
{
public:
explicit RTUStorage( ModbusRTU::ModbusAddr addr );
~RTUStorage();
// -----------------------------------------------------------------------------
class ModbusRTUMaster;
// -----------------------------------------------------------------------------
class RTUStorage
{
public:
explicit RTUStorage( ModbusRTU::ModbusAddr addr );
~RTUStorage();
void poll( const std::shared_ptr<ModbusRTUMaster>& mb )
throw(ModbusRTU::mbException);
void poll( const std::shared_ptr<ModbusRTUMaster>& mb )
throw(ModbusRTU::mbException);
inline ModbusRTU::ModbusAddr getAddress()
{
return addr;
}
inline bool ping()
{
return pingOK;
}
inline ModbusRTU::ModbusAddr getAddress()
{
return addr;
}
inline bool ping()
{
return pingOK;
}
inline void setPollADC( bool set )
{
pollADC = set;
}
inline void setPollDI( bool set )
{
pollDI = set;
}
inline void setPollDIO( bool set )
{
pollDIO = set;
}
inline void setPollUNIO( bool set )
{
pollUNIO = set;
}
inline void setPollADC( bool set )
{
pollADC = set;
}
inline void setPollDI( bool set )
{
pollDI = set;
}
inline void setPollDIO( bool set )
{
pollDIO = set;
}
inline void setPollUNIO( bool set )
{
pollUNIO = set;
}
enum RTUJack
{
nUnknown,
nJ1, // UNIO48 (FPGA0)
nJ2, // UNIO48 (FPGA1)
nJ5, // DIO 16
nX1, // АЦП (8)
nX2, // АЦП (8)
nX4, // DI (8)
nX5 // DI (8)
};
enum RTUJack
{
nUnknown,
nJ1, // UNIO48 (FPGA0)
nJ2, // UNIO48 (FPGA1)
nJ5, // DIO 16
nX1, // АЦП (8)
nX2, // АЦП (8)
nX4, // DI (8)
nX5 // DI (8)
};
static RTUJack s2j( const std::string& jack );
static std::string j2s( RTUJack j );
static RTUJack s2j( const std::string& jack );
static std::string j2s( RTUJack j );
long getInt( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
float getFloat( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
bool getState( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
long getInt( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
float getFloat( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
bool getState( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
static ModbusRTU::ModbusData getRegister( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
static ModbusRTU::ModbusData getRegister( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
static ModbusRTU::SlaveFunctionCode getFunction( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
static ModbusRTU::SlaveFunctionCode getFunction( RTUJack jack, unsigned short channel, UniversalIO::IOType t );
// ДОДЕЛАТЬ: setState, setValue
void print();
// ДОДЕЛАТЬ: setState, setValue
void print();
friend std::ostream& operator<<(std::ostream& os, RTUStorage& m );
friend std::ostream& operator<<(std::ostream& os, RTUStorage* m );
friend std::ostream& operator<<(std::ostream& os, RTUStorage& m );
friend std::ostream& operator<<(std::ostream& os, RTUStorage* m );
protected:
ModbusRTU::ModbusAddr addr;
bool pingOK;
protected:
ModbusRTU::ModbusAddr addr;
bool pingOK;
bool pollADC;
bool pollDI;
bool pollDIO;
bool pollUNIO;
bool pollADC;
bool pollDI;
bool pollDIO;
bool pollUNIO;
float adc[8]; // АЦП
bool di[16]; // Порт 16DI
bool dio_do[16]; // Порт 16DIO DO
bool dio_di[16]; // Порт 16DIO DI
float dio_ai[16]; // Порт 16DIO AI
float dio_ao[16]; // Порт 16DIO AO
bool unio_do[48]; // Порт UNIO48 DO
bool unio_di[48]; // Порт UNIO48 DI
float unio_ai[24]; // Порт UNIO48 AI
float unio_ao[24]; // Порт UNIO48 AO
};
// --------------------------------------------------------------------------
float adc[8]; // АЦП
bool di[16]; // Порт 16DI
bool dio_do[16]; // Порт 16DIO DO
bool dio_di[16]; // Порт 16DIO DI
float dio_ai[16]; // Порт 16DIO AI
float dio_ao[16]; // Порт 16DIO AO
bool unio_do[48]; // Порт UNIO48 DO
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_
......
......@@ -197,7 +197,7 @@ ModbusRTU::mbErrCode MBTCPTestServer::readInputStatus( ReadInputStatusMessage& q
}
// -------------------------------------------------------------------------
mbErrCode MBTCPTestServer::readInputRegisters( ReadInputMessage& query,
ReadInputRetMessage& reply )
ReadInputRetMessage& reply )
{
if( disabled )
return ModbusRTU::erTimeOut;
......@@ -539,7 +539,7 @@ ModbusRTU::mbErrCode MBTCPTestServer::diagnostics( ModbusRTU::DiagnosticMessage&
}
// -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBTCPTestServer::read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply )
ModbusRTU::MEIMessageRetRDI& reply )
{
if( disabled )
return ModbusRTU::erTimeOut;
......
......@@ -73,26 +73,26 @@ class MBTCPTestServer
/*! обработка 0x01 */
uniset::ModbusRTU::mbErrCode readCoilStatus( uniset::ModbusRTU::ReadCoilMessage& query,
uniset::ModbusRTU::ReadCoilRetMessage& reply );
uniset::ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
uniset::ModbusRTU::mbErrCode readInputStatus( uniset::ModbusRTU::ReadInputStatusMessage& query,
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
uniset::ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
uniset::ModbusRTU::mbErrCode readOutputRegisters( uniset::ModbusRTU::ReadOutputMessage& query,
uniset::ModbusRTU::ReadOutputRetMessage& reply );
uniset::ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
uniset::ModbusRTU::mbErrCode readInputRegisters( uniset::ModbusRTU::ReadInputMessage& query,
uniset::ModbusRTU::ReadInputRetMessage& reply );
uniset::ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
uniset::ModbusRTU::mbErrCode forceSingleCoil( uniset::ModbusRTU::ForceSingleCoilMessage& query,
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
uniset::ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
uniset::ModbusRTU::mbErrCode forceMultipleCoils( uniset::ModbusRTU::ForceCoilsMessage& query,
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
uniset::ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
......@@ -105,25 +105,25 @@ class MBTCPTestServer
uniset::ModbusRTU::mbErrCode diagnostics( uniset::ModbusRTU::DiagnosticMessage& query,
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::DiagnosticRetMessage& reply );
uniset::ModbusRTU::mbErrCode read4314( uniset::ModbusRTU::MEIMessageRDI& query,
uniset::ModbusRTU::MEIMessageRetRDI& reply );
/*! обработка запросов на чтение ошибок */
uniset::ModbusRTU::mbErrCode journalCommand( uniset::ModbusRTU::JournalCommandMessage& query,
uniset::ModbusRTU::JournalCommandRetMessage& reply );
uniset::ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
uniset::ModbusRTU::mbErrCode setDateTime( uniset::ModbusRTU::SetDateTimeMessage& query,
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
uniset::ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
uniset::ModbusRTU::mbErrCode remoteService( uniset::ModbusRTU::RemoteServiceMessage& query,
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::RemoteServiceRetMessage& reply );
uniset::ModbusRTU::mbErrCode fileTransfer( uniset::ModbusRTU::FileTransferMessage& query,
uniset::ModbusRTU::FileTransferRetMessage& reply );
uniset::ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -202,8 +202,8 @@ void SMDBServer::help_print( int argc, const char* const* argv )
}
// -----------------------------------------------------------------------------
SMDBServer* SMDBServer::init_smdbserver( int argc, const char* const* argv,
uniset::ObjectId icID, SharedMemory* ic,
const std::string& prefix )
uniset::ObjectId icID, SharedMemory* ic,
const std::string& prefix )
{
string name = conf->getArgParam("--" + prefix + "-name", "DBServer");
......
......@@ -27,126 +27,126 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*!
\page pageUniExchange Обмен между узлами на основе TCP.
\par Обмен построен на основе функций IOControl-ера получения списка дискретных
и аналоговых датчиков. Работает через удалённые CORBA-вызовы.
\par Процесс считывает из конфигурационного файла список узлов которые необходимо
опрашивать (точнее список IOControl-еров), запускается поток обмена, в котором
эти узлы ПОСЛЕДОВАТЕЛЬНО опрашиваются..
\par Пример записи в конфигурационном файле для опроса пяти узлов...
\code
<UniExchange name="UniExchange">
<item name="UniExchange2" node="Node2"/>
<item id="3001" node_id="Node2"/>
<item name="UniExchange3" node="Node3"/>
<item name="UniExchange4" node="Node4"/>
<item name="UniExchange5" node="Node5"/>
</UniExchange>
\endcode
Запись можно делать по "id" или по "name"
*/
// -----------------------------------------------------------------------------
class UniExchange:
public IOController
{
public:
UniExchange( uniset::ObjectId id, uniset::ObjectId shmID,
const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "unet" );
virtual ~UniExchange();
void execute();
static std::shared_ptr<UniExchange> init_exchange( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "unet" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char** argv );
virtual IOController_i::ShortMapSeq* getSensors() override;
protected:
virtual void sysCommand( const uniset::SystemMessage* sm ) override;
virtual void askSensors( UniversalIO::UIOCommand cmd );
virtual void sigterm( int signo ) override;
xmlNode* cnode = { 0 };
std::string s_field = { "" };
std::string s_fvalue = { "" };
std::shared_ptr<SMInterface> shm;
struct SInfo
{
// т.к. содержится rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
SInfo( const SInfo& r ) = delete;
SInfo& operator=(const SInfo& r) = delete;
SInfo( SInfo&& r ) = default;
SInfo& operator=(SInfo&& r) = default;
SInfo():
val(0),
id(uniset::DefaultObjectId),
type(UniversalIO::UnknownIOType)
{}
IOController::IOStateList::iterator ioit;
long val;
long id;
UniversalIO::IOType type;
uniset::uniset_rwmutex val_lock;
};
typedef std::vector<SInfo> SList;
struct NetNodeInfo
{
// т.к. содержится SList в котором rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
NetNodeInfo( const NetNodeInfo& r ) = delete;
NetNodeInfo& operator=(const NetNodeInfo& r) = delete;
NetNodeInfo( NetNodeInfo&& r ) = default;
NetNodeInfo& operator=(NetNodeInfo&& r) = default;
NetNodeInfo();
CORBA::Object_var oref;
IOController_i_var shm;
uniset::ObjectId id;
uniset::ObjectId node;
uniset::ObjectId sidConnection; /*!< датчик связи */
IOController::IOStateList::iterator conn_it;
SList smap;
void update(IOController_i::ShortMapSeq_var& map, const std::shared_ptr<SMInterface>& shm );
};
typedef std::list<NetNodeInfo> NetNodeList;
NetNodeList nlst;
void readConfiguration();
bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec );
bool initItem( UniXML::iterator& it );
void updateLocalData();
void initIterators();
timeout_t polltime = { 200 };
PassiveTimer ptUpdate;
bool init_ok = { false };
SList mymap;
size_t maxIndex = { 0 };
timeout_t smReadyTimeout = { 15000 }; // msec
private:
};
// --------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/*!
\page pageUniExchange Обмен между узлами на основе TCP.
\par Обмен построен на основе функций IOControl-ера получения списка дискретных
и аналоговых датчиков. Работает через удалённые CORBA-вызовы.
\par Процесс считывает из конфигурационного файла список узлов которые необходимо
опрашивать (точнее список IOControl-еров), запускается поток обмена, в котором
эти узлы ПОСЛЕДОВАТЕЛЬНО опрашиваются..
\par Пример записи в конфигурационном файле для опроса пяти узлов...
\code
<UniExchange name="UniExchange">
<item name="UniExchange2" node="Node2"/>
<item id="3001" node_id="Node2"/>
<item name="UniExchange3" node="Node3"/>
<item name="UniExchange4" node="Node4"/>
<item name="UniExchange5" node="Node5"/>
</UniExchange>
\endcode
Запись можно делать по "id" или по "name"
*/
// -----------------------------------------------------------------------------
class UniExchange:
public IOController
{
public:
UniExchange( uniset::ObjectId id, uniset::ObjectId shmID,
const std::shared_ptr<SharedMemory>& ic = nullptr, const std::string& prefix = "unet" );
virtual ~UniExchange();
void execute();
static std::shared_ptr<UniExchange> init_exchange( int argc, const char* const* argv,
uniset::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "unet" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char** argv );
virtual IOController_i::ShortMapSeq* getSensors() override;
protected:
virtual void sysCommand( const uniset::SystemMessage* sm ) override;
virtual void askSensors( UniversalIO::UIOCommand cmd );
virtual void sigterm( int signo ) override;
xmlNode* cnode = { 0 };
std::string s_field = { "" };
std::string s_fvalue = { "" };
std::shared_ptr<SMInterface> shm;
struct SInfo
{
// т.к. содержится rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
SInfo( const SInfo& r ) = delete;
SInfo& operator=(const SInfo& r) = delete;
SInfo( SInfo&& r ) = default;
SInfo& operator=(SInfo&& r) = default;
SInfo():
val(0),
id(uniset::DefaultObjectId),
type(UniversalIO::UnknownIOType)
{}
IOController::IOStateList::iterator ioit;
long val;
long id;
UniversalIO::IOType type;
uniset::uniset_rwmutex val_lock;
};
typedef std::vector<SInfo> SList;
struct NetNodeInfo
{
// т.к. содержится SList в котором rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
NetNodeInfo( const NetNodeInfo& r ) = delete;
NetNodeInfo& operator=(const NetNodeInfo& r) = delete;
NetNodeInfo( NetNodeInfo&& r ) = default;
NetNodeInfo& operator=(NetNodeInfo&& r) = default;
NetNodeInfo();
CORBA::Object_var oref;
IOController_i_var shm;
uniset::ObjectId id;
uniset::ObjectId node;
uniset::ObjectId sidConnection; /*!< датчик связи */
IOController::IOStateList::iterator conn_it;
SList smap;
void update(IOController_i::ShortMapSeq_var& map, const std::shared_ptr<SMInterface>& shm );
};
typedef std::list<NetNodeInfo> NetNodeList;
NetNodeList nlst;
void readConfiguration();
bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec );
bool initItem( UniXML::iterator& it );
void updateLocalData();
void initIterators();
timeout_t polltime = { 200 };
PassiveTimer ptUpdate;
bool init_ok = { false };
SList mymap;
size_t maxIndex = { 0 };
timeout_t smReadyTimeout = { 15000 }; // msec
private:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // UniExchange_H_
......@@ -26,103 +26,103 @@
//--------------------------------------------------------------------------
namespace uniset
{
//--------------------------------------------------------------------------
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,
double iir_coeff_new = 0.5 );
~DigitalFilter ();
// T <=0 - отключить вторую ступень фильтра
void setSettings( unsigned int bufsize, double T, double lsq,
int iir_thr, double iir_coeff_prev, double iir_coeff_new );
// Усреднение с учётом СКОС
// На вход подается новое значение
// возвращается фильтрованное с учётом
// предыдущих значений...
int filter1( int newValue );
// RC-фильтр
int filterRC( int newVal );
// медианный фильтр
int median( int newval );
// адаптивный фильтр по схеме наименьших квадратов
int leastsqr( int newval );
// рекурсивный фильтр
int filterIIR( int newval );
// получить текущее фильтрованное значение
int current1();
int currentRC();
int currentMedian();
int currentLS();
int currentIIR();
// просто добавить очередное значение
void add( int newValue );
void init( int val );
// void init( list<int>& data );
inline int size()
{
return buf.size();
}
inline double middle()
{
return M;
}
inline double sko()
{
return S;
}
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter& d);
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter* d);
private:
// Первая ступень фильтра
double firstLevel();
// Вторая ступень фильтра, математическая реализация RC фильтра
double secondLevel( double val );
double Ti; // Постоянная времени для апериодического звена в милисекундах
double val; // Текущее значение второй ступени фильтра
double M; // Среднее арифметическое
double S; // Среднеквадратичное отклонение
PassiveTimer tmr;
typedef std::deque<int> FIFOBuffer;
FIFOBuffer buf;
unsigned int maxsize;
typedef std::vector<int> MedianVector;
MedianVector mvec;
bool mvec_sorted; // флаг, что mvec остортирован (заполнен)
typedef std::vector<double> Coeff;
Coeff w; // Вектор коэффициентов для filterIIR
double lsparam; // Параметр для filterIIR
double ls; // Последнее значение, возвращённое filterIIR
int thr; // Порог для изменений, обрабатываемых рекурсивным фильтром
int prev; // Последнее значение, возвращённое рекурсивным фильтром
// Коэффициенты для рекурсивного фильтра
double coeff_prev;
double coeff_new;
};
// -------------------------------------------------------------------------
//--------------------------------------------------------------------------
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,
double iir_coeff_new = 0.5 );
~DigitalFilter ();
// T <=0 - отключить вторую ступень фильтра
void setSettings( unsigned int bufsize, double T, double lsq,
int iir_thr, double iir_coeff_prev, double iir_coeff_new );
// Усреднение с учётом СКОС
// На вход подается новое значение
// возвращается фильтрованное с учётом
// предыдущих значений...
int filter1( int newValue );
// RC-фильтр
int filterRC( int newVal );
// медианный фильтр
int median( int newval );
// адаптивный фильтр по схеме наименьших квадратов
int leastsqr( int newval );
// рекурсивный фильтр
int filterIIR( int newval );
// получить текущее фильтрованное значение
int current1();
int currentRC();
int currentMedian();
int currentLS();
int currentIIR();
// просто добавить очередное значение
void add( int newValue );
void init( int val );
// void init( list<int>& data );
inline int size()
{
return buf.size();
}
inline double middle()
{
return M;
}
inline double sko()
{
return S;
}
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter& d);
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter* d);
private:
// Первая ступень фильтра
double firstLevel();
// Вторая ступень фильтра, математическая реализация RC фильтра
double secondLevel( double val );
double Ti; // Постоянная времени для апериодического звена в милисекундах
double val; // Текущее значение второй ступени фильтра
double M; // Среднее арифметическое
double S; // Среднеквадратичное отклонение
PassiveTimer tmr;
typedef std::deque<int> FIFOBuffer;
FIFOBuffer buf;
unsigned int maxsize;
typedef std::vector<int> MedianVector;
MedianVector mvec;
bool mvec_sorted; // флаг, что mvec остортирован (заполнен)
typedef std::vector<double> Coeff;
Coeff w; // Вектор коэффициентов для filterIIR
double lsparam; // Параметр для filterIIR
double ls; // Последнее значение, возвращённое filterIIR
int thr; // Порог для изменений, обрабатываемых рекурсивным фильтром
int prev; // Последнее значение, возвращённое рекурсивным фильтром
// Коэффициенты для рекурсивного фильтра
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 );
/*! замена служебных символов в строке
* '\\' -> '\n'
*/
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
// -------------------------------------------------------------------------
......
......@@ -22,62 +22,62 @@
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
/*! ПИД
Формулы выведены на основе разностных уравнений
см. http://atm.h1.ru/root/theory/theory33.html
// -----------------------------------------------------------------------------
/*! ПИД
Формулы выведены на основе разностных уравнений
см. http://atm.h1.ru/root/theory/theory33.html
Он даёт неплохой результат и опимальнее по расчётам
(содержит только умножение, не переполняется
т.к. учитывает только два последних шага)
*/
class PID
{
public:
PID();
~PID();
Он даёт неплохой результат и опимальнее по расчётам
(содержит только умножение, не переполняется
т.к. учитывает только два последних шага)
*/
class PID
{
public:
PID();
~PID();
/*! Выполнение очередного шага расчётов
\param X - входное значение
\param Z - заданное значение
\param Ts - интервал расчёта данных, [сек] (интервал между шагами расчёта).
Ts - должно быть больше нуля
*/
void step( const double& X, const double& Z, const double& Ts );
/*! Выполнение очередного шага расчётов
\param X - входное значение
\param Z - заданное значение
\param Ts - интервал расчёта данных, [сек] (интервал между шагами расчёта).
Ts - должно быть больше нуля
*/
void step( const double& X, const double& Z, const double& Ts );
/*! рестарт регулятора... */
void reset();
/*! рестарт регулятора... */
void reset();
/*! пересчёт констант */
void recalc();
/*! пересчёт констант */
void recalc();
double Y; /*!< расчётное выходное значение */
double Kc; /*!< пропорциональный коэффициент */
double Ti; /*!< постоянная времени интеграла, [сек] */
double Td; /*!< постоянная времени дифференциала, [сек] */
double Y; /*!< расчётное выходное значение */
double Kc; /*!< пропорциональный коэффициент */
double Ti; /*!< постоянная времени интеграла, [сек] */
double Td; /*!< постоянная времени дифференциала, [сек] */
double vlim; /*!< максимальное(минимальное) разрешённое значение (для любого растущего во времени коэффициента)
double vlim; /*!< максимальное(минимальное) разрешённое значение (для любого растущего во времени коэффициента)
защита от переполнения
*/
double d0;
double d1;
double d2;
double sub1;
double sub2;
double sub;
double prevTs;
double d0;
double d1;
double d2;
double sub1;
double sub2;
double sub;
double prevTs;
friend std::ostream& operator<<(std::ostream& os, PID& p );
friend std::ostream& operator<<(std::ostream& os, PID& p );
friend std::ostream& operator<<(std::ostream& os, PID* p )
{
return os << (*p);
}
friend std::ostream& operator<<(std::ostream& os, PID* p )
{
return os << (*p);
}
protected:
private:
};
// --------------------------------------------------------------------------
protected:
private:
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
#endif // PID_H_
......
......@@ -26,74 +26,74 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
class SMInterface
{
public:
// --------------------------------------------------------------------------
class SMInterface
{
public:
SMInterface( uniset::ObjectId _shmID, const std::shared_ptr<UInterface>& ui,
uniset::ObjectId myid, const std::shared_ptr<IONotifyController> ic = nullptr );
~SMInterface();
SMInterface( uniset::ObjectId _shmID, const std::shared_ptr<UInterface>& ui,
uniset::ObjectId myid, const std::shared_ptr<IONotifyController> ic = nullptr );
~SMInterface();
void setValue ( uniset::ObjectId, long value );
void setUndefinedState( const IOController_i::SensorInfo& si, bool undefined, uniset::ObjectId supplier );
void setValue ( uniset::ObjectId, long value );
void setUndefinedState( const IOController_i::SensorInfo& si, bool undefined, uniset::ObjectId supplier );
long getValue ( uniset::ObjectId id );
long getValue ( uniset::ObjectId id );
void askSensor( uniset::ObjectId id, UniversalIO::UIOCommand cmd,
uniset::ObjectId backid = uniset::DefaultObjectId );
void askSensor( uniset::ObjectId id, UniversalIO::UIOCommand cmd,
uniset::ObjectId backid = uniset::DefaultObjectId );
IOController_i::SensorInfoSeq* getSensorsMap();
IONotifyController_i::ThresholdsListSeq* getThresholdsList();
IOController_i::SensorInfoSeq* getSensorsMap();
IONotifyController_i::ThresholdsListSeq* getThresholdsList();
void localSetValue( IOController::IOStateList::iterator& it,
uniset::ObjectId sid,
CORBA::Long newvalue, uniset::ObjectId sup_id );
void localSetValue( IOController::IOStateList::iterator& it,
uniset::ObjectId sid,
CORBA::Long newvalue, uniset::ObjectId sup_id );
long localGetValue( IOController::IOStateList::iterator& it,
uniset::ObjectId sid );
long localGetValue( IOController::IOStateList::iterator& it,
uniset::ObjectId sid );
/*! функция выставления признака неопределённого состояния для аналоговых датчиков
// для дискретных датчиков необходимости для подобной функции нет.
// см. логику выставления в функции localSaveState
*/
void localSetUndefinedState( IOController::IOStateList::iterator& it,
bool undefined, uniset::ObjectId sid );
/*! функция выставления признака неопределённого состояния для аналоговых датчиков
// для дискретных датчиков необходимости для подобной функции нет.
// см. логику выставления в функции localSaveState
*/
void localSetUndefinedState( IOController::IOStateList::iterator& it,
bool undefined, uniset::ObjectId sid );
// специальные функции
IOController::IOStateList::iterator ioEnd();
void initIterator( IOController::IOStateList::iterator& it );
// специальные функции
IOController::IOStateList::iterator ioEnd();
void initIterator( IOController::IOStateList::iterator& it );
bool exist();
bool waitSMready( int msec, int pause = 5000 );
bool waitSMworking( uniset::ObjectId, int msec, int pause = 3000 );
bool exist();
bool waitSMready( int msec, int pause = 5000 );
bool waitSMworking( uniset::ObjectId, int msec, int pause = 3000 );
inline bool isLocalwork()
{
return (ic == NULL);
}
inline uniset::ObjectId ID()
{
return myid;
}
inline const std::shared_ptr<IONotifyController> SM()
{
return ic;
}
inline uniset::ObjectId getSMID()
{
return shmID;
}
inline bool isLocalwork()
{
return (ic == NULL);
}
inline uniset::ObjectId ID()
{
return myid;
}
inline const std::shared_ptr<IONotifyController> SM()
{
return ic;
}
inline uniset::ObjectId getSMID()
{
return shmID;
}
protected:
const std::shared_ptr<IONotifyController> ic;
const std::shared_ptr<UInterface> ui;
CORBA::Object_var oref;
uniset::ObjectId shmID;
uniset::ObjectId myid;
uniset::uniset_rwmutex shmMutex;
};
// --------------------------------------------------------------------------
protected:
const std::shared_ptr<IONotifyController> ic;
const std::shared_ptr<UInterface> ui;
CORBA::Object_var oref;
uniset::ObjectId shmID;
uniset::ObjectId myid;
uniset::uniset_rwmutex shmMutex;
};
// --------------------------------------------------------------------------
} // end of namespace uniset
//--------------------------------------------------------------------------
#endif
......@@ -21,29 +21,29 @@
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
/*! Базовый класс для одиночных процессов.
Обеспечивает корректное завершение процесса,
даже по сигналам...
*/
class SingleProcess
{
public:
SingleProcess();
virtual ~SingleProcess();
// --------------------------------------------------------------------------
/*! Базовый класс для одиночных процессов.
Обеспечивает корректное завершение процесса,
даже по сигналам...
*/
class SingleProcess
{
public:
SingleProcess();
virtual ~SingleProcess();
protected:
virtual void term( int signo ) {}
protected:
virtual void term( int signo ) {}
static void set_signals( bool ask );
static void set_signals( bool ask );
private:
private:
static void terminated( int signo );
static void finishterm( int signo );
static void terminated( int signo );
static void finishterm( int signo );
};
// --------------------------------------------------------------------------
};
// --------------------------------------------------------------------------
} // end of namespace uniset
// --------------------------------------------------------------------------
#endif // SingleProcess_H_
......
......@@ -24,136 +24,136 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// -------------------------------------------------------------------------
namespace extensions
{
static std::shared_ptr<DebugStream> _dlog;
std::shared_ptr<DebugStream> dlog()
{
if( _dlog )
return _dlog;
_dlog = make_shared<DebugStream>();
_dlog->setLogName("dlog");
auto conf = uniset_conf();
if( conf )
conf->initLogStream(_dlog, "dlog");
return _dlog;
}
// -------------------------------------------------------------------------
static uniset::ObjectId shmID = DefaultObjectId;
uniset::ObjectId getSharedMemoryID()
{
if( shmID != DefaultObjectId )
return shmID;
auto conf = uniset_conf();
string sname = conf->getArgParam("--smemory-id", "SharedMemory1");
shmID = conf->getControllerID(sname);
if( shmID == uniset::DefaultObjectId )
{
ostringstream err;
err << ": Unknown ID for '" << sname << "'" << endl;
dcrit << err.str() << endl;
throw SystemError(err.str());
}
// cout << "(uniset): shm=" << name << " id=" << shmID << endl;
return shmID;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
if( s.empty() )
return;
string::size_type pos = s.find("\\n");
while( pos != string::npos )
{
s.replace(pos, 2, "\n");
pos = s.find("\\n");
}
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
xmlNode* getCalibrationsSection()
{
if( xmlCalibrationsNode )
return xmlCalibrationsNode;
xmlCalibrationsNode = uniset_conf()->getNode("Calibrations");
return xmlCalibrationsNode;
}
// -------------------------------------------------------------------------
xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
{
if( !node )
return 0;
UniXML::iterator it(node);
if( !it.goChildren() )
return 0;
for( ; it; it.goNext() )
// -------------------------------------------------------------------------
namespace extensions
{
if( snode == it.getProp(field) )
return it;
}
return 0;
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
xmlNode* root = getCalibrationsSection();
if( !root )
{
ostringstream err;
err << "(buildCalibrationDiagram): НЕ НАЙДЕН корневой узел для калибровочных диаграмм";
dcrit << err.str() << endl;
throw SystemError( err.str());
}
xmlNode* dnode = findNode( root, dname, "name" );
if( !dnode )
{
ostringstream err;
err << "(buildCalibrationDiagram): НЕ НАЙДЕНА калибровочная диаграмма '" << dname << "'";
dcrit << err.str() << endl;
throw SystemError( err.str());
}
return new Calibration(dnode);
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
while(1)
{
int istatus;
pid_t pid = waitpid( -1, &istatus, WNOHANG );
if( pid == -1 && errno == EINTR ) continue;
if( pid <= 0 ) break;
}
}
// --------------------------------------------------------------------------
} // end of namespace extensions
static std::shared_ptr<DebugStream> _dlog;
std::shared_ptr<DebugStream> dlog()
{
if( _dlog )
return _dlog;
_dlog = make_shared<DebugStream>();
_dlog->setLogName("dlog");
auto conf = uniset_conf();
if( conf )
conf->initLogStream(_dlog, "dlog");
return _dlog;
}
// -------------------------------------------------------------------------
static uniset::ObjectId shmID = DefaultObjectId;
uniset::ObjectId getSharedMemoryID()
{
if( shmID != DefaultObjectId )
return shmID;
auto conf = uniset_conf();
string sname = conf->getArgParam("--smemory-id", "SharedMemory1");
shmID = conf->getControllerID(sname);
if( shmID == uniset::DefaultObjectId )
{
ostringstream err;
err << ": Unknown ID for '" << sname << "'" << endl;
dcrit << err.str() << endl;
throw SystemError(err.str());
}
// cout << "(uniset): shm=" << name << " id=" << shmID << endl;
return shmID;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
if( s.empty() )
return;
string::size_type pos = s.find("\\n");
while( pos != string::npos )
{
s.replace(pos, 2, "\n");
pos = s.find("\\n");
}
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
xmlNode* getCalibrationsSection()
{
if( xmlCalibrationsNode )
return xmlCalibrationsNode;
xmlCalibrationsNode = uniset_conf()->getNode("Calibrations");
return xmlCalibrationsNode;
}
// -------------------------------------------------------------------------
xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
{
if( !node )
return 0;
UniXML::iterator it(node);
if( !it.goChildren() )
return 0;
for( ; it; it.goNext() )
{
if( snode == it.getProp(field) )
return it;
}
return 0;
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
xmlNode* root = getCalibrationsSection();
if( !root )
{
ostringstream err;
err << "(buildCalibrationDiagram): НЕ НАЙДЕН корневой узел для калибровочных диаграмм";
dcrit << err.str() << endl;
throw SystemError( err.str());
}
xmlNode* dnode = findNode( root, dname, "name" );
if( !dnode )
{
ostringstream err;
err << "(buildCalibrationDiagram): НЕ НАЙДЕНА калибровочная диаграмма '" << dname << "'";
dcrit << err.str() << endl;
throw SystemError( err.str());
}
return new Calibration(dnode);
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
while(1)
{
int istatus;
pid_t pid = waitpid( -1, &istatus, WNOHANG );
if( pid == -1 && errno == EINTR ) continue;
if( pid <= 0 ) break;
}
}
// --------------------------------------------------------------------------
} // end of namespace extensions
} // end of namespace uniset
// -------------------------------------------------------------------------
......@@ -21,81 +21,81 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// -----------------------------------------------------------------------------
PID::PID():
Y(0), Kc(0),
Ti(0), Td(0),
vlim(2.0),
d0(0),
d1(0),
d2(0),
prevTs(0)
{
reset();
}
// -----------------------------------------------------------------------------
PID::PID():
Y(0), Kc(0),
Ti(0), Td(0),
vlim(2.0),
d0(0),
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 )
{
// Чтобы не пересчитывать коэффициенты на каждом шаге
// сделан пересчёт только по изменению
// d0 = 1+Ts/Ti+Td/Ts;
// d1 = -1-2*Td/Ts;
// d2 = Td/Ts;
// Чтобы не пересчитывать коэффициенты на каждом шаге
// сделан пересчёт только по изменению
// d0 = 1+Ts/Ti+Td/Ts;
// d1 = -1-2*Td/Ts;
// d2 = Td/Ts;
// в случае изменения Td и Ts за вызов recalc отвечает "Родитель"(PIDControl)
if( prevTs != Ts )
{
prevTs = Ts;
recalc();
}
// в случае изменения Td и Ts за вызов recalc отвечает "Родитель"(PIDControl)
if( prevTs != Ts )
{
prevTs = Ts;
recalc();
}
sub2 = sub1;// ошибка 2 шага назад
sub1 = sub; // ошибка 1 шаг назад
sub = Z - X; // текущая ошибка
// NOTE: в первоисточнике было "текущее"(X) - "заданное"(Z),
// но правильно именно Z-X (проверено!)
sub2 = sub1;// ошибка 2 шага назад
sub1 = sub; // ошибка 1 шаг назад
sub = Z - X; // текущая ошибка
// NOTE: в первоисточнике было "текущее"(X) - "заданное"(Z),
// но правильно именно Z-X (проверено!)
// окончальное выходное(расчётное) значение
Y = Y + Kc * ( d0 * sub + d1 * sub1 + d2 * sub2 );
// окончальное выходное(расчётное) значение
Y = Y + Kc * ( d0 * sub + d1 * sub1 + d2 * sub2 );
if( Y > vlim ) Y = vlim;
else if ( Y < -vlim ) Y = -vlim;
}
// -----------------------------------------------------------------------------
void PID::reset()
{
sub2 = sub1 = sub = Y = 0;
}
// -----------------------------------------------------------------------------
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
<< " Y=" << std::setw(4) << p.Y
<< " vlim=" << std::setw(4) << p.vlim
<< " sub2=" << setw(4) << p.sub2
<< " sub1=" << setw(4) << p.sub1
<< " sub=" << setw(4) << p.sub;
}
// --------------------------------------------------------------------------
if( Y > vlim ) Y = vlim;
else if ( Y < -vlim ) Y = -vlim;
}
// -----------------------------------------------------------------------------
void PID::reset()
{
sub2 = sub1 = sub = Y = 0;
}
// -----------------------------------------------------------------------------
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
<< " Y=" << std::setw(4) << p.Y
<< " vlim=" << std::setw(4) << p.vlim
<< " sub2=" << setw(4) << p.sub2
<< " sub1=" << setw(4) << p.sub1
<< " sub=" << setw(4) << p.sub;
}
// --------------------------------------------------------------------------
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;
}
// --------------------------------------------------------------------------
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
......@@ -249,8 +249,8 @@ using namespace uniset;
}
// --------------------------------------------------------------------------
void SMInterface::localSetUndefinedState( IOController::IOStateList::iterator& it,
bool undefined,
uniset::ObjectId sid )
bool undefined,
uniset::ObjectId sid )
{
// CHECK_IC_PTR(localSetUndefinedState)
if( !ic )
......
......@@ -24,92 +24,92 @@
// --------------------------------------------------------------------------
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()
{
gMain = this;
}
// --------------------------------------------------------------------------------
SingleProcess::~SingleProcess()
{
}
// --------------------------------------------------------------------------------
void SingleProcess::finishterm( int signo )
{
if( !doneterm )
// --------------------------------------------------------------------------------
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()
{
cerr << "(SingleProcess:finishterm): прерываем процесс завершения...!" << endl << flush;
sigset(SIGALRM, SIG_DFL);
gMain->set_signals(false);
doneterm = 1;
raise(SIGKILL);
gMain = this;
}
}
// ------------------------------------------------------------------------------------------
void SingleProcess::terminated( int signo )
{
if( !signo || doneterm || !gMain || procterm )
return;
// --------------------------------------------------------------------------------
SingleProcess::~SingleProcess()
{
// lock
// на случай прихода нескольких сигналов
if( !procterm )
}
// --------------------------------------------------------------------------------
void SingleProcess::finishterm( int signo )
{
if( !doneterm )
{
procterm = 1;
sighold(SIGALRM);
sigset(SIGALRM, SingleProcess::finishterm);
alarm(TERMINATE_TIMEOUT);
sigrelse(SIGALRM);
gMain->term(signo);
cerr << "(SingleProcess:finishterm): прерываем процесс завершения...!" << endl << flush;
sigset(SIGALRM, SIG_DFL);
gMain->set_signals(false);
doneterm = 1;
raise(signo);
raise(SIGKILL);
}
}
}
// --------------------------------------------------------------------------------
void SingleProcess::set_signals( bool ask )
{
struct sigaction act, oact;
sigemptyset(&act.sa_mask);
// ------------------------------------------------------------------------------------------
void SingleProcess::terminated( int signo )
{
if( !signo || doneterm || !gMain || procterm )
return;
{
// lock
// на случай прихода нескольких сигналов
if( !procterm )
{
procterm = 1;
sighold(SIGALRM);
sigset(SIGALRM, SingleProcess::finishterm);
alarm(TERMINATE_TIMEOUT);
sigrelse(SIGALRM);
gMain->term(signo);
gMain->set_signals(false);
doneterm = 1;
raise(signo);
}
}
}
// --------------------------------------------------------------------------------
void SingleProcess::set_signals( bool ask )
{
struct sigaction act, oact;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESETHAND;
act.sa_flags = SA_RESETHAND;
// добавляем сигналы, которые будут игнорироваться
// при обработке сигнала
sigaddset(&act.sa_mask, SIGINT);
sigaddset(&act.sa_mask, SIGTERM);
sigaddset(&act.sa_mask, SIGABRT );
sigaddset(&act.sa_mask, SIGQUIT);
// sigaddset(&act.sa_mask, SIGSEGV);
// добавляем сигналы, которые будут игнорироваться
// при обработке сигнала
sigaddset(&act.sa_mask, SIGINT);
sigaddset(&act.sa_mask, SIGTERM);
sigaddset(&act.sa_mask, SIGABRT );
sigaddset(&act.sa_mask, SIGQUIT);
// sigaddset(&act.sa_mask, SIGSEGV);
// sigaddset(&act.sa_mask, SIGALRM);
// act.sa_flags = 0;
// act.sa_flags |= SA_RESTART;
// act.sa_flags |= SA_RESETHAND;
if(ask)
act.sa_handler = terminated;
else
act.sa_handler = SIG_DFL;
// sigaddset(&act.sa_mask, SIGALRM);
// act.sa_flags = 0;
// act.sa_flags |= SA_RESTART;
// act.sa_flags |= SA_RESETHAND;
if(ask)
act.sa_handler = terminated;
else
act.sa_handler = SIG_DFL;
sigaction(SIGINT, &act, &oact);
sigaction(SIGTERM, &act, &oact);
sigaction(SIGABRT, &act, &oact);
sigaction(SIGQUIT, &act, &oact);
sigaction(SIGINT, &act, &oact);
sigaction(SIGTERM, &act, &oact);
sigaction(SIGABRT, &act, &oact);
sigaction(SIGQUIT, &act, &oact);
// sigaction(SIGSEGV, &act, &oact);
}
// --------------------------------------------------------------------------------
// sigaction(SIGSEGV, &act, &oact);
}
// --------------------------------------------------------------------------------
} // end of namespace uniset
......@@ -21,112 +21,112 @@ using namespace std;
// --------------------------------------------------------------------------
namespace uniset
{
// --------------------------------------------------------------------------
namespace VTypes
{
// --------------------------------------------------------------------------
namespace VTypes
{
std::ostream& operator<<( std::ostream& os, const VType& vt )
{
return os << type2str(vt);
}
std::ostream& operator<<( std::ostream& os, const VType& vt )
{
return os << type2str(vt);
}
VType str2type( const std::string& s ) noexcept
{
if( s == "Byte" || s == "byte" )
return vtByte;
VType str2type( const std::string& s ) noexcept
{
if( s == "Byte" || s == "byte" )
return vtByte;
if( s == "F2" || s == "f2" )
return vtF2;
if( s == "F2" || s == "f2" )
return vtF2;
if( s == "F2r" || s == "f2r" )
return vtF2r;
if( s == "F2r" || s == "f2r" )
return vtF2r;
if( s == "F4" || s == "f4" )
return vtF4;
if( s == "F4" || s == "f4" )
return vtF4;
if( s == "Unsigned" || s == "unsigned" )
return vtUnsigned;
if( s == "Unsigned" || s == "unsigned" )
return vtUnsigned;
if( s == "Signed" || s == "signed" )
return vtSigned;
if( s == "Signed" || s == "signed" )
return vtSigned;
if( s == "I2" || s == "i2" )
return vtI2;
if( s == "I2" || s == "i2" )
return vtI2;
if( s == "I2r" || s == "i2r" )
return vtI2r;
if( s == "I2r" || s == "i2r" )
return vtI2r;
if( s == "U2" || s == "u2" )
return vtU2;
if( s == "U2" || s == "u2" )
return vtU2;
if( s == "U2r" || s == "u2r" )
return vtU2r;
if( s == "U2r" || s == "u2r" )
return vtU2r;
return vtUnknown;
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
if( t == vtByte )
return "Byte";
return vtUnknown;
}
// -------------------------------------------------------------------------
string type2str( VType t ) noexcept
{
if( t == vtByte )
return "Byte";
if( t == vtF2 )
return "F2";
if( t == vtF2 )
return "F2";
if( t == vtF2r )
return "F2r";
if( t == vtF2r )
return "F2r";
if( t == vtF4 )
return "F4";
if( t == vtF4 )
return "F4";
if( t == vtUnsigned )
return "Unsigned";
if( t == vtUnsigned )
return "Unsigned";
if( t == vtSigned )
return "Signed";
if( t == vtSigned )
return "Signed";
if( t == vtI2 )
return "I2";
if( t == vtI2 )
return "I2";
if( t == vtI2r )
return "I2r";
if( t == vtI2r )
return "I2r";
if( t == vtU2 )
return "U2";
if( t == vtU2 )
return "U2";
if( t == vtU2r )
return "U2r";
if( t == vtU2r )
return "U2r";
return "vtUnknown";
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
if( t == vtByte )
return Byte::wsize();
return "vtUnknown";
}
// -------------------------------------------------------------------------
int wsize( const VType t ) noexcept
{
if( t == vtByte )
return Byte::wsize();
if( t == vtF2 || t == vtF2r )
return F2::wsize();
if( t == vtF2 || t == vtF2r )
return F2::wsize();
if( t == vtF4 )
return F4::wsize();
if( t == vtF4 )
return F4::wsize();
if( t == vtUnsigned )
return Unsigned::wsize();
if( t == vtUnsigned )
return Unsigned::wsize();
if( t == vtSigned )
return Signed::wsize();
if( t == vtSigned )
return Signed::wsize();
if( t == vtI2 || t == vtI2r )
return I2::wsize();
if( t == vtI2 || t == vtI2r )
return I2::wsize();
if( t == vtU2 || t == vtU2r )
return U2::wsize();
if( t == vtU2 || t == vtU2r )
return U2::wsize();
return 1;
}
// -----------------------------------------------------------------------------
} // end of namespace VTypes
// -----------------------------------------------------------------------------
return 1;
}
// -----------------------------------------------------------------------------
} // end of namespace VTypes
// -----------------------------------------------------------------------------
} // end of namespace uniset
// -----------------------------------------------------------------------------
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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