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

make style

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