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

make style (atyle)

parent d79d7839
...@@ -198,6 +198,7 @@ int main(int argc, char** argv) ...@@ -198,6 +198,7 @@ int main(int argc, char** argv)
{ {
if( opt == 'z' ) if( opt == 'z' )
csv = true; csv = true;
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl; // cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
auto conf = uniset_init(argc, argv, conffile); auto conf = uniset_init(argc, argv, conffile);
UInterface ui(conf); UInterface ui(conf);
...@@ -712,13 +713,16 @@ int getValue( const string& args, UInterface& ui ) ...@@ -712,13 +713,16 @@ int getValue( const string& args, UInterface& ui )
// т.к. может сработать исключение, а нам надо вывести ',' // т.к. может сработать исключение, а нам надо вывести ','
// до числа, то сперва получаем val // до числа, то сперва получаем val
long val = ui.getValue(it.si.id, it.si.node); long val = ui.getValue(it.si.id, it.si.node);
if( csv && num++ > 0 ) if( csv && num++ > 0 )
cout << ","; cout << ",";
cout << val; cout << val;
} }
else else
cout << ui.getValue(it.si.id, it.si.node); cout << ui.getValue(it.si.id, it.si.node);
} }
break; break;
default: default:
...@@ -1009,14 +1013,14 @@ int oinfo(const string& args, UInterface& ui, const string& userparam ) ...@@ -1009,14 +1013,14 @@ int oinfo(const string& args, UInterface& ui, const string& userparam )
auto conf = uniset_conf(); auto conf = uniset_conf();
auto sl = uniset::getObjectsList( args, conf ); auto sl = uniset::getObjectsList( args, conf );
for( auto&& it : sl ) for( auto && it : sl )
{ {
if( it.node == DefaultObjectId ) if( it.node == DefaultObjectId )
it.node = conf->getLocalNode(); it.node = conf->getLocalNode();
try try
{ {
cout << ui.getObjectInfo(it.id, userparam,it.node) << endl; cout << ui.getObjectInfo(it.id, userparam, it.node) << endl;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
......
...@@ -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,24 +75,24 @@ class MBSlave ...@@ -75,24 +75,24 @@ 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 );
/*! интерфейс ModbusRTUSlave для обмена по RS */ /*! интерфейс ModbusRTUSlave для обмена по RS */
uniset::ModbusRTUSlaveSlot* rscomm; uniset::ModbusRTUSlaveSlot* rscomm;
......
...@@ -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 */
......
...@@ -19,7 +19,7 @@ class TestGen: ...@@ -19,7 +19,7 @@ class TestGen:
virtual void timerInfo( const uniset::TimerMessage* tm ) override; virtual void timerInfo( const uniset::TimerMessage* tm ) override;
virtual void sysCommand( const uniset::SystemMessage* sm ) override; virtual void sysCommand( const uniset::SystemMessage* sm ) override;
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
virtual void httpGetUserData( nlohmann::json& jdata ) override; virtual void httpGetUserData( nlohmann::json& jdata ) override;
#endif #endif
private: private:
......
...@@ -32,7 +32,7 @@ AC_ENABLE_SHARED(yes) ...@@ -32,7 +32,7 @@ AC_ENABLE_SHARED(yes)
AC_ENABLE_STATIC(no) AC_ENABLE_STATIC(no)
AM_PROG_LIBTOOL AM_PROG_LIBTOOL
ASTYLE_OPT="-A1 -T -C -S -N -L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi" ASTYLE_OPT="-A1 -T -C -S -L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi --max-instatement-indent=50"
AC_SUBST(ASTYLE_OPT) AC_SUBST(ASTYLE_OPT)
# Checks for libraries. # Checks for libraries.
......
...@@ -231,8 +231,8 @@ class IOControl: ...@@ -231,8 +231,8 @@ class IOControl:
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<IOControl> init_iocontrol( int argc, const char* const* argv, static std::shared_ptr<IOControl> init_iocontrol( int argc, const char* const* argv,
uniset::ObjectId icID, const std::shared_ptr<SharedMemory>& ic = nullptr, uniset::ObjectId icID, const std::shared_ptr<SharedMemory>& ic = nullptr,
const std::string& prefix = "io" ); const std::string& prefix = "io" );
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
......
...@@ -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 */
......
...@@ -1505,7 +1505,7 @@ void MBSlave::help_print( int argc, const char* const* argv ) ...@@ -1505,7 +1505,7 @@ void MBSlave::help_print( int argc, const char* const* argv )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::shared_ptr<MBSlave> MBSlave::init_mbslave(int argc, const char* const* argv, uniset::ObjectId icID, std::shared_ptr<MBSlave> MBSlave::init_mbslave(int argc, const char* const* argv, uniset::ObjectId icID,
const std::shared_ptr<SharedMemory>& ic, const string& prefix ) const std::shared_ptr<SharedMemory>& ic, const string& prefix )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name", "MBSlave1"); string name = conf->getArgParam("--" + prefix + "-name", "MBSlave1");
...@@ -1652,7 +1652,7 @@ ModbusRTU::mbErrCode MBSlave::writeOutputSingleRegister( ModbusRTU::WriteSingleO ...@@ -1652,7 +1652,7 @@ ModbusRTU::mbErrCode MBSlave::writeOutputSingleRegister( ModbusRTU::WriteSingleO
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::much_real_write( RegMap& rmap, const ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat, ModbusRTU::mbErrCode MBSlave::much_real_write( RegMap& rmap, const ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat,
size_t count, const int fn ) size_t count, const int fn )
{ {
mbinfo << myname << "(much_real_write): write mbID=" mbinfo << myname << "(much_real_write): write mbID="
<< ModbusRTU::dat2str(reg) << "(" << (int)reg << ")" << " count=" << count << " fn=" << fn << endl; << ModbusRTU::dat2str(reg) << "(" << (int)reg << ")" << " count=" << count << " fn=" << fn << endl;
...@@ -1985,7 +1985,7 @@ ModbusRTU::mbErrCode MBSlave::real_write_prop( IOProperty* p, ModbusRTU::ModbusD ...@@ -1985,7 +1985,7 @@ ModbusRTU::mbErrCode MBSlave::real_write_prop( IOProperty* p, ModbusRTU::ModbusD
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::much_real_read(RegMap& rmap, const ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat, ModbusRTU::mbErrCode MBSlave::much_real_read(RegMap& rmap, const ModbusRTU::ModbusData reg, ModbusRTU::ModbusData* dat,
size_t count, const int fn ) size_t count, const int fn )
{ {
mbinfo << myname << "(much_real_read): read mbID=" mbinfo << myname << "(much_real_read): read mbID="
<< ModbusRTU::dat2str(reg) << "(" << (int)reg << ") " << " count=" << count << ModbusRTU::dat2str(reg) << "(" << (int)reg << ") " << " count=" << count
...@@ -2278,20 +2278,20 @@ mbErrCode MBSlave::readInputRegisters( ReadInputMessage& query, ReadInputRetMess ...@@ -2278,20 +2278,20 @@ mbErrCode MBSlave::readInputRegisters( ReadInputMessage& query, ReadInputRetMess
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::setDateTime( ModbusRTU::SetDateTimeMessage& query, ModbusRTU::mbErrCode MBSlave::setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ) ModbusRTU::SetDateTimeRetMessage& reply )
{ {
return ModbusServer::replySetDateTime(query, reply, mblog); return ModbusServer::replySetDateTime(query, reply, mblog);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
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 )
{ {
mbinfo << myname << "(fileTransfer): " << query << endl; mbinfo << myname << "(fileTransfer): " << query << endl;
...@@ -2305,7 +2305,7 @@ ModbusRTU::mbErrCode MBSlave::fileTransfer( ModbusRTU::FileTransferMessage& quer ...@@ -2305,7 +2305,7 @@ ModbusRTU::mbErrCode MBSlave::fileTransfer( ModbusRTU::FileTransferMessage& quer
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query, ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply ) ReadCoilRetMessage& reply )
{ {
mbinfo << myname << "(readCoilStatus): " << query << endl; mbinfo << myname << "(readCoilStatus): " << query << endl;
...@@ -2378,7 +2378,7 @@ ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query, ...@@ -2378,7 +2378,7 @@ ModbusRTU::mbErrCode MBSlave::readCoilStatus( ReadCoilMessage& query,
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::readInputStatus( ReadInputStatusMessage& query, ModbusRTU::mbErrCode MBSlave::readInputStatus( ReadInputStatusMessage& query,
ReadInputStatusRetMessage& reply ) ReadInputStatusRetMessage& reply )
{ {
mbinfo << myname << "(readInputStatus): " << query << endl; mbinfo << myname << "(readInputStatus): " << query << endl;
...@@ -2451,7 +2451,7 @@ ModbusRTU::mbErrCode MBSlave::readInputStatus( ReadInputStatusMessage& query, ...@@ -2451,7 +2451,7 @@ ModbusRTU::mbErrCode MBSlave::readInputStatus( ReadInputStatusMessage& query,
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode MBSlave::forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ) ModbusRTU::ForceCoilsRetMessage& reply )
{ {
mbinfo << myname << "(forceMultipleCoils): " << query << endl; mbinfo << myname << "(forceMultipleCoils): " << query << endl;
...@@ -2488,7 +2488,7 @@ ModbusRTU::mbErrCode MBSlave::forceMultipleCoils( ModbusRTU::ForceCoilsMessage& ...@@ -2488,7 +2488,7 @@ ModbusRTU::mbErrCode MBSlave::forceMultipleCoils( ModbusRTU::ForceCoilsMessage&
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ) ModbusRTU::ForceSingleCoilRetMessage& reply )
{ {
mbinfo << myname << "(forceSingleCoil): " << query << endl; mbinfo << myname << "(forceSingleCoil): " << query << endl;
...@@ -2510,7 +2510,7 @@ ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage ...@@ -2510,7 +2510,7 @@ ModbusRTU::mbErrCode MBSlave::forceSingleCoil( ModbusRTU::ForceSingleCoilMessage
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode MBSlave::diagnostics( ModbusRTU::DiagnosticMessage& query, ModbusRTU::mbErrCode MBSlave::diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ) ModbusRTU::DiagnosticRetMessage& reply )
{ {
auto mbserver = dynamic_pointer_cast<ModbusServer>(mbslot); auto mbserver = dynamic_pointer_cast<ModbusServer>(mbslot);
......
...@@ -315,8 +315,8 @@ class MBSlave: ...@@ -315,8 +315,8 @@ class MBSlave:
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<MBSlave> init_mbslave(int argc, const char* const* argv, static std::shared_ptr<MBSlave> init_mbslave(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 = "mbs" ); const std::string& prefix = "mbs" );
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
...@@ -399,11 +399,11 @@ class MBSlave: ...@@ -399,11 +399,11 @@ class MBSlave:
/*! обработка 0x03 */ /*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */ /*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */ /*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
...@@ -411,16 +411,16 @@ class MBSlave: ...@@ -411,16 +411,16 @@ class MBSlave:
/*! обработка 0x0F */ /*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */ /*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */ /*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */ /*! обработка запросов на чтение ошибок */
// ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, // ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
......
...@@ -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");
......
...@@ -28,24 +28,24 @@ namespace uniset ...@@ -28,24 +28,24 @@ 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();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
......
...@@ -27,133 +27,133 @@ namespace uniset ...@@ -27,133 +27,133 @@ namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace extensions namespace extensions
{ {
static std::shared_ptr<DebugStream> _dlog; static std::shared_ptr<DebugStream> _dlog;
std::shared_ptr<DebugStream> dlog() std::shared_ptr<DebugStream> dlog()
{ {
if( _dlog ) if( _dlog )
return _dlog; return _dlog;
_dlog = make_shared<DebugStream>();
_dlog->setLogName("dlog"); _dlog = make_shared<DebugStream>();
auto conf = uniset_conf(); _dlog->setLogName("dlog");
if( conf ) auto conf = uniset_conf();
conf->initLogStream(_dlog, "dlog");
return _dlog; if( conf )
} conf->initLogStream(_dlog, "dlog");
// -------------------------------------------------------------------------
static uniset::ObjectId shmID = DefaultObjectId;
uniset::ObjectId getSharedMemoryID() return _dlog;
{ }
if( shmID != DefaultObjectId ) // -------------------------------------------------------------------------
return shmID; static uniset::ObjectId shmID = DefaultObjectId;
auto conf = uniset_conf(); uniset::ObjectId getSharedMemoryID()
{
if( shmID != DefaultObjectId )
return shmID;
string sname = conf->getArgParam("--smemory-id", "SharedMemory1"); auto conf = uniset_conf();
shmID = conf->getControllerID(sname);
if( shmID == uniset::DefaultObjectId ) string sname = conf->getArgParam("--smemory-id", "SharedMemory1");
{ shmID = conf->getControllerID(sname);
ostringstream err;
err << ": Unknown ID for '" << sname << "'" << endl;
dcrit << err.str() << endl;
throw SystemError(err.str());
}
// cout << "(uniset): shm=" << name << " id=" << shmID << endl; if( shmID == uniset::DefaultObjectId )
return shmID;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{ {
if( s.empty() ) ostringstream err;
return; err << ": Unknown ID for '" << sname << "'" << endl;
dcrit << err.str() << endl;
throw SystemError(err.str());
}
string::size_type pos = s.find("\\n"); // cout << "(uniset): shm=" << name << " id=" << shmID << endl;
return shmID;
}
// -------------------------------------------------------------------------
void escape_string( string& s )
{
if( s.empty() )
return;
while( pos != string::npos ) string::size_type pos = s.find("\\n");
{
s.replace(pos, 2, "\n");
pos = s.find("\\n");
}
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
xmlNode* getCalibrationsSection() while( pos != string::npos )
{ {
if( xmlCalibrationsNode ) s.replace(pos, 2, "\n");
return xmlCalibrationsNode; pos = s.find("\\n");
}
}
// -------------------------------------------------------------------------
static xmlNode* xmlCalibrationsNode = 0;
xmlCalibrationsNode = uniset_conf()->getNode("Calibrations"); xmlNode* getCalibrationsSection()
{
if( xmlCalibrationsNode )
return 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() ) xmlNode* findNode( xmlNode* node, const string& snode, const string& field )
return 0; {
if( !node )
return 0;
for( ; it; it.goNext() ) UniXML::iterator it(node);
{
if( snode == it.getProp(field) )
return it;
}
if( !it.goChildren() )
return 0; return 0;
for( ; it; it.goNext() )
{
if( snode == it.getProp(field) )
return it;
} }
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname ) return 0;
}
// -------------------------------------------------------------------------
Calibration* buildCalibrationDiagram( const std::string& dname )
{
xmlNode* root = getCalibrationsSection();
if( !root )
{ {
xmlNode* root = getCalibrationsSection(); ostringstream err;
err << "(buildCalibrationDiagram): НЕ НАЙДЕН корневой узел для калибровочных диаграмм";
if( !root ) dcrit << err.str() << endl;
{ throw SystemError( err.str());
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 ) xmlNode* dnode = findNode( root, dname, "name" );
if( !dnode )
{ {
while(1) ostringstream err;
{ err << "(buildCalibrationDiagram): НЕ НАЙДЕНА калибровочная диаграмма '" << dname << "'";
int istatus; dcrit << err.str() << endl;
pid_t pid = waitpid( -1, &istatus, WNOHANG ); throw SystemError( err.str());
}
if( pid == -1 && errno == EINTR ) continue; return new Calibration(dnode);
}
// -------------------------------------------------------------------------
void on_sigchild( int sig )
{
while(1)
{
int istatus;
pid_t pid = waitpid( -1, &istatus, WNOHANG );
if( pid <= 0 ) break; if( pid == -1 && errno == EINTR ) continue;
}
if( pid <= 0 ) break;
} }
// -------------------------------------------------------------------------- }
// --------------------------------------------------------------------------
} // end of namespace extensions } // end of namespace extensions
} // 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 )
......
...@@ -25,107 +25,107 @@ namespace uniset ...@@ -25,107 +25,107 @@ 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
......
...@@ -32,10 +32,10 @@ LostPassiveTestProc::LostPassiveTestProc( uniset::ObjectId id, xmlNode* confnode ...@@ -32,10 +32,10 @@ LostPassiveTestProc::LostPassiveTestProc( uniset::ObjectId id, xmlNode* confnode
if( it.getProp("iotype") != "AI" ) if( it.getProp("iotype") != "AI" )
continue; continue;
slist.emplace(it.getIntProp("id"),0); slist.emplace(it.getIntProp("id"), 0);
} }
setMaxSizeOfMessageQueue(slist.size()*2+500); setMaxSizeOfMessageQueue(slist.size() * 2 + 500);
smTestID = slist.begin()->first; smTestID = slist.begin()->first;
} }
...@@ -53,6 +53,7 @@ long LostPassiveTestProc::checkValue( ObjectId sid ) ...@@ -53,6 +53,7 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
{ {
std::lock_guard<std::mutex> lock(mut); std::lock_guard<std::mutex> lock(mut);
auto s = slist.find(sid); auto s = slist.find(sid);
if( s == slist.end() ) if( s == slist.end() )
{ {
ostringstream err; ostringstream err;
...@@ -66,13 +67,13 @@ long LostPassiveTestProc::checkValue( ObjectId sid ) ...@@ -66,13 +67,13 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
LostPassiveTestProc::LostPassiveTestProc() LostPassiveTestProc::LostPassiveTestProc()
{ {
cerr << ": init failed!!!!!!!!!!!!!!!" << endl; cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception(myname+"(init): FAILED.."); throw uniset::Exception(myname + "(init): FAILED..");
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void LostPassiveTestProc::askSensors(UniversalIO::UIOCommand cmd) void LostPassiveTestProc::askSensors(UniversalIO::UIOCommand cmd)
{ {
for( const auto& s: slist ) for( const auto& s : slist )
askSensor(s.first,cmd); askSensor(s.first, cmd);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void LostPassiveTestProc::sensorInfo(const SensorMessage* sm) void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
...@@ -80,6 +81,7 @@ void LostPassiveTestProc::sensorInfo(const SensorMessage* sm) ...@@ -80,6 +81,7 @@ void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
std::lock_guard<std::mutex> lock(mut); std::lock_guard<std::mutex> lock(mut);
auto s = slist.find(sm->id); auto s = slist.find(sm->id);
if( s == slist.end() ) if( s == slist.end() )
{ {
mycrit << myname << "(sensorInfo): ERROR: message from UNKNOWN SENSOR sm->id=" << sm->id << endl; mycrit << myname << "(sensorInfo): ERROR: message from UNKNOWN SENSOR sm->id=" << sm->id << endl;
......
...@@ -24,7 +24,7 @@ class LostPassiveTestProc: ...@@ -24,7 +24,7 @@ class LostPassiveTestProc:
virtual void sensorInfo( const uniset::SensorMessage* sm ) override; virtual void sensorInfo( const uniset::SensorMessage* sm ) override;
std::mutex mut; std::mutex mut;
std::unordered_map<uniset::ObjectId,long> slist; std::unordered_map<uniset::ObjectId, long> slist;
private: private:
}; };
......
...@@ -24,7 +24,7 @@ void LostTestProc::setChildPassiveProc( const std::shared_ptr<LostPassiveTestPro ...@@ -24,7 +24,7 @@ void LostTestProc::setChildPassiveProc( const std::shared_ptr<LostPassiveTestPro
LostTestProc::LostTestProc() LostTestProc::LostTestProc()
{ {
cerr << ": init failed!!!!!!!!!!!!!!!" << endl; cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw uniset::Exception(myname+"(init): FAILED.."); throw uniset::Exception(myname + "(init): FAILED..");
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void LostTestProc::sysCommand( const uniset::SystemMessage* sm ) void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
...@@ -36,11 +36,11 @@ void LostTestProc::sysCommand( const uniset::SystemMessage* sm ) ...@@ -36,11 +36,11 @@ void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
askTimer(tmCheck, checkTime); askTimer(tmCheck, checkTime);
// начальная инициализация значений в SM // начальная инициализация значений в SM
for( auto&& s: slist ) for( auto && s : slist )
{ {
try try
{ {
ui->setValue(s.first,s.second); ui->setValue(s.first, s.second);
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
...@@ -78,11 +78,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm ) ...@@ -78,11 +78,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
waitEmpty = false; waitEmpty = false;
myinfo << myname << ": [OK]: empty queue. CHECK VALUE... " << endl; myinfo << myname << ": [OK]: empty queue. CHECK VALUE... " << endl;
for( auto&& s: slist )
for( auto && s : slist )
{ {
try try
{ {
long smValue = ui->getValue(s.first); long smValue = ui->getValue(s.first);
if( smValue != s.second ) if( smValue != s.second )
{ {
cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << s.second << endl; cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << s.second << endl;
...@@ -94,6 +96,7 @@ void LostTestProc::timerInfo( const TimerMessage* tm ) ...@@ -94,6 +96,7 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
if( child ) if( child )
{ {
long childValue = child->checkValue(s.first); long childValue = child->checkValue(s.first);
if( smValue != childValue ) if( smValue != childValue )
{ {
cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << childValue cerr << myname << "(check): ERROR!! sid=" << s.first << " smValue=" << smValue << " != " << childValue
...@@ -108,13 +111,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm ) ...@@ -108,13 +111,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
cerr << i2->info << endl; cerr << i2->info << endl;
// cerr << "JSON: " << endl; // cerr << "JSON: " << endl;
// Poco::URI::QueryParameters p; // Poco::URI::QueryParameters p;
// auto j = httpGet(p); // auto j = httpGet(p);
// cerr << j.dump() << endl; // cerr << j.dump() << endl;
// cerr << "-------------------------" << endl; // cerr << "-------------------------" << endl;
// auto j2 = child->httpGet(p); // auto j2 = child->httpGet(p);
// cerr << j2.dump() << endl; // cerr << j2.dump() << endl;
std::abort(); std::abort();
} }
...@@ -127,20 +130,21 @@ void LostTestProc::timerInfo( const TimerMessage* tm ) ...@@ -127,20 +130,21 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
} }
myinfo << myname << ": [OK]: UPDATE VALUE... " << endl; myinfo << myname << ": [OK]: UPDATE VALUE... " << endl;
for( auto&& s: slist )
for( auto && s : slist )
{ {
try try
{ {
// Выставляем новое значение // Выставляем новое значение
ui->setValue(s.first, s.second+1); ui->setValue(s.first, s.second + 1);
// проверяем что сохранилось // проверяем что сохранилось
long smValue = ui->getValue(s.first); long smValue = ui->getValue(s.first);
if(ui->getValue(s.first) != (s.second+1) ) if(ui->getValue(s.first) != (s.second + 1) )
{ {
cerr << myname << "(check): SAVE TO SM ERROR!! sid=" << s.first cerr << myname << "(check): SAVE TO SM ERROR!! sid=" << s.first
<< " value=" << smValue << " != " << (s.second+1) << endl; << " value=" << smValue << " != " << (s.second + 1) << endl;
uniset::SimpleInfo_var i = getInfo(); uniset::SimpleInfo_var i = getInfo();
cerr << i->info << endl; cerr << i->info << endl;
std::abort(); std::abort();
......
...@@ -43,7 +43,7 @@ int main(int argc, const char** argv) ...@@ -43,7 +43,7 @@ int main(int argc, const char** argv)
act->add(tp); act->add(tp);
ostringstream sp; ostringstream sp;
sp << "TestProc" << (i+max); sp << "TestProc" << (i + max);
cout << "..create passive " << sp.str() << endl; cout << "..create passive " << sp.str() << endl;
auto child = make_shared<LostPassiveTestProc>( conf->getObjectID(sp.str())); auto child = make_shared<LostPassiveTestProc>( conf->getObjectID(sp.str()));
......
...@@ -28,15 +28,15 @@ ...@@ -28,15 +28,15 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
class LimitTimers: class LimitTimers:
public uniset::Exception public uniset::Exception
{ {
public: public:
LimitTimers(): Exception("LimitTimers") {} LimitTimers(): Exception("LimitTimers") {}
/*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */ /*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */
LimitTimers(const std::string& err): Exception(err) {} LimitTimers(const std::string& err): Exception(err) {}
}; };
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
/*! /*!
......
...@@ -283,13 +283,15 @@ class DebugStream : public std::ostream ...@@ -283,13 +283,15 @@ class DebugStream : public std::ostream
public: public:
explicit IosFlagSaver(std::ostream& _ios): explicit IosFlagSaver(std::ostream& _ios):
ios(_ios), ios(_ios),
f(_ios.flags()) { f(_ios.flags())
{
} }
~IosFlagSaver() { ~IosFlagSaver()
{
ios.flags(f); ios.flags(f);
} }
IosFlagSaver(const IosFlagSaver &rhs) = delete; IosFlagSaver(const IosFlagSaver& rhs) = delete;
IosFlagSaver& operator= (const IosFlagSaver& rhs) = delete; IosFlagSaver& operator= (const IosFlagSaver& rhs) = delete;
private: private:
......
...@@ -82,7 +82,7 @@ class IOController: ...@@ -82,7 +82,7 @@ class IOController:
IOController_i::CalibrateInfo getCalibrateInfo( uniset::ObjectId sid ) override; IOController_i::CalibrateInfo getCalibrateInfo( uniset::ObjectId sid ) override;
inline IOController_i::SensorInfo SensorInfo( const uniset::ObjectId sid, inline IOController_i::SensorInfo SensorInfo( const uniset::ObjectId sid,
const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode()) const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode())
{ {
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
si.id = sid; si.id = sid;
...@@ -98,7 +98,7 @@ class IOController: ...@@ -98,7 +98,7 @@ class IOController:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// http API // http API
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override; // virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
#endif #endif
...@@ -245,8 +245,8 @@ class IOController: ...@@ -245,8 +245,8 @@ class IOController:
IOStateList::iterator myiofind( uniset::ObjectId id ); IOStateList::iterator myiofind( uniset::ObjectId id );
size_t ioCount(); size_t ioCount();
// -------------------------- // --------------------------
private: private:
friend class NCRestorer; friend class NCRestorer;
friend class SMInterface; friend class SMInterface;
......
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
class NCRestorer; class NCRestorer;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
/*! /*!
\page page_IONotifyController Хранение информации о состоянии с уведомлениями об изменении (IONotifyController) \page page_IONotifyController Хранение информации о состоянии с уведомлениями об изменении (IONotifyController)
...@@ -158,7 +158,7 @@ class IONotifyController: ...@@ -158,7 +158,7 @@ class IONotifyController:
virtual IONotifyController_i::ThresholdsListSeq* getThresholdsList() override; virtual IONotifyController_i::ThresholdsListSeq* getThresholdsList() override;
virtual uniset::IDSeq* askSensorsSeq(const uniset::IDSeq& lst, virtual uniset::IDSeq* askSensorsSeq(const uniset::IDSeq& lst,
const uniset::ConsumerInfo& ci, UniversalIO::UIOCommand cmd) override; const uniset::ConsumerInfo& ci, UniversalIO::UIOCommand cmd) override;
// -------------------------------------------- // --------------------------------------------
......
...@@ -27,25 +27,25 @@ ...@@ -27,25 +27,25 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
/*! Класс работы с файлами содержащими IOR объекта /*! Класс работы с файлами содержащими IOR объекта
\todo Для оптимизации можно сделать кэширование id:node > filename \todo Для оптимизации можно сделать кэширование id:node > filename
*/ */
class IORFile class IORFile
{ {
public: public:
IORFile(); IORFile();
static std::string getIOR( const ObjectId id ); static std::string getIOR( const ObjectId id );
static void setIOR( const ObjectId id, const std::string& sior ); static void setIOR( const ObjectId id, const std::string& sior );
static void unlinkIOR( const ObjectId id ); static void unlinkIOR( const ObjectId id );
static std::string getFileName( const ObjectId id ); static std::string getFileName( const ObjectId id );
protected: protected:
private: private:
}; };
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
} // end of namespace } // end of namespace
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#endif #endif
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
class UniSetObject; class UniSetObject;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
/*! \class LT_Object /*! \class LT_Object
......
...@@ -25,51 +25,51 @@ namespace uniset ...@@ -25,51 +25,51 @@ namespace uniset
namespace LogServerTypes namespace LogServerTypes
{ {
const unsigned int MAGICNUM = 0x20160417; const unsigned int MAGICNUM = 0x20160417;
enum Command enum Command
{ {
cmdNOP, /*!< отсутствие команды */ cmdNOP, /*!< отсутствие команды */
cmdSetLevel, /*!< установить уровень вывода */ cmdSetLevel, /*!< установить уровень вывода */
cmdAddLevel, /*!< добавить уровень вывода */ cmdAddLevel, /*!< добавить уровень вывода */
cmdDelLevel, /*!< удалить уровень вывода */ cmdDelLevel, /*!< удалить уровень вывода */
cmdRotate, /*!< пересоздать файл с логами */ cmdRotate, /*!< пересоздать файл с логами */
cmdOffLogFile, /*!< отключить запись файла логов (если включена) */ cmdOffLogFile, /*!< отключить запись файла логов (если включена) */
cmdOnLogFile, /*!< включить запись файла логов (если была отключена) */ cmdOnLogFile, /*!< включить запись файла логов (если была отключена) */
// работа с логами по умолчанию // работа с логами по умолчанию
cmdSaveLogLevel, /*!< запомнить текущее состояние логов (для восстановления при завершении сессии или команде Restore) */ cmdSaveLogLevel, /*!< запомнить текущее состояние логов (для восстановления при завершении сессии или команде Restore) */
cmdRestoreLogLevel, /*!< восстановить последнее запоненное (cmdSaveLogLevel) состояние логов (т.е. не восстанавливать как было, при завершении сессии) */ cmdRestoreLogLevel, /*!< восстановить последнее запоненное (cmdSaveLogLevel) состояние логов (т.е. не восстанавливать как было, при завершении сессии) */
// команды требующий ответа.. // команды требующий ответа..
cmdList, /*!< вывести список контролируемых логов */ cmdList, /*!< вывести список контролируемых логов */
cmdFilterMode, /*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */ cmdFilterMode, /*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */
cmdViewDefaultLogLevel /*!< вывести уровни логов сохранённых как умолчательный (cmdSaveLogLevel) */ cmdViewDefaultLogLevel /*!< вывести уровни логов сохранённых как умолчательный (cmdSaveLogLevel) */
// cmdSetLogFile // cmdSetLogFile
}; };
std::ostream& operator<<(std::ostream& os, Command c ); std::ostream& operator<<(std::ostream& os, Command c );
struct lsMessage struct lsMessage
{
lsMessage(): magic(MAGICNUM), cmd(cmdNOP), data(0)
{ {
lsMessage(): magic(MAGICNUM), cmd(cmdNOP), data(0) std::memset(logname, 0, sizeof(logname));
{ }
std::memset(logname, 0, sizeof(logname)); unsigned int magic;
} Command cmd;
unsigned int magic; unsigned int data;
Command cmd;
unsigned int data;
static const size_t MAXLOGNAME = 30; static const size_t MAXLOGNAME = 30;
char logname[MAXLOGNAME + 1]; // +1 reserverd for '\0' char logname[MAXLOGNAME + 1]; // +1 reserverd for '\0'
void setLogName( const std::string& name ); void setLogName( const std::string& name );
// для команды 'cmdSetLogFile' // для команды 'cmdSetLogFile'
// static const size_t MAXLOGFILENAME = 200; // static const size_t MAXLOGFILENAME = 200;
// char logfile[MAXLOGFILENAME]; // char logfile[MAXLOGFILENAME];
} __attribute__((packed)); } __attribute__((packed));
std::ostream& operator<<(std::ostream& os, lsMessage& m ); std::ostream& operator<<(std::ostream& os, lsMessage& m );
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
......
...@@ -25,9 +25,9 @@ ...@@ -25,9 +25,9 @@
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr; typedef std::shared_ptr<uniset::VoidMessage> VoidMessagePtr;
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/*! \class MQMutex /*! \class MQMutex
* Простая "многопоточная" очередь сообщений с использованием std::mutex. * Простая "многопоточная" очередь сообщений с использованием std::mutex.
......
...@@ -28,71 +28,71 @@ ...@@ -28,71 +28,71 @@
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
// rwmutex.. // rwmutex..
class uniset_rwmutex class uniset_rwmutex
{ {
public: public:
uniset_rwmutex( const std::string& name ); uniset_rwmutex( const std::string& name );
uniset_rwmutex(); uniset_rwmutex();
~uniset_rwmutex(); ~uniset_rwmutex();
void lock(); void lock();
void unlock(); void unlock();
void wrlock(); void wrlock();
void rlock(); void rlock();
bool try_lock(); bool try_lock();
bool try_rlock(); bool try_rlock();
bool try_wrlock(); bool try_wrlock();
uniset_rwmutex( const uniset_rwmutex& r ) = delete; uniset_rwmutex( const uniset_rwmutex& r ) = delete;
uniset_rwmutex& operator=(const uniset_rwmutex& r) = delete; uniset_rwmutex& operator=(const uniset_rwmutex& r) = delete;
uniset_rwmutex( uniset_rwmutex&& r ) = default; uniset_rwmutex( uniset_rwmutex&& r ) = default;
uniset_rwmutex& operator=(uniset_rwmutex&& r) = default; uniset_rwmutex& operator=(uniset_rwmutex&& r) = default;
inline std::string name() inline std::string name()
{ {
return nm; return nm;
} }
inline void setName( const std::string& name ) inline void setName( const std::string& name )
{ {
nm = name; nm = name;
} }
private: private:
std::string nm; std::string nm;
friend class uniset_rwmutex_lock; friend class uniset_rwmutex_lock;
std::unique_ptr<Poco::RWLock> m; std::unique_ptr<Poco::RWLock> m;
}; };
std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m ); std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m );
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class uniset_rwmutex_wrlock class uniset_rwmutex_wrlock
{ {
public: public:
uniset_rwmutex_wrlock( uniset_rwmutex& m ); uniset_rwmutex_wrlock( uniset_rwmutex& m );
~uniset_rwmutex_wrlock(); ~uniset_rwmutex_wrlock();
private: private:
uniset_rwmutex_wrlock(const uniset_rwmutex_wrlock&) = delete; uniset_rwmutex_wrlock(const uniset_rwmutex_wrlock&) = delete;
uniset_rwmutex_wrlock& operator=(const uniset_rwmutex_wrlock&) = delete; uniset_rwmutex_wrlock& operator=(const uniset_rwmutex_wrlock&) = delete;
uniset_rwmutex& m; uniset_rwmutex& m;
}; };
class uniset_rwmutex_rlock class uniset_rwmutex_rlock
{ {
public: public:
uniset_rwmutex_rlock( uniset_rwmutex& m ); uniset_rwmutex_rlock( uniset_rwmutex& m );
~uniset_rwmutex_rlock(); ~uniset_rwmutex_rlock();
private: private:
uniset_rwmutex_rlock(const uniset_rwmutex_rlock&) = delete; uniset_rwmutex_rlock(const uniset_rwmutex_rlock&) = delete;
uniset_rwmutex_rlock& operator=(const uniset_rwmutex_rlock&) = delete; uniset_rwmutex_rlock& operator=(const uniset_rwmutex_rlock&) = delete;
uniset_rwmutex& m; uniset_rwmutex& m;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of UniSetTypes namespace } // end of UniSetTypes namespace
#endif #endif
...@@ -34,31 +34,31 @@ namespace uniset ...@@ -34,31 +34,31 @@ namespace uniset
*/ */
namespace ORepHelpers namespace ORepHelpers
{ {
//! Получение ссылки на корень репозитория //! Получение ссылки на корень репозитория
CosNaming::NamingContext_ptr getRootNamingContext( const CORBA::ORB_ptr orb, CosNaming::NamingContext_ptr getRootNamingContext( const CORBA::ORB_ptr orb,
const std::string& nsName, int timeOutSec = 2); const std::string& nsName, int timeOutSec = 2);
//! Получение контекста по заданному имени //! Получение контекста по заданному имени
CosNaming::NamingContext_ptr getContext(const std::string& cname, int argc, CosNaming::NamingContext_ptr getContext(const std::string& cname, int argc,
const char* const* argv, const std::string& nsName) const char* const* argv, const std::string& nsName)
throw(uniset::ORepFailed); throw(uniset::ORepFailed);
CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const std::string& cname, CosNaming::NamingContext_ptr getContext(const CORBA::ORB_ptr orb, const std::string& cname,
const std::string& nsName) const std::string& nsName)
throw(uniset::ORepFailed); throw(uniset::ORepFailed);
//! Функция отделяющая имя секции от полного имени //! Функция отделяющая имя секции от полного имени
const std::string getSectionName(const std::string& fullName, const std::string& brk = "/"); const std::string getSectionName(const std::string& fullName, const std::string& brk = "/");
//! Функция выделения имени из полного имени //! Функция выделения имени из полного имени
const std::string getShortName(const std::string& fullName, const std::string& brk = "/"); const std::string getShortName(const std::string& fullName, const std::string& brk = "/");
//! Проверка на наличие недопустимых символов //! Проверка на наличие недопустимых символов
char checkBadSymbols(const std::string& str); char checkBadSymbols(const std::string& str);
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */ /*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
std::string BadSymbolsToStr(); std::string BadSymbolsToStr();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -27,60 +27,60 @@ ...@@ -27,60 +27,60 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
class ObjectIndex class ObjectIndex
{ {
public: public:
ObjectIndex() {}; ObjectIndex() {};
virtual ~ObjectIndex() {}; virtual ~ObjectIndex() {};
// info // info
// \return nullptr if not found // \return nullptr if not found
virtual const ObjectInfo* getObjectInfo( const uniset::ObjectId ) const noexcept = 0; virtual const ObjectInfo* getObjectInfo( const uniset::ObjectId ) const noexcept = 0;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept = 0; virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept = 0;
static std::string getBaseName( const std::string& fname ) noexcept; static std::string getBaseName( const std::string& fname ) noexcept;
// object id // object id
//! \return uniset::DefaultObjectId if not found //! \return uniset::DefaultObjectId if not found
virtual ObjectId getIdByName(const std::string& name) const noexcept = 0; virtual ObjectId getIdByName(const std::string& name) const noexcept = 0;
//! \return "" if not found //! \return "" if not found
virtual std::string getNameById( const uniset::ObjectId id ) const noexcept; virtual std::string getNameById( const uniset::ObjectId id ) const noexcept;
// node // node
//! \return "" if not found //! \return "" if not found
inline std::string getNodeName( const uniset::ObjectId id ) const noexcept inline std::string getNodeName( const uniset::ObjectId id ) const noexcept
{ {
return getNameById(id); return getNameById(id);
} }
//! \return uniset::DefaultObjectId if not found //! \return uniset::DefaultObjectId if not found
inline ObjectId getNodeId( const std::string& name ) const noexcept inline ObjectId getNodeId( const std::string& name ) const noexcept
{ {
return getIdByName(name); return getIdByName(name);
} }
// src name // src name
//! \return "" if not found //! \return "" if not found
virtual std::string getMapName( const uniset::ObjectId id ) const noexcept = 0; virtual std::string getMapName( const uniset::ObjectId id ) const noexcept = 0;
//! \return "" if not found //! \return "" if not found
virtual std::string getTextName( const uniset::ObjectId id ) const noexcept = 0; virtual std::string getTextName( const uniset::ObjectId id ) const noexcept = 0;
// //
virtual std::ostream& printMap(std::ostream& os) const noexcept = 0; virtual std::ostream& printMap(std::ostream& os) const noexcept = 0;
void initLocalNode( const uniset::ObjectId nodeid ) noexcept; void initLocalNode( const uniset::ObjectId nodeid ) noexcept;
protected: protected:
std::string nmLocalNode = {""}; // поле для оптимизации получения LocalNode std::string nmLocalNode = {""}; // поле для оптимизации получения LocalNode
private: private:
}; };
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
} // end of namespace } // end of namespace
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#endif #endif
...@@ -30,37 +30,37 @@ ...@@ -30,37 +30,37 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
/*! /*!
\todo Проверить функции этого класса на повторную входимость \todo Проверить функции этого класса на повторную входимость
\bug При обращении к objectsMap[0].textName срабатывает исключение(видимо какое-то из std). \bug При обращении к objectsMap[0].textName срабатывает исключение(видимо какое-то из std).
Требуется дополнительное изучение. Требуется дополнительное изучение.
*/ */
class ObjectIndex_Array: class ObjectIndex_Array:
public ObjectIndex public ObjectIndex
{ {
public: public:
ObjectIndex_Array(const ObjectInfo* objectInfo); ObjectIndex_Array(const ObjectInfo* objectInfo);
virtual ~ObjectIndex_Array(); virtual ~ObjectIndex_Array();
virtual const ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override; virtual const ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override; virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override;
virtual ObjectId getIdByName( const std::string& name ) const noexcept override; virtual ObjectId getIdByName( const std::string& name ) const noexcept override;
virtual std::string getMapName( const ObjectId id ) const noexcept override; virtual std::string getMapName( const ObjectId id ) const noexcept override;
virtual std::string getTextName( const ObjectId id ) const noexcept override; virtual std::string getTextName( const ObjectId id ) const noexcept override;
virtual std::ostream& printMap(std::ostream& os) const noexcept override; virtual std::ostream& printMap(std::ostream& os) const noexcept override;
friend std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi ); friend std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi );
private: private:
size_t numOfObject; size_t numOfObject;
typedef std::unordered_map<std::string, ObjectId> MapObjectKey; typedef std::unordered_map<std::string, ObjectId> MapObjectKey;
MapObjectKey::iterator MapObjectKeyIterator; MapObjectKey::iterator MapObjectKeyIterator;
MapObjectKey mok; MapObjectKey mok;
const ObjectInfo* objectInfo; const ObjectInfo* objectInfo;
size_t maxId; size_t maxId;
}; };
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
} // end of namespace } // end of namespace
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#endif #endif
...@@ -31,35 +31,35 @@ ...@@ -31,35 +31,35 @@
namespace uniset namespace uniset
{ {
/*! \todo Проверить функции этого класса на повторную входимость */ /*! \todo Проверить функции этого класса на повторную входимость */
class ObjectIndex_XML: class ObjectIndex_XML:
public ObjectIndex public ObjectIndex
{ {
public: public:
ObjectIndex_XML(const std::string& xmlfile, size_t minSize = 1000 ); ObjectIndex_XML(const std::string& xmlfile, size_t minSize = 1000 );
ObjectIndex_XML( const std::shared_ptr<UniXML>& xml, size_t minSize = 1000 ); ObjectIndex_XML( const std::shared_ptr<UniXML>& xml, size_t minSize = 1000 );
virtual ~ObjectIndex_XML(); virtual ~ObjectIndex_XML();
virtual const uniset::ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override; virtual const uniset::ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override;
virtual const uniset::ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override; virtual const uniset::ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override;
virtual ObjectId getIdByName( const std::string& name ) const noexcept override; virtual ObjectId getIdByName( const std::string& name ) const noexcept override;
virtual std::string getMapName( const ObjectId id ) const noexcept override; virtual std::string getMapName( const ObjectId id ) const noexcept override;
virtual std::string getTextName( const ObjectId id ) const noexcept override; virtual std::string getTextName( const ObjectId id ) const noexcept override;
virtual std::ostream& printMap(std::ostream& os) const noexcept override; virtual std::ostream& printMap(std::ostream& os) const noexcept override;
friend std::ostream& operator<<(std::ostream& os, ObjectIndex_XML& oi ); friend std::ostream& operator<<(std::ostream& os, ObjectIndex_XML& oi );
protected: protected:
void build( const std::shared_ptr<UniXML>& xml ); void build( const std::shared_ptr<UniXML>& xml );
size_t read_section(const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind ); size_t read_section(const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind );
size_t read_nodes( const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind ); size_t read_nodes( const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind );
private: private:
typedef std::unordered_map<std::string, ObjectId> MapObjectKey; typedef std::unordered_map<std::string, ObjectId> MapObjectKey;
MapObjectKey mok; // для обратного писка MapObjectKey mok; // для обратного писка
std::vector<ObjectInfo> omap; // для прямого поиска std::vector<ObjectInfo> omap; // для прямого поиска
}; };
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
} // end of namespace } // end of namespace
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#endif #endif
...@@ -22,103 +22,103 @@ ...@@ -22,103 +22,103 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
// Шаблон для "универсальной инициализации объекта(процесса)". // Шаблон для "универсальной инициализации объекта(процесса)".
// Использование: // Использование:
// auto m = make_object<MyClass>("ObjectId","secname",...); // auto m = make_object<MyClass>("ObjectId","secname",...);
// -- // --
// Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. ); // Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. );
// --------------- // ---------------
// Если secname задан, то ищется: <secname name="ObjectId" ....> // Если secname задан, то ищется: <secname name="ObjectId" ....>
// Если secname не задан, то: <idname name="idname" ...> // Если secname не задан, то: <idname name="idname" ...>
//---------------- //----------------
template<typename T, typename... _Args> template<typename T, typename... _Args>
std::shared_ptr<T> make_object( const std::string& idname, const std::string& secname, _Args&& ... __args ) std::shared_ptr<T> make_object( const std::string& idname, const std::string& secname, _Args&& ... __args )
{ {
auto conf = uniset::uniset_conf(); auto conf = uniset::uniset_conf();
uniset::ObjectId id = conf->getObjectID(idname); uniset::ObjectId id = conf->getObjectID(idname);
if( id == uniset::DefaultObjectId ) if( id == uniset::DefaultObjectId )
throw uniset::SystemError("(make_object<" + string(typeid(T).name()) + ">): Not found ID for '" + idname + "'"); throw uniset::SystemError("(make_object<" + string(typeid(T).name()) + ">): Not found ID for '" + idname + "'");
auto xml = conf->getConfXML(); auto xml = conf->getConfXML();
std::string s( (secname.empty() ? idname : secname) ); std::string s( (secname.empty() ? idname : secname) );
xmlNode* cnode = conf->findNode(xml->getFirstNode(), s, idname); xmlNode* cnode = conf->findNode(xml->getFirstNode(), s, idname);
if( cnode == 0 ) if( cnode == 0 )
throw uniset::SystemError("(make_object<" + string(typeid(T).name()) + ">): Not found xmlnode <" + s + " name='" + idname + "' ... >"); throw uniset::SystemError("(make_object<" + string(typeid(T).name()) + ">): Not found xmlnode <" + s + " name='" + idname + "' ... >");
std::shared_ptr<T> obj = std::make_shared<T>(id, cnode, std::forward<_Args>(__args)...); std::shared_ptr<T> obj = std::make_shared<T>(id, cnode, std::forward<_Args>(__args)...);
if (obj == nullptr) if (obj == nullptr)
throw uniset::SystemError("(make_object<T> == nullptr" + string(typeid(T).name())); throw uniset::SystemError("(make_object<T> == nullptr" + string(typeid(T).name()));
return obj; return obj;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// версия с указанием начального xml-узла, с которого ведётся поиск xmlNode // версия с указанием начального xml-узла, с которого ведётся поиск xmlNode
// а ID берётся из поля name="" у найденного xmlnode. // а ID берётся из поля name="" у найденного xmlnode.
template<typename T, typename... _Args> template<typename T, typename... _Args>
std::shared_ptr<T> make_object_x( xmlNode* root, const std::string& secname, _Args&& ... __args ) std::shared_ptr<T> make_object_x( xmlNode* root, const std::string& secname, _Args&& ... __args )
{ {
auto conf = uniset::uniset_conf(); auto conf = uniset::uniset_conf();
auto xml = conf->getConfXML(); auto xml = conf->getConfXML();
xmlNode* cnode = conf->findNode(root, secname, ""); xmlNode* cnode = conf->findNode(root, secname, "");
if( cnode == 0 ) if( cnode == 0 )
throw uniset::SystemError("(make_object_x<" + string(typeid(T).name()) + ">): Not found xmlnode <" + secname + " ... >"); throw uniset::SystemError("(make_object_x<" + string(typeid(T).name()) + ">): Not found xmlnode <" + secname + " ... >");
string idname = conf->getProp(cnode, "name"); string idname = conf->getProp(cnode, "name");
uniset::ObjectId id = conf->getObjectID(idname); uniset::ObjectId id = conf->getObjectID(idname);
if( id == uniset::DefaultObjectId ) if( id == uniset::DefaultObjectId )
throw uniset::SystemError("(make_object_x<" + string(typeid(T).name()) + ">): Not found ID for '" + idname + "'"); throw uniset::SystemError("(make_object_x<" + string(typeid(T).name()) + ">): Not found ID for '" + idname + "'");
return std::make_shared<T>(id, cnode, std::forward<_Args>(__args)...); return std::make_shared<T>(id, cnode, std::forward<_Args>(__args)...);
}
// -----------------------------------------------------------------------------
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// "по задумке" позволяет не загромаждать код..
// T - тип создаваемого объекта
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// Использование
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object( M* m, const std::string& idname, const std::string& secname, _Args&& ... __args )
{
try
{
m->log()->info() << m->getName() << "(" << __FUNCTION__ << "): " << "create " << idname << "..." << std::endl;
auto o = uniset::make_object<T>(idname, secname, std::forward<_Args>(__args)...);
m->add(o);
m->logAgregator()->add(o->logAgregator());
return std::move(o);
} }
// ----------------------------------------------------------------------------- catch( const uniset::Exception& ex )
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// "по задумке" позволяет не загромаждать код..
// T - тип создаваемого объекта
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// Использование
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object( M* m, const std::string& idname, const std::string& secname, _Args&& ... __args )
{ {
try m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << idname << "): " << ex << std::endl;
{ throw;
m->log()->info() << m->getName() << "(" << __FUNCTION__ << "): " << "create " << idname << "..." << std::endl;
auto o = uniset::make_object<T>(idname, secname, std::forward<_Args>(__args)...);
m->add(o);
m->logAgregator()->add(o->logAgregator());
return std::move(o);
}
catch( const uniset::Exception& ex )
{
m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << idname << "): " << ex << std::endl;
throw;
}
} }
// ----------------------------------------------------------------------------- }
// Версия использующая make_object_x<> // -----------------------------------------------------------------------------
template<typename T, typename M, typename... _Args> // Версия использующая make_object_x<>
std::shared_ptr<T> make_child_object_x( M* m, xmlNode* root, const std::string& secname, _Args&& ... __args ) template<typename T, typename M, typename... _Args>
std::shared_ptr<T> make_child_object_x( M* m, xmlNode* root, const std::string& secname, _Args&& ... __args )
{
try
{ {
try auto o = uniset::make_object_x<T>(root, secname, std::forward<_Args>(__args)...);
{ m->add(o);
auto o = uniset::make_object_x<T>(root, secname, std::forward<_Args>(__args)...); m->logAgregator()->add(o->logAgregator());
m->add(o); return std::move(o);
m->logAgregator()->add(o->logAgregator());
return std::move(o);
}
catch( const uniset::Exception& ex )
{
m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << string(typeid(T).name()) << "): " << ex << std::endl;
throw;
}
} }
// ----------------------------------------------------------------------------------------- catch( const uniset::Exception& ex )
{
m->log()->crit() << m->getName() << "(" << __FUNCTION__ << "): " << "(create " << string(typeid(T).name()) << "): " << ex << std::endl;
throw;
}
}
// -----------------------------------------------------------------------------------------
} // endof namespace uniset } // endof namespace uniset
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
#endif // UHelpers_H_ #endif // UHelpers_H_
...@@ -47,70 +47,70 @@ ...@@ -47,70 +47,70 @@
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
namespace UHttp namespace UHttp
{ {
// текущая версия API // текущая версия API
const std::string UHTTP_API_VERSION="v01"; const std::string UHTTP_API_VERSION = "v01";
/*! интерфейс для объекта выдающего json-данные */ /*! интерфейс для объекта выдающего json-данные */
class IHttpRequest class IHttpRequest
{ {
public: public:
IHttpRequest(){} IHttpRequest() {}
virtual ~IHttpRequest(){} virtual ~IHttpRequest() {}
// throw SystemError // throw SystemError
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) = 0;
// не обязательная функция. // не обязательная функция.
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ); virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p );
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! интерфейс для обработки запросов к объектам */ /*! интерфейс для обработки запросов к объектам */
class IHttpRequestRegistry class IHttpRequestRegistry
{ {
public: public:
IHttpRequestRegistry(){} IHttpRequestRegistry() {}
virtual ~IHttpRequestRegistry(){} virtual ~IHttpRequestRegistry() {}
// throw SystemError, NameNotFound // throw SystemError, NameNotFound
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
// throw SystemError // throw SystemError
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class UHttpRequestHandler: class UHttpRequestHandler:
public Poco::Net::HTTPRequestHandler public Poco::Net::HTTPRequestHandler
{ {
public: public:
UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry ); UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry );
virtual void handleRequest( Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp ) override; virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override;
private: private:
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class UHttpRequestHandlerFactory: class UHttpRequestHandlerFactory:
public Poco::Net::HTTPRequestHandlerFactory public Poco::Net::HTTPRequestHandlerFactory
{ {
public: public:
UHttpRequestHandlerFactory( std::shared_ptr<IHttpRequestRegistry>& _registry ); UHttpRequestHandlerFactory( std::shared_ptr<IHttpRequestRegistry>& _registry );
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest & ) override; virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& ) override;
private: private:
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
}; };
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -31,33 +31,33 @@ ...@@ -31,33 +31,33 @@
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
namespace UHttp namespace UHttp
{ {
class UHttpServer class UHttpServer
{ {
public: public:
UHttpServer( std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& host, int port ); UHttpServer( std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& host, int port );
virtual ~UHttpServer(); virtual ~UHttpServer();
void start(); void start();
void stop(); void stop();
std::shared_ptr<DebugStream> log(); std::shared_ptr<DebugStream> log();
protected: protected:
UHttpServer(); UHttpServer();
private: private:
std::shared_ptr<DebugStream> mylog; std::shared_ptr<DebugStream> mylog;
Poco::Net::SocketAddress sa; Poco::Net::SocketAddress sa;
std::shared_ptr<Poco::Net::HTTPServer> http; std::shared_ptr<Poco::Net::HTTPServer> http;
std::shared_ptr<UHttpRequestHandlerFactory> reqFactory; std::shared_ptr<UHttpRequestHandlerFactory> reqFactory;
}; };
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // UHttpServer_H_ #endif // UHttpServer_H_
......
...@@ -95,7 +95,7 @@ class UInterface ...@@ -95,7 +95,7 @@ class UInterface
//! Заказ по списку //! Заказ по списку
uniset::IDSeq_var askSensorsSeq( const uniset::IDList& lst, UniversalIO::UIOCommand cmd, uniset::IDSeq_var askSensorsSeq( const uniset::IDList& lst, UniversalIO::UIOCommand cmd,
uniset::ObjectId backid = uniset::DefaultObjectId ); uniset::ObjectId backid = uniset::DefaultObjectId );
// ------------------------------------------------------ // ------------------------------------------------------
// установка неопределённого состояния // установка неопределённого состояния
...@@ -146,10 +146,10 @@ class UInterface ...@@ -146,10 +146,10 @@ class UInterface
//! Получить список датчиков //! Получить список датчиков
IOController_i::ShortMapSeq* getSensors( const uniset::ObjectId id, IOController_i::ShortMapSeq* getSensors( const uniset::ObjectId id,
const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
IOController_i::SensorInfoSeq* getSensorsMap( const uniset::ObjectId id, IOController_i::SensorInfoSeq* getSensorsMap( const uniset::ObjectId id,
const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
IONotifyController_i::ThresholdsListSeq* getThresholdsList( const uniset::ObjectId id, IONotifyController_i::ThresholdsListSeq* getThresholdsList( const uniset::ObjectId id,
const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); const uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
......
...@@ -11,27 +11,27 @@ namespace uniset ...@@ -11,27 +11,27 @@ namespace uniset
namespace UTCPCore namespace UTCPCore
{ {
bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ) noexcept; bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ) noexcept;
// ------------------------------------------- // -------------------------------------------
// author: https://gist.github.com/koblas/3364414 // author: https://gist.github.com/koblas/3364414
// ---------------------- // ----------------------
// for use with ev::io.. // for use with ev::io..
// Buffer class - allow for output buffering such that it can be written out into async pieces // Buffer class - allow for output buffering such that it can be written out into async pieces
struct Buffer struct Buffer
{ {
Buffer( const unsigned char* bytes, ssize_t nbytes ); Buffer( const unsigned char* bytes, ssize_t nbytes );
Buffer( const std::string& s ); Buffer( const std::string& s );
virtual ~Buffer(); virtual ~Buffer();
unsigned char* dpos() noexcept; unsigned char* dpos() noexcept;
ssize_t nbytes() noexcept; ssize_t nbytes() noexcept;
unsigned char* data = { 0 }; unsigned char* data = { 0 };
ssize_t len; ssize_t len;
ssize_t pos; ssize_t pos;
}; };
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
......
...@@ -56,7 +56,7 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr; ...@@ -56,7 +56,7 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
class UniSetActivator: class UniSetActivator:
public UniSetManager public UniSetManager
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
,public uniset::UHttp::IHttpRequestRegistry , public uniset::UHttp::IHttpRequestRegistry
#endif #endif
{ {
public: public:
......
...@@ -134,7 +134,7 @@ class UniSetManager: ...@@ -134,7 +134,7 @@ class UniSetManager:
const std::shared_ptr<UniSetObject> deepFindObject( const std::string& name ); const std::shared_ptr<UniSetObject> deepFindObject( const std::string& name );
// рекурсивное наполнение списка объектов // рекурсивное наполнение списка объектов
void getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>>& vec, size_t lim=1000 ); void getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>>& vec, size_t lim = 1000 );
typedef UniSetManagerList::iterator MListIterator; typedef UniSetManagerList::iterator MListIterator;
......
...@@ -75,7 +75,7 @@ class UniSetObject: ...@@ -75,7 +75,7 @@ class UniSetObject:
public POA_UniSetObject_i, public POA_UniSetObject_i,
public LT_Object public LT_Object
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
,public uniset::UHttp::IHttpRequest , public uniset::UHttp::IHttpRequest
#endif #endif
{ {
public: public:
......
...@@ -38,7 +38,7 @@ class ModbusClient ...@@ -38,7 +38,7 @@ class ModbusClient
\param count - сколько регистров читать \param count - сколько регистров читать
*/ */
ModbusRTU::ReadInputStatusRetMessage read02( ModbusRTU::ModbusAddr addr, ModbusRTU::ReadInputStatusRetMessage read02( ModbusRTU::ModbusAddr addr,
ModbusRTU::ModbusData start, ModbusRTU::ModbusData count ) ModbusRTU::ModbusData start, ModbusRTU::ModbusData count )
throw(ModbusRTU::mbException); throw(ModbusRTU::mbException);
...@@ -66,7 +66,7 @@ class ModbusClient ...@@ -66,7 +66,7 @@ class ModbusClient
\param cmd - команда ON | OFF \param cmd - команда ON | OFF
*/ */
ModbusRTU::ForceSingleCoilRetMessage write05( ModbusRTU::ModbusAddr addr, ModbusRTU::ForceSingleCoilRetMessage write05( ModbusRTU::ModbusAddr addr,
ModbusRTU::ModbusData reg, bool cmd ) ModbusRTU::ModbusData reg, bool cmd )
throw(ModbusRTU::mbException); throw(ModbusRTU::mbException);
/*! Запись одного регистра (0x06) /*! Запись одного регистра (0x06)
...@@ -75,7 +75,7 @@ class ModbusClient ...@@ -75,7 +75,7 @@ class ModbusClient
\param data - данные \param data - данные
*/ */
ModbusRTU::WriteSingleOutputRetMessage write06( ModbusRTU::ModbusAddr addr, ModbusRTU::WriteSingleOutputRetMessage write06( ModbusRTU::ModbusAddr addr,
ModbusRTU::ModbusData reg, ModbusRTU::ModbusData data ) ModbusRTU::ModbusData reg, ModbusRTU::ModbusData data )
throw(ModbusRTU::mbException); throw(ModbusRTU::mbException);
/*! Запись группы выходов (0x0F) */ /*! Запись группы выходов (0x0F) */
...@@ -110,9 +110,9 @@ class ModbusClient ...@@ -110,9 +110,9 @@ class ModbusClient
century - столетие [19-20] century - столетие [19-20]
*/ */
ModbusRTU::SetDateTimeRetMessage setDateTime( ModbusRTU::ModbusAddr addr, ModbusRTU::SetDateTimeRetMessage setDateTime( ModbusRTU::ModbusAddr addr,
ModbusRTU::ModbusByte hour, ModbusRTU::ModbusByte min, ModbusRTU::ModbusByte sec, ModbusRTU::ModbusByte hour, ModbusRTU::ModbusByte min, ModbusRTU::ModbusByte sec,
ModbusRTU::ModbusByte day, ModbusRTU::ModbusByte mon, ModbusRTU::ModbusByte year, ModbusRTU::ModbusByte day, ModbusRTU::ModbusByte mon, ModbusRTU::ModbusByte year,
ModbusRTU::ModbusByte century ) ModbusRTU::ModbusByte century )
throw(ModbusRTU::mbException); throw(ModbusRTU::mbException);
......
...@@ -13,32 +13,32 @@ class ModbusRTUMaster; ...@@ -13,32 +13,32 @@ class ModbusRTUMaster;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace ModbusHelpers namespace ModbusHelpers
{ {
ModbusRTU::ModbusAddr autodetectSlave( ModbusRTUMaster* m, ModbusRTU::ModbusAddr autodetectSlave( ModbusRTUMaster* m,
ModbusRTU::ModbusAddr beg = 0, ModbusRTU::ModbusAddr beg = 0,
ModbusRTU::ModbusAddr end = 255, ModbusRTU::ModbusAddr end = 255,
ModbusRTU::ModbusData reg = 0, ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut(); ); // throw uniset::TimeOut();
ModbusRTU::ModbusAddr autodetectSlave( std::string dev, ModbusRTU::ModbusAddr autodetectSlave( std::string dev,
ComPort::Speed s, int tout = 1000, ComPort::Speed s, int tout = 1000,
ModbusRTU::ModbusAddr beg = 0, ModbusRTU::ModbusAddr beg = 0,
ModbusRTU::ModbusAddr end = 255, ModbusRTU::ModbusAddr end = 255,
ModbusRTU::ModbusData reg = 0, ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut(); ); // throw uniset::TimeOut();
ComPort::Speed autodetectSpeed( ModbusRTUMaster* m, ModbusRTU::ModbusAddr slave, ComPort::Speed autodetectSpeed( ModbusRTUMaster* m, ModbusRTU::ModbusAddr slave,
ModbusRTU::ModbusData reg = 0, ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut(); ); // throw uniset::TimeOut();
ComPort::Speed autodetectSpeed( std::string dev, ComPort::Speed autodetectSpeed( std::string dev,
ModbusRTU::ModbusAddr slave, ModbusRTU::ModbusAddr slave,
int timeout_msec = 1000, int timeout_msec = 1000,
ModbusRTU::ModbusData reg = 0, ModbusRTU::ModbusData reg = 0,
ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters ModbusRTU::SlaveFunctionCode fn = ModbusRTU::fnReadInputRegisters
); // throw uniset::TimeOut(); ); // throw uniset::TimeOut();
} // end of namespace ModbusHelpers } // end of namespace ModbusHelpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
......
...@@ -10,51 +10,51 @@ namespace uniset ...@@ -10,51 +10,51 @@ namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace ModbusRTU namespace ModbusRTU
{ {
/*! Ошибки обмена /*! Ошибки обмена
все ошибки > InternalErrorCode в сеть не посылаются... все ошибки > InternalErrorCode в сеть не посылаются...
*/ */
enum mbErrCode enum mbErrCode
{ {
erNoError = 0, /*!< нет ошибок */ erNoError = 0, /*!< нет ошибок */
erUnExpectedPacketType = 1, /*!< Неожидаемый тип пакета (ошибка кода функции) */ erUnExpectedPacketType = 1, /*!< Неожидаемый тип пакета (ошибка кода функции) */
erBadDataAddress = 2, /*!< адрес запрещен к опросу или не существует */ erBadDataAddress = 2, /*!< адрес запрещен к опросу или не существует */
erBadDataValue = 3, /*!< недопустимое значение */ erBadDataValue = 3, /*!< недопустимое значение */
erHardwareError = 4, /*!< ошибка оборудования */ erHardwareError = 4, /*!< ошибка оборудования */
erAnknowledge = 5, /*!< запрос принят в исполнению, но ещё не выполнен */ erAnknowledge = 5, /*!< запрос принят в исполнению, но ещё не выполнен */
erSlaveBusy = 6, /*!< контроллер занят длительной операцией (повторить запрос позже) */ erSlaveBusy = 6, /*!< контроллер занят длительной операцией (повторить запрос позже) */
erOperationFailed = 7, /*!< запрашиваемая функция запрещена конфигурацией контроллера */ erOperationFailed = 7, /*!< запрашиваемая функция запрещена конфигурацией контроллера */
erMemoryParityError = 8, /*!< ошибка паритета при чтении памяти */ erMemoryParityError = 8, /*!< ошибка паритета при чтении памяти */
erInternalErrorCode = 10, /*!< коды ошибок используемые для внутренней работы */ erInternalErrorCode = 10, /*!< коды ошибок используемые для внутренней работы */
erInvalidFormat = 11, /*!< неправильный формат */ erInvalidFormat = 11, /*!< неправильный формат */
erBadCheckSum = 12, /*!< У пакета не сошлась контрольная сумма */ erBadCheckSum = 12, /*!< У пакета не сошлась контрольная сумма */
erBadReplyNodeAddress = 13, /*!< Ответ на запрос адресован не мне или от станции,которую не спрашивали */ erBadReplyNodeAddress = 13, /*!< Ответ на запрос адресован не мне или от станции,которую не спрашивали */
erTimeOut = 14, /*!< Тайм-аут при приеме ответа */ erTimeOut = 14, /*!< Тайм-аут при приеме ответа */
erPacketTooLong = 15, /*!< пакет длинее буфера приема */ erPacketTooLong = 15, /*!< пакет длинее буфера приема */
erSessionClosed = 16 /*!< соединение закрыто */ erSessionClosed = 16 /*!< соединение закрыто */
}; };
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
std::string mbErr2Str( mbErrCode e ); std::string mbErr2Str( mbErrCode e );
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
class mbException: class mbException:
public uniset::Exception public uniset::Exception
{ {
public: public:
mbException(): mbException():
uniset::Exception("mbException"), err(ModbusRTU::erNoError) {} uniset::Exception("mbException"), err(ModbusRTU::erNoError) {}
mbException( ModbusRTU::mbErrCode err ): mbException( ModbusRTU::mbErrCode err ):
uniset::Exception(mbErr2Str(err)), err(err) {} uniset::Exception(mbErr2Str(err)), err(err) {}
ModbusRTU::mbErrCode err; ModbusRTU::mbErrCode err;
friend std::ostream& operator<<(std::ostream& os, mbException& ex ) friend std::ostream& operator<<(std::ostream& os, mbException& ex )
{ {
return os << "(" << ex.err << ") " << mbErr2Str(ex.err); return os << "(" << ex.err << ") " << mbErr2Str(ex.err);
} }
}; };
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
} // end of namespace ModbusRTU } // end of namespace ModbusRTU
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of namespace uniset } // end of namespace uniset
......
...@@ -34,46 +34,46 @@ class ModbusRTUSlaveSlot: ...@@ -34,46 +34,46 @@ class ModbusRTUSlaveSlot:
protected: protected:
virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
private: private:
}; };
......
...@@ -15,15 +15,15 @@ ...@@ -15,15 +15,15 @@
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace std namespace std
{ {
template<> template<>
class hash<uniset::ModbusRTU::mbErrCode> class hash<uniset::ModbusRTU::mbErrCode>
{ {
public: public:
size_t operator()(const uniset::ModbusRTU::mbErrCode& e) const size_t operator()(const uniset::ModbusRTU::mbErrCode& e) const
{ {
return std::hash<size_t>()(e); return std::hash<size_t>()(e);
} }
}; };
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
...@@ -128,8 +128,8 @@ class ModbusServer ...@@ -128,8 +128,8 @@ class ModbusServer
Основана на использовании gettimeofday и settimeofday. Основана на использовании gettimeofday и settimeofday.
*/ */
static ModbusRTU::mbErrCode replySetDateTime( ModbusRTU::SetDateTimeMessage& query, static ModbusRTU::mbErrCode replySetDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply, ModbusRTU::SetDateTimeRetMessage& reply,
std::shared_ptr<DebugStream> dlog = nullptr ); std::shared_ptr<DebugStream> dlog = nullptr );
/*! Вспомогательная функция реализующая обработку передачи файла /*! Вспомогательная функция реализующая обработку передачи файла
...@@ -138,9 +138,9 @@ class ModbusServer ...@@ -138,9 +138,9 @@ class ModbusServer
\param reply - ответ \param reply - ответ
*/ */
static ModbusRTU::mbErrCode replyFileTransfer( const std::string& fname, static ModbusRTU::mbErrCode replyFileTransfer( const std::string& fname,
ModbusRTU::FileTransferMessage& query, ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply, ModbusRTU::FileTransferRetMessage& reply,
std::shared_ptr<DebugStream> dlog = nullptr ); std::shared_ptr<DebugStream> dlog = nullptr );
virtual void cleanupChannel() {} virtual void cleanupChannel() {}
virtual void terminate() {} virtual void terminate() {}
...@@ -174,14 +174,14 @@ class ModbusServer ...@@ -174,14 +174,14 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ) = 0; ModbusRTU::ReadCoilRetMessage& reply ) = 0;
/*! Обработка запроса на чтение данных (0x02). /*! Обработка запроса на чтение данных (0x02).
\param query - запрос \param query - запрос
\param reply - ответ. Заполняется в обработчике. \param reply - ответ. Заполняется в обработчике.
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ) = 0; ModbusRTU::ReadInputStatusRetMessage& reply ) = 0;
/*! Обработка запроса на чтение данных (0x03). /*! Обработка запроса на чтение данных (0x03).
\param query - запрос \param query - запрос
...@@ -189,7 +189,7 @@ class ModbusServer ...@@ -189,7 +189,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ) = 0; ModbusRTU::ReadOutputRetMessage& reply ) = 0;
/*! Обработка запроса на чтение данных (0x04). /*! Обработка запроса на чтение данных (0x04).
\param query - запрос \param query - запрос
...@@ -197,7 +197,7 @@ class ModbusServer ...@@ -197,7 +197,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ) = 0; ModbusRTU::ReadInputRetMessage& reply ) = 0;
/*! Обработка запроса на запись данных (0x05). /*! Обработка запроса на запись данных (0x05).
\param query - запрос \param query - запрос
...@@ -205,7 +205,7 @@ class ModbusServer ...@@ -205,7 +205,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ) = 0; ModbusRTU::ForceSingleCoilRetMessage& reply ) = 0;
/*! Обработка запроса на запись данных (0x06). /*! Обработка запроса на запись данных (0x06).
...@@ -222,7 +222,7 @@ class ModbusServer ...@@ -222,7 +222,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ) = 0; ModbusRTU::ForceCoilsRetMessage& reply ) = 0;
/*! Обработка запроса на запись данных (0x10). /*! Обработка запроса на запись данных (0x10).
\param query - запрос \param query - запрос
...@@ -239,7 +239,7 @@ class ModbusServer ...@@ -239,7 +239,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ) = 0; ModbusRTU::DiagnosticRetMessage& reply ) = 0;
/*! Обработка запроса 43(0x2B). /*! Обработка запроса 43(0x2B).
\param query - запрос \param query - запрос
...@@ -256,7 +256,7 @@ class ModbusServer ...@@ -256,7 +256,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ) = 0; ModbusRTU::JournalCommandRetMessage& reply ) = 0;
/*! Обработка запроса по установке даты и времени (0x50) /*! Обработка запроса по установке даты и времени (0x50)
...@@ -265,7 +265,7 @@ class ModbusServer ...@@ -265,7 +265,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ) = 0; ModbusRTU::SetDateTimeRetMessage& reply ) = 0;
/*! Вызов удалённого сервиса (0x53) /*! Вызов удалённого сервиса (0x53)
...@@ -274,7 +274,7 @@ class ModbusServer ...@@ -274,7 +274,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ) = 0; ModbusRTU::RemoteServiceRetMessage& reply ) = 0;
/*! Передача файла (0x66) /*! Передача файла (0x66)
...@@ -283,7 +283,7 @@ class ModbusServer ...@@ -283,7 +283,7 @@ class ModbusServer
\return Результат обработки \return Результат обработки
*/ */
virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ) = 0; ModbusRTU::FileTransferRetMessage& reply ) = 0;
/*! get next data block from channel or recv buffer /*! get next data block from channel or recv buffer
\param begin - get from position \param begin - get from position
......
...@@ -12,17 +12,17 @@ namespace uniset ...@@ -12,17 +12,17 @@ namespace uniset
/*! ModbusTCP core functions */ /*! ModbusTCP core functions */
namespace ModbusTCPCore namespace ModbusTCPCore
{ {
// Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed // Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed
// t - msec (сколько ждать) // t - msec (сколько ждать)
size_t readNextData(UTCPStream* tcp, std::queue<unsigned char>& qrecv, size_t max = 100); size_t readNextData(UTCPStream* tcp, std::queue<unsigned char>& qrecv, size_t max = 100);
size_t getNextData( UTCPStream* tcp, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len ); size_t getNextData( UTCPStream* tcp, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len );
ModbusRTU::mbErrCode sendData(UTCPStream* tcp, unsigned char* buf, size_t len ); ModbusRTU::mbErrCode sendData(UTCPStream* tcp, unsigned char* buf, size_t len );
// работа напрямую с сокетом // работа напрямую с сокетом
size_t readDataFD(int fd, std::queue<unsigned char>& qrecv, size_t max = 100, size_t attempts = 1 ); size_t readDataFD(int fd, std::queue<unsigned char>& qrecv, size_t max = 100, size_t attempts = 1 );
size_t getDataFD( int fd, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len, size_t attempts = 1 ); size_t getDataFD( int fd, std::queue<unsigned char>& qrecv, unsigned char* buf, size_t len, size_t attempts = 1 );
ModbusRTU::mbErrCode sendDataFD( int fd, unsigned char* buf, size_t len ); ModbusRTU::mbErrCode sendDataFD( int fd, unsigned char* buf, size_t len );
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of namespace uniset } // end of namespace uniset
......
...@@ -23,46 +23,46 @@ class ModbusTCPServerSlot: ...@@ -23,46 +23,46 @@ class ModbusTCPServerSlot:
protected: protected:
virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
private: private:
......
...@@ -80,46 +80,46 @@ class ModbusTCPSession: ...@@ -80,46 +80,46 @@ class ModbusTCPSession:
virtual ModbusRTU::mbErrCode post_send_request(ModbusRTU::ModbusMessage& request ) override; virtual ModbusRTU::mbErrCode post_send_request(ModbusRTU::ModbusMessage& request ) override;
virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query, virtual ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply ); ModbusRTU::ReadCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query, virtual ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply ); ModbusRTU::ReadInputStatusRetMessage& reply );
virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query, virtual ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply ); ModbusRTU::ReadOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query, virtual ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply ); ModbusRTU::ReadInputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query, virtual ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply ); ModbusRTU::ForceSingleCoilRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply ); ModbusRTU::WriteSingleOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query, virtual ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply ); ModbusRTU::ForceCoilsRetMessage& reply );
virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query, virtual ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply ); ModbusRTU::WriteOutputRetMessage& reply );
virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query, virtual ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply ); ModbusRTU::DiagnosticRetMessage& reply );
virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query, virtual ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ); ModbusRTU::MEIMessageRetRDI& reply );
virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query, virtual ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply ); ModbusRTU::JournalCommandRetMessage& reply );
virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query, virtual ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply ); ModbusRTU::SetDateTimeRetMessage& reply );
virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query, virtual ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply ); ModbusRTU::RemoteServiceRetMessage& reply );
virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query, virtual ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply ); ModbusRTU::FileTransferRetMessage& reply );
private: private:
std::queue<unsigned char> qrecv; std::queue<unsigned char> qrecv;
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -64,13 +64,14 @@ long pyUInterface::getValue( long id )throw(UException) ...@@ -64,13 +64,14 @@ long pyUInterface::getValue( long id )throw(UException)
using namespace uniset; using namespace uniset;
UniversalIO::IOType t = conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
if( t == UniversalIO::UnknownIOType ) if( t == UniversalIO::UnknownIOType )
{ {
ostringstream e; ostringstream e;
e << "(getValue): Unknown iotype for id=" << id; e << "(getValue): Unknown iotype for id=" << id;
throw UException(e.str()); throw UException(e.str());
} }
try try
{ {
return uInterface->getValue(id); return uInterface->getValue(id);
...@@ -99,6 +100,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException) ...@@ -99,6 +100,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
using namespace uniset; using namespace uniset;
UniversalIO::IOType t = conf->getIOType(id); UniversalIO::IOType t = conf->getIOType(id);
if( t == UniversalIO::UnknownIOType ) if( t == UniversalIO::UnknownIOType )
{ {
ostringstream e; ostringstream e;
......
...@@ -23,22 +23,22 @@ ...@@ -23,22 +23,22 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace pyUInterface namespace pyUInterface
{ {
void uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException); void uniset_init_params( UTypes::Params* p, const std::string& xmlfile )throw(UException);
void uniset_init( int argc, char** argv, const std::string& xmlfile )throw(UException); void uniset_init( int argc, char** argv, const std::string& xmlfile )throw(UException);
void uniset_activate_objects() throw(UException); void uniset_activate_objects() throw(UException);
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
long getValue( long id )throw(UException); long getValue( long id )throw(UException);
void setValue( long id, long val, long supplier = UTypes::DefaultSupplerID )throw(UException); void setValue( long id, long val, long supplier = UTypes::DefaultSupplerID )throw(UException);
long getSensorID( const std::string& name ); long getSensorID( const std::string& name );
long getObjectID( const std::string& name ); long getObjectID( const std::string& name );
std::string getShortName( long id ); std::string getShortName( long id );
std::string getName( long id ); std::string getName( long id );
std::string getTextName( long id ); std::string getTextName( long id );
std::string getConfFileName(); std::string getConfFileName();
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#endif #endif
......
...@@ -135,7 +135,7 @@ UTypes::ShortIOInfo UConnector::getTimeChange( long id, long node ) ...@@ -135,7 +135,7 @@ UTypes::ShortIOInfo UConnector::getTimeChange( long id, long node )
try try
{ {
IOController_i::ShortIOInfo i = ui->getTimeChange(id,node); IOController_i::ShortIOInfo i = ui->getTimeChange(id, node);
return toUTypes(i); return toUTypes(i);
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
...@@ -198,7 +198,7 @@ throw(UException) ...@@ -198,7 +198,7 @@ throw(UException)
try try
{ {
return ui->getObjectInfo(id,params,node); return ui->getObjectInfo(id, params, node);
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
struct UException struct UException
{ {
UException():err("UException") {} UException(): err("UException") {}
explicit UException( const std::string& e ): err(e) {} explicit UException( const std::string& e ): err(e) {}
explicit UException( const char* e ): err( std::string(e)) {} explicit UException( const char* e ): err( std::string(e)) {}
~UException() {} ~UException() {}
......
...@@ -60,7 +60,7 @@ class UProxyObject_impl: ...@@ -60,7 +60,7 @@ class UProxyObject_impl:
}; };
std::mutex mutexSMap; std::mutex mutexSMap;
std::unordered_map<uniset::ObjectId,SInfo> smap; std::unordered_map<uniset::ObjectId, SInfo> smap;
bool askOK = { false }; bool askOK = { false };
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -72,6 +72,7 @@ UProxyObject::UProxyObject() throw(UException) ...@@ -72,6 +72,7 @@ UProxyObject::UProxyObject() throw(UException)
UProxyObject::UProxyObject( const std::string& name ) throw( UException ) UProxyObject::UProxyObject( const std::string& name ) throw( UException )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
if ( !conf ) if ( !conf )
{ {
std::ostringstream err; std::ostringstream err;
...@@ -117,7 +118,7 @@ long UProxyObject::getValue( long id ) throw(UException) ...@@ -117,7 +118,7 @@ long UProxyObject::getValue( long id ) throw(UException)
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void UProxyObject::setValue( long id, long val ) throw(UException) void UProxyObject::setValue( long id, long val ) throw(UException)
{ {
uobj->impl_setValue(id,val); uobj->impl_setValue(id, val);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
bool UProxyObject::askIsOK() bool UProxyObject::askIsOK()
...@@ -160,7 +161,7 @@ void UProxyObject::addToAsk( long id ) throw(UException) ...@@ -160,7 +161,7 @@ void UProxyObject::addToAsk( long id ) throw(UException)
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
UProxyObject_impl::UProxyObject_impl( ObjectId id ): UProxyObject_impl::UProxyObject_impl( ObjectId id ):
UObject_SK(id,nullptr) UObject_SK(id, nullptr)
{ {
} }
...@@ -179,6 +180,7 @@ void UProxyObject_impl::impl_addToAsk( ObjectId id ) throw( UException ) ...@@ -179,6 +180,7 @@ void UProxyObject_impl::impl_addToAsk( ObjectId id ) throw( UException )
i.si.node = conf->getLocalNode(); i.si.node = conf->getLocalNode();
auto inf = conf->oind->getObjectInfo(id); auto inf = conf->oind->getObjectInfo(id);
if( inf && inf->data ) if( inf && inf->data )
{ {
UniXML::iterator it( (xmlNode*)(inf->data) ); UniXML::iterator it( (xmlNode*)(inf->data) );
...@@ -193,6 +195,7 @@ long UProxyObject_impl::impl_getValue( long id ) throw(UException) ...@@ -193,6 +195,7 @@ long UProxyObject_impl::impl_getValue( long id ) throw(UException)
{ {
std::unique_lock<std::mutex> lk(mutexSMap); std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(id); auto i = smap.find(id);
if( i == smap.end() ) if( i == smap.end() )
{ {
std::ostringstream err; std::ostringstream err;
...@@ -207,6 +210,7 @@ float UProxyObject_impl::impl_getFloatValue( long id ) throw(UException) ...@@ -207,6 +210,7 @@ float UProxyObject_impl::impl_getFloatValue( long id ) throw(UException)
{ {
std::unique_lock<std::mutex> lk(mutexSMap); std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(id); auto i = smap.find(id);
if( i == smap.end() ) if( i == smap.end() )
{ {
std::ostringstream err; std::ostringstream err;
...@@ -227,7 +231,7 @@ void UProxyObject_impl::impl_setValue( long id, long val ) throw(UException) ...@@ -227,7 +231,7 @@ void UProxyObject_impl::impl_setValue( long id, long val ) throw(UException)
{ {
try try
{ {
UObject_SK::setValue(id,val); UObject_SK::setValue(id, val);
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
...@@ -247,11 +251,12 @@ bool UProxyObject_impl::impl_updateValues() ...@@ -247,11 +251,12 @@ bool UProxyObject_impl::impl_updateValues()
{ {
std::unique_lock<std::mutex> lk(mutexSMap); std::unique_lock<std::mutex> lk(mutexSMap);
bool ret = true; bool ret = true;
for( auto&& i: smap )
for( auto && i : smap )
{ {
try try
{ {
i.second.value = ui->getValue(i.second.si.id,i.second.si.node); i.second.value = ui->getValue(i.second.si.id, i.second.si.node);
i.second.fvalue = (float)i.second.value / pow(10.0, i.second.precision); i.second.fvalue = (float)i.second.value / pow(10.0, i.second.precision);
} }
catch( std::exception& ex ) catch( std::exception& ex )
...@@ -270,18 +275,19 @@ bool UProxyObject_impl::impl_smIsOK() ...@@ -270,18 +275,19 @@ bool UProxyObject_impl::impl_smIsOK()
// проверяем по первому датчику // проверяем по первому датчику
auto s = smap.begin(); auto s = smap.begin();
return ui->isExist(s->second.si.id,s->second.si.node); return ui->isExist(s->second.si.id, s->second.si.node);
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void UProxyObject_impl::askSensors( UniversalIO::UIOCommand cmd ) void UProxyObject_impl::askSensors( UniversalIO::UIOCommand cmd )
{ {
std::unique_lock<std::mutex> lk(mutexSMap); std::unique_lock<std::mutex> lk(mutexSMap);
askOK = true; askOK = true;
for( const auto& i: smap )
for( const auto& i : smap )
{ {
try try
{ {
ui->askRemoteSensor(i.second.si.id,cmd,i.second.si.node, getId()); ui->askRemoteSensor(i.second.si.id, cmd, i.second.si.node, getId());
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
...@@ -295,6 +301,7 @@ void UProxyObject_impl::sensorInfo( const SensorMessage* sm ) ...@@ -295,6 +301,7 @@ void UProxyObject_impl::sensorInfo( const SensorMessage* sm )
{ {
std::unique_lock<std::mutex> lk(mutexSMap); std::unique_lock<std::mutex> lk(mutexSMap);
auto i = smap.find(sm->id); auto i = smap.find(sm->id);
if( i != smap.end() ) if( i != smap.end() )
{ {
i->second.value = sm->value; i->second.value = sm->value;
......
...@@ -23,56 +23,56 @@ ...@@ -23,56 +23,56 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
namespace UTypes namespace UTypes
{ {
const long DefaultID = uniset::DefaultObjectId; const long DefaultID = uniset::DefaultObjectId;
const long DefaultSupplerID = uniset::AdminID; const long DefaultSupplerID = uniset::AdminID;
struct Params struct Params
{
static const int max = 20;
Params(): argc(0)
{ {
static const int max = 20; memset(argv, 0, sizeof(argv));
}
Params(): argc(0) bool add( char* s )
{
if( argc < Params::max )
{ {
memset(argv, 0, sizeof(argv)); argv[argc++] = uniset::uni_strdup(s);
return true;
} }
bool add( char* s ) return false;
{ }
if( argc < Params::max )
{
argv[argc++] = uniset::uni_strdup(s);
return true;
}
return false;
}
bool add_str( const std::string s ) bool add_str( const std::string s )
{
if( argc < Params::max )
{ {
if( argc < Params::max ) argv[argc++] = uniset::uni_strdup(s);
{ return true;
argv[argc++] = uniset::uni_strdup(s);
return true;
}
return false;
} }
int argc; return false;
char* argv[max]; }
static Params inst() int argc;
{ char* argv[max];
return Params();
}
};
struct ShortIOInfo static Params inst()
{ {
long value; return Params();
unsigned long tv_sec; }
unsigned long tv_nsec; };
long supplier;
}; struct ShortIOInfo
{
long value;
unsigned long tv_sec;
unsigned long tv_nsec;
long supplier;
};
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
......
...@@ -71,9 +71,9 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -71,9 +71,9 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
// example: http://host:port/api/version/ObjectName // example: http://host:port/api/version/ObjectName
if( seg.size() < 3 if( seg.size() < 3
|| seg[0] != "api" || seg[0] != "api"
|| seg[1] != UHTTP_API_VERSION || seg[1] != UHTTP_API_VERSION
|| seg[2].empty() ) || seg[2].empty() )
{ {
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST); resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp.setContentType("text/json"); resp.setContentType("text/json");
...@@ -99,12 +99,13 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -99,12 +99,13 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
if( objectName == "help" ) if( objectName == "help" )
{ {
nlohmann::json jdata; nlohmann::json jdata;
jdata["help"] = { jdata["help"] =
{"help", {"desc", "this help"}}, {
{"list", {"desc", "list of objects"}}, {"help", {"desc", "this help"}},
{"ObjectName", {"desc", "'ObjectName' information"}}, {"list", {"desc", "list of objects"}},
{"ObjectName/help", {"desc", "help for ObjectName"}}, {"ObjectName", {"desc", "'ObjectName' information"}},
{"apidocs", {"desc", "https://github.com/Etersoft/uniset2"}} {"ObjectName/help", {"desc", "help for ObjectName"}},
{"apidocs", {"desc", "https://github.com/Etersoft/uniset2"}}
}; };
out << jdata.dump(); out << jdata.dump();
......
...@@ -26,45 +26,45 @@ using namespace UHttp; ...@@ -26,45 +26,45 @@ using namespace UHttp;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ): UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host,_port) sa(_host, _port)
{ {
try try
{ {
mylog = std::make_shared<DebugStream>(); mylog = std::make_shared<DebugStream>();
/*! \FIXME: доделать конфигурирование параметров */ /*! \FIXME: доделать конфигурирование параметров */
HTTPServerParams* httpParams = new HTTPServerParams; HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100); httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1); httpParams->setMaxThreads(1);
reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier); reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier);
http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams ); http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams );
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
std::stringstream err; std::stringstream err;
err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what(); err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what();
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl; mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::~UHttpServer() UHttpServer::~UHttpServer()
{ {
if( http ) if( http )
http->stop(); http->stop();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpServer::start() void UHttpServer::start()
{ {
http->start(); http->start();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpServer::stop() void UHttpServer::stop()
{ {
http->stop(); http->stop();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::UHttpServer() UHttpServer::UHttpServer()
...@@ -73,7 +73,7 @@ UHttpServer::UHttpServer() ...@@ -73,7 +73,7 @@ UHttpServer::UHttpServer()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log() std::shared_ptr<DebugStream> UHttpServer::log()
{ {
return mylog; return mylog;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
...@@ -58,7 +58,7 @@ int ModbusClient::setAfterSendPause( timeout_t msec ) ...@@ -58,7 +58,7 @@ int ModbusClient::setAfterSendPause( timeout_t msec )
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
ReadCoilRetMessage ModbusClient::read01( ModbusAddr addr, ReadCoilRetMessage ModbusClient::read01( ModbusAddr addr,
ModbusData start, ModbusData count ) ModbusData start, ModbusData count )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
ReadCoilMessage msg(addr, start, count); ReadCoilMessage msg(addr, start, count);
...@@ -72,7 +72,7 @@ throw(ModbusRTU::mbException) ...@@ -72,7 +72,7 @@ throw(ModbusRTU::mbException)
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
ReadInputStatusRetMessage ModbusClient::read02( ModbusAddr addr, ReadInputStatusRetMessage ModbusClient::read02( ModbusAddr addr,
ModbusData start, ModbusData count ) ModbusData start, ModbusData count )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
ReadInputStatusMessage msg(addr, start, count); ReadInputStatusMessage msg(addr, start, count);
...@@ -87,7 +87,7 @@ throw(ModbusRTU::mbException) ...@@ -87,7 +87,7 @@ throw(ModbusRTU::mbException)
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
ReadOutputRetMessage ModbusClient::read03( ModbusAddr addr, ReadOutputRetMessage ModbusClient::read03( ModbusAddr addr,
ModbusData start, ModbusData count ) ModbusData start, ModbusData count )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
ReadOutputMessage msg(addr, start, count); ReadOutputMessage msg(addr, start, count);
...@@ -102,7 +102,7 @@ throw(ModbusRTU::mbException) ...@@ -102,7 +102,7 @@ throw(ModbusRTU::mbException)
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
ReadInputRetMessage ModbusClient::read04( ModbusAddr addr, ReadInputRetMessage ModbusClient::read04( ModbusAddr addr,
ModbusData start, ModbusData count ) ModbusData start, ModbusData count )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
ReadInputMessage msg(addr, start, count); ReadInputMessage msg(addr, start, count);
...@@ -116,7 +116,7 @@ throw(ModbusRTU::mbException) ...@@ -116,7 +116,7 @@ throw(ModbusRTU::mbException)
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
ForceSingleCoilRetMessage ModbusClient::write05( ModbusAddr addr, ForceSingleCoilRetMessage ModbusClient::write05( ModbusAddr addr,
ModbusData start, bool cmd ) ModbusData start, bool cmd )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
ForceSingleCoilMessage msg(addr, start, cmd); ForceSingleCoilMessage msg(addr, start, cmd);
...@@ -172,8 +172,8 @@ throw(ModbusRTU::mbException) ...@@ -172,8 +172,8 @@ throw(ModbusRTU::mbException)
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
DiagnosticRetMessage ModbusClient::diag08( ModbusAddr addr, DiagnosticRetMessage ModbusClient::diag08( ModbusAddr addr,
DiagnosticsSubFunction subfunc, DiagnosticsSubFunction subfunc,
ModbusRTU::ModbusData dat ) ModbusRTU::ModbusData dat )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
DiagnosticMessage msg(addr, subfunc, dat); DiagnosticMessage msg(addr, subfunc, dat);
...@@ -202,8 +202,8 @@ throw(ModbusRTU::mbException) ...@@ -202,8 +202,8 @@ throw(ModbusRTU::mbException)
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
SetDateTimeRetMessage ModbusClient::setDateTime( ModbusAddr addr, ModbusByte hour, ModbusByte min, ModbusByte sec, SetDateTimeRetMessage ModbusClient::setDateTime( ModbusAddr addr, ModbusByte hour, ModbusByte min, ModbusByte sec,
ModbusByte day, ModbusByte mon, ModbusByte year, ModbusByte day, ModbusByte mon, ModbusByte year,
ModbusByte century ) ModbusByte century )
throw(ModbusRTU::mbException) throw(ModbusRTU::mbException)
{ {
SetDateTimeMessage msg(addr); SetDateTimeMessage msg(addr);
......
...@@ -38,9 +38,9 @@ static ComPort::Speed checkSpeed[] = ...@@ -38,9 +38,9 @@ static ComPort::Speed checkSpeed[] =
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusAddr ModbusHelpers::autodetectSlave( ModbusRTUMaster* m, ModbusAddr ModbusHelpers::autodetectSlave( ModbusRTUMaster* m,
ModbusAddr beg, ModbusAddr end, ModbusAddr beg, ModbusAddr end,
ModbusData reg, ModbusData reg,
SlaveFunctionCode fn ) SlaveFunctionCode fn )
{ {
if( beg > end ) if( beg > end )
{ {
...@@ -90,9 +90,9 @@ ModbusAddr ModbusHelpers::autodetectSlave( ModbusRTUMaster* m, ...@@ -90,9 +90,9 @@ ModbusAddr ModbusHelpers::autodetectSlave( ModbusRTUMaster* m,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusAddr ModbusHelpers::autodetectSlave( std::string dev, ComPort::Speed s, int tout, ModbusAddr ModbusHelpers::autodetectSlave( std::string dev, ComPort::Speed s, int tout,
ModbusAddr beg, ModbusAddr end, ModbusAddr beg, ModbusAddr end,
ModbusData reg, ModbusData reg,
SlaveFunctionCode fn ) SlaveFunctionCode fn )
{ {
ModbusRTUMaster mb(dev); ModbusRTUMaster mb(dev);
mb.setSpeed(s); mb.setSpeed(s);
...@@ -102,7 +102,7 @@ ModbusAddr ModbusHelpers::autodetectSlave( std::string dev, ComPort::Speed s, i ...@@ -102,7 +102,7 @@ ModbusAddr ModbusHelpers::autodetectSlave( std::string dev, ComPort::Speed s, i
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ComPort::Speed ModbusHelpers::autodetectSpeed( ModbusRTUMaster* m, ModbusAddr slave, ComPort::Speed ModbusHelpers::autodetectSpeed( ModbusRTUMaster* m, ModbusAddr slave,
ModbusData reg, SlaveFunctionCode fn ) ModbusData reg, SlaveFunctionCode fn )
{ {
ComPort::Speed cur = m->getSpeed(); ComPort::Speed cur = m->getSpeed();
ComPort::Speed s = ComPort::ComSpeed0; ComPort::Speed s = ComPort::ComSpeed0;
...@@ -156,7 +156,7 @@ ComPort::Speed ModbusHelpers::autodetectSpeed( ModbusRTUMaster* m, ModbusAddr sl ...@@ -156,7 +156,7 @@ ComPort::Speed ModbusHelpers::autodetectSpeed( ModbusRTUMaster* m, ModbusAddr sl
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ComPort::Speed ModbusHelpers::autodetectSpeed( std::string dev, ModbusRTU::ModbusAddr slave, int tout, ComPort::Speed ModbusHelpers::autodetectSpeed( std::string dev, ModbusRTU::ModbusAddr slave, int tout,
ModbusData reg, SlaveFunctionCode fn ) ModbusData reg, SlaveFunctionCode fn )
{ {
ModbusRTUMaster mb(dev); ModbusRTUMaster mb(dev);
mb.setTimeout(tout); mb.setTimeout(tout);
......
...@@ -39,7 +39,7 @@ ModbusRTUSlaveSlot::~ModbusRTUSlaveSlot() ...@@ -39,7 +39,7 @@ ModbusRTUSlaveSlot::~ModbusRTUSlaveSlot()
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::readCoilStatus( ReadCoilMessage& query, mbErrCode ModbusRTUSlaveSlot::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply ) ReadCoilRetMessage& reply )
{ {
if( !slReadCoil ) if( !slReadCoil )
return erOperationFailed; return erOperationFailed;
...@@ -49,7 +49,7 @@ mbErrCode ModbusRTUSlaveSlot::readCoilStatus( ReadCoilMessage& query, ...@@ -49,7 +49,7 @@ mbErrCode ModbusRTUSlaveSlot::readCoilStatus( ReadCoilMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::readInputStatus( ReadInputStatusMessage& query, mbErrCode ModbusRTUSlaveSlot::readInputStatus( ReadInputStatusMessage& query,
ReadInputStatusRetMessage& reply ) ReadInputStatusRetMessage& reply )
{ {
if( !slReadInputStatus ) if( !slReadInputStatus )
return erOperationFailed; return erOperationFailed;
...@@ -70,7 +70,7 @@ mbErrCode ModbusRTUSlaveSlot::readOutputRegisters( ReadOutputMessage& query, ...@@ -70,7 +70,7 @@ mbErrCode ModbusRTUSlaveSlot::readOutputRegisters( ReadOutputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::readInputRegisters( ReadInputMessage& query, mbErrCode ModbusRTUSlaveSlot::readInputRegisters( ReadInputMessage& query,
ReadInputRetMessage& reply ) ReadInputRetMessage& reply )
{ {
if( !slReadInputs ) if( !slReadInputs )
return erOperationFailed; return erOperationFailed;
...@@ -80,7 +80,7 @@ mbErrCode ModbusRTUSlaveSlot::readInputRegisters( ReadInputMessage& query, ...@@ -80,7 +80,7 @@ mbErrCode ModbusRTUSlaveSlot::readInputRegisters( ReadInputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::forceMultipleCoils( ForceCoilsMessage& query, mbErrCode ModbusRTUSlaveSlot::forceMultipleCoils( ForceCoilsMessage& query,
ForceCoilsRetMessage& reply ) ForceCoilsRetMessage& reply )
{ {
if( !slForceCoils ) if( !slForceCoils )
return erOperationFailed; return erOperationFailed;
...@@ -101,7 +101,7 @@ mbErrCode ModbusRTUSlaveSlot::writeOutputRegisters( WriteOutputMessage& query, ...@@ -101,7 +101,7 @@ mbErrCode ModbusRTUSlaveSlot::writeOutputRegisters( WriteOutputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::diagnostics( DiagnosticMessage& query, mbErrCode ModbusRTUSlaveSlot::diagnostics( DiagnosticMessage& query,
DiagnosticRetMessage& reply ) DiagnosticRetMessage& reply )
{ {
if( !slDiagnostics ) if( !slDiagnostics )
return erOperationFailed; return erOperationFailed;
...@@ -119,7 +119,7 @@ ModbusRTU::mbErrCode ModbusRTUSlaveSlot::read4314( ModbusRTU::MEIMessageRDI& que ...@@ -119,7 +119,7 @@ ModbusRTU::mbErrCode ModbusRTUSlaveSlot::read4314( ModbusRTU::MEIMessageRDI& que
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::forceSingleCoil( ForceSingleCoilMessage& query, mbErrCode ModbusRTUSlaveSlot::forceSingleCoil( ForceSingleCoilMessage& query,
ForceSingleCoilRetMessage& reply ) ForceSingleCoilRetMessage& reply )
{ {
if( !slForceSingleCoil ) if( !slForceSingleCoil )
return erOperationFailed; return erOperationFailed;
...@@ -139,7 +139,7 @@ mbErrCode ModbusRTUSlaveSlot::writeOutputSingleRegister( WriteSingleOutputMessag ...@@ -139,7 +139,7 @@ mbErrCode ModbusRTUSlaveSlot::writeOutputSingleRegister( WriteSingleOutputMessag
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusRTUSlaveSlot::journalCommand( JournalCommandMessage& query, mbErrCode ModbusRTUSlaveSlot::journalCommand( JournalCommandMessage& query,
JournalCommandRetMessage& reply ) JournalCommandRetMessage& reply )
{ {
if( !slJournalCommand ) if( !slJournalCommand )
return erOperationFailed; return erOperationFailed;
......
...@@ -33,7 +33,7 @@ ModbusTCPServerSlot::~ModbusTCPServerSlot() ...@@ -33,7 +33,7 @@ ModbusTCPServerSlot::~ModbusTCPServerSlot()
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPServerSlot::readCoilStatus( ReadCoilMessage& query, mbErrCode ModbusTCPServerSlot::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply ) ReadCoilRetMessage& reply )
{ {
if( !slReadCoil ) if( !slReadCoil )
return erOperationFailed; return erOperationFailed;
...@@ -43,7 +43,7 @@ mbErrCode ModbusTCPServerSlot::readCoilStatus( ReadCoilMessage& query, ...@@ -43,7 +43,7 @@ mbErrCode ModbusTCPServerSlot::readCoilStatus( ReadCoilMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPServerSlot::readInputStatus( ReadInputStatusMessage& query, mbErrCode ModbusTCPServerSlot::readInputStatus( ReadInputStatusMessage& query,
ReadInputStatusRetMessage& reply ) ReadInputStatusRetMessage& reply )
{ {
if( !slReadInputStatus ) if( !slReadInputStatus )
return erOperationFailed; return erOperationFailed;
...@@ -95,7 +95,7 @@ mbErrCode ModbusTCPServerSlot::writeOutputRegisters( WriteOutputMessage& query, ...@@ -95,7 +95,7 @@ mbErrCode ModbusTCPServerSlot::writeOutputRegisters( WriteOutputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPServerSlot::diagnostics( DiagnosticMessage& query, mbErrCode ModbusTCPServerSlot::diagnostics( DiagnosticMessage& query,
DiagnosticRetMessage& reply ) DiagnosticRetMessage& reply )
{ {
if( !slDiagnostics ) if( !slDiagnostics )
return erOperationFailed; return erOperationFailed;
...@@ -113,7 +113,7 @@ ModbusRTU::mbErrCode ModbusTCPServerSlot::read4314( ModbusRTU::MEIMessageRDI& qu ...@@ -113,7 +113,7 @@ ModbusRTU::mbErrCode ModbusTCPServerSlot::read4314( ModbusRTU::MEIMessageRDI& qu
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPServerSlot::forceSingleCoil( ForceSingleCoilMessage& query, mbErrCode ModbusTCPServerSlot::forceSingleCoil( ForceSingleCoilMessage& query,
ForceSingleCoilRetMessage& reply ) ForceSingleCoilRetMessage& reply )
{ {
if( !slForceSingleCoil ) if( !slForceSingleCoil )
return erOperationFailed; return erOperationFailed;
...@@ -133,7 +133,7 @@ mbErrCode ModbusTCPServerSlot::writeOutputSingleRegister( WriteSingleOutputMessa ...@@ -133,7 +133,7 @@ mbErrCode ModbusTCPServerSlot::writeOutputSingleRegister( WriteSingleOutputMessa
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPServerSlot::journalCommand( JournalCommandMessage& query, mbErrCode ModbusTCPServerSlot::journalCommand( JournalCommandMessage& query,
JournalCommandRetMessage& reply ) JournalCommandRetMessage& reply )
{ {
if( !slJournalCommand ) if( !slJournalCommand )
return erOperationFailed; return erOperationFailed;
......
...@@ -441,7 +441,7 @@ void ModbusTCPSession::terminate() ...@@ -441,7 +441,7 @@ void ModbusTCPSession::terminate()
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::readCoilStatus( ReadCoilMessage& query, mbErrCode ModbusTCPSession::readCoilStatus( ReadCoilMessage& query,
ReadCoilRetMessage& reply ) ReadCoilRetMessage& reply )
{ {
if( !slReadCoil ) if( !slReadCoil )
return erOperationFailed; return erOperationFailed;
...@@ -451,7 +451,7 @@ mbErrCode ModbusTCPSession::readCoilStatus( ReadCoilMessage& query, ...@@ -451,7 +451,7 @@ mbErrCode ModbusTCPSession::readCoilStatus( ReadCoilMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::readInputStatus( ReadInputStatusMessage& query, mbErrCode ModbusTCPSession::readInputStatus( ReadInputStatusMessage& query,
ReadInputStatusRetMessage& reply ) ReadInputStatusRetMessage& reply )
{ {
if( !slReadInputStatus ) if( !slReadInputStatus )
return erOperationFailed; return erOperationFailed;
...@@ -462,7 +462,7 @@ mbErrCode ModbusTCPSession::readInputStatus( ReadInputStatusMessage& query, ...@@ -462,7 +462,7 @@ mbErrCode ModbusTCPSession::readInputStatus( ReadInputStatusMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::readOutputRegisters( ReadOutputMessage& query, mbErrCode ModbusTCPSession::readOutputRegisters( ReadOutputMessage& query,
ReadOutputRetMessage& reply ) ReadOutputRetMessage& reply )
{ {
if( !slReadOutputs ) if( !slReadOutputs )
return erOperationFailed; return erOperationFailed;
...@@ -472,7 +472,7 @@ mbErrCode ModbusTCPSession::readOutputRegisters( ReadOutputMessage& query, ...@@ -472,7 +472,7 @@ mbErrCode ModbusTCPSession::readOutputRegisters( ReadOutputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::readInputRegisters( ReadInputMessage& query, mbErrCode ModbusTCPSession::readInputRegisters( ReadInputMessage& query,
ReadInputRetMessage& reply ) ReadInputRetMessage& reply )
{ {
if( !slReadInputs ) if( !slReadInputs )
return erOperationFailed; return erOperationFailed;
...@@ -482,7 +482,7 @@ mbErrCode ModbusTCPSession::readInputRegisters( ReadInputMessage& query, ...@@ -482,7 +482,7 @@ mbErrCode ModbusTCPSession::readInputRegisters( ReadInputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::forceMultipleCoils( ForceCoilsMessage& query, mbErrCode ModbusTCPSession::forceMultipleCoils( ForceCoilsMessage& query,
ForceCoilsRetMessage& reply ) ForceCoilsRetMessage& reply )
{ {
if( !slForceCoils ) if( !slForceCoils )
return erOperationFailed; return erOperationFailed;
...@@ -493,7 +493,7 @@ mbErrCode ModbusTCPSession::forceMultipleCoils( ForceCoilsMessage& query, ...@@ -493,7 +493,7 @@ mbErrCode ModbusTCPSession::forceMultipleCoils( ForceCoilsMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::writeOutputRegisters( WriteOutputMessage& query, mbErrCode ModbusTCPSession::writeOutputRegisters( WriteOutputMessage& query,
WriteOutputRetMessage& reply ) WriteOutputRetMessage& reply )
{ {
if( !slWriteOutputs ) if( !slWriteOutputs )
return erOperationFailed; return erOperationFailed;
...@@ -503,7 +503,7 @@ mbErrCode ModbusTCPSession::writeOutputRegisters( WriteOutputMessage& query, ...@@ -503,7 +503,7 @@ mbErrCode ModbusTCPSession::writeOutputRegisters( WriteOutputMessage& query,
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::diagnostics( DiagnosticMessage& query, mbErrCode ModbusTCPSession::diagnostics( DiagnosticMessage& query,
DiagnosticRetMessage& reply ) DiagnosticRetMessage& reply )
{ {
if( !slDiagnostics ) if( !slDiagnostics )
return erOperationFailed; return erOperationFailed;
...@@ -512,7 +512,7 @@ mbErrCode ModbusTCPSession::diagnostics( DiagnosticMessage& query, ...@@ -512,7 +512,7 @@ mbErrCode ModbusTCPSession::diagnostics( DiagnosticMessage& query,
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTU::mbErrCode ModbusTCPSession::read4314( ModbusRTU::MEIMessageRDI& query, ModbusRTU::mbErrCode ModbusTCPSession::read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply ) ModbusRTU::MEIMessageRetRDI& reply )
{ {
if( !slMEIRDI ) if( !slMEIRDI )
return erOperationFailed; return erOperationFailed;
...@@ -521,7 +521,7 @@ ModbusRTU::mbErrCode ModbusTCPSession::read4314( ModbusRTU::MEIMessageRDI& query ...@@ -521,7 +521,7 @@ ModbusRTU::mbErrCode ModbusTCPSession::read4314( ModbusRTU::MEIMessageRDI& query
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::forceSingleCoil( ForceSingleCoilMessage& query, mbErrCode ModbusTCPSession::forceSingleCoil( ForceSingleCoilMessage& query,
ForceSingleCoilRetMessage& reply ) ForceSingleCoilRetMessage& reply )
{ {
if( !slForceSingleCoil ) if( !slForceSingleCoil )
return erOperationFailed; return erOperationFailed;
...@@ -541,7 +541,7 @@ mbErrCode ModbusTCPSession::writeOutputSingleRegister( WriteSingleOutputMessage& ...@@ -541,7 +541,7 @@ mbErrCode ModbusTCPSession::writeOutputSingleRegister( WriteSingleOutputMessage&
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
mbErrCode ModbusTCPSession::journalCommand( JournalCommandMessage& query, mbErrCode ModbusTCPSession::journalCommand( JournalCommandMessage& query,
JournalCommandRetMessage& reply ) JournalCommandRetMessage& reply )
{ {
if( !slJournalCommand ) if( !slJournalCommand )
return erOperationFailed; return erOperationFailed;
......
...@@ -1546,7 +1546,7 @@ void ForceCoilsRetMessage::init( const ModbusMessage& m ) ...@@ -1546,7 +1546,7 @@ void ForceCoilsRetMessage::init( const ModbusMessage& m )
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ForceCoilsRetMessage::ForceCoilsRetMessage( ModbusAddr _from, ForceCoilsRetMessage::ForceCoilsRetMessage( ModbusAddr _from,
ModbusData s, ModbusData q ) ModbusData s, ModbusData q )
{ {
addr = _from; addr = _from;
func = fnForceMultipleCoils; func = fnForceMultipleCoils;
...@@ -1805,7 +1805,7 @@ void WriteOutputRetMessage::init( const ModbusMessage& m ) ...@@ -1805,7 +1805,7 @@ void WriteOutputRetMessage::init( const ModbusMessage& m )
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
WriteOutputRetMessage::WriteOutputRetMessage( ModbusAddr _from, WriteOutputRetMessage::WriteOutputRetMessage( ModbusAddr _from,
ModbusData s, ModbusData q ) ModbusData s, ModbusData q )
{ {
addr = _from; addr = _from;
func = fnWriteOutputRegisters; func = fnWriteOutputRegisters;
...@@ -3050,13 +3050,13 @@ std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m ) ...@@ -3050,13 +3050,13 @@ std::ostream& ModbusRTU::operator<<(std::ostream& os, SetDateTimeMessage& m )
DebugStream::IosFlagSaver ifs(os); DebugStream::IosFlagSaver ifs(os);
os << setfill('0') os << setfill('0')
<< setw(2) << (int)m.day << "-" << setw(2) << (int)m.day << "-"
<< setw(2) << (int)m.mon << "-" << setw(2) << (int)m.mon << "-"
<< setw(2) << (int)m.century << setw(2) << (int)m.century
<< setw(2) << (int)m.year << " " << setw(2) << (int)m.year << " "
<< setw(2) << (int)m.hour << ":" << setw(2) << (int)m.hour << ":"
<< setw(2) << (int)m.min << ":" << setw(2) << (int)m.min << ":"
<< setw(2) << (int)m.sec; << setw(2) << (int)m.sec;
return os; return os;
} }
......
...@@ -80,7 +80,7 @@ bool TCPCheck::check( const std::string& _ip, int _port, timeout_t tout ) ...@@ -80,7 +80,7 @@ bool TCPCheck::check( const std::string& _ip, int _port, timeout_t tout )
TGuard<TCPCheck> t(this, &TCPCheck::check_thread); TGuard<TCPCheck> t(this, &TCPCheck::check_thread);
std::unique_lock<std::mutex> lock(thr_mutex); std::unique_lock<std::mutex> lock(thr_mutex);
thr_event.wait_for(lock,std::chrono::milliseconds(tout), [=]() thr_event.wait_for(lock, std::chrono::milliseconds(tout), [ = ]()
{ {
return ( thr_finished == true ); return ( thr_finished == true );
} ); } );
...@@ -118,7 +118,7 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, const std::string& ...@@ -118,7 +118,7 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, const std::string&
TGuard<TCPCheck> t(this, &TCPCheck::ping_thread); TGuard<TCPCheck> t(this, &TCPCheck::ping_thread);
std::unique_lock<std::mutex> lock(thr_mutex); std::unique_lock<std::mutex> lock(thr_mutex);
thr_event.wait_for(lock,std::chrono::milliseconds(tout), [=]() thr_event.wait_for(lock, std::chrono::milliseconds(tout), [ = ]()
{ {
return ( thr_finished == true ); return ( thr_finished == true );
} ); } );
......
...@@ -1349,7 +1349,7 @@ void UInterface::askThreshold( const uniset::ObjectId sid, const uniset::Thresho ...@@ -1349,7 +1349,7 @@ void UInterface::askThreshold( const uniset::ObjectId sid, const uniset::Thresho
void UInterface::askRemoteThreshold( const uniset::ObjectId sid, const uniset::ObjectId node, void UInterface::askRemoteThreshold( const uniset::ObjectId sid, const uniset::ObjectId node,
uniset::ThresholdId tid, UniversalIO::UIOCommand cmd, uniset::ThresholdId tid, UniversalIO::UIOCommand cmd,
long lowLimit, long hiLimit, bool invert, long lowLimit, long hiLimit, bool invert,
uniset::ObjectId backid ) const uniset::ObjectId backid ) const
{ {
if( backid == uniset::DefaultObjectId ) if( backid == uniset::DefaultObjectId )
backid = myid; backid = myid;
...@@ -1946,7 +1946,7 @@ uniset::IDSeq_var UInterface::setOutputSeq( const IOController_i::OutSeq& lst, u ...@@ -1946,7 +1946,7 @@ uniset::IDSeq_var UInterface::setOutputSeq( const IOController_i::OutSeq& lst, u
} }
// -------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------
uniset::IDSeq_var UInterface::askSensorsSeq( const uniset::IDList& lst, uniset::IDSeq_var UInterface::askSensorsSeq( const uniset::IDList& lst,
UniversalIO::UIOCommand cmd, uniset::ObjectId backid ) UniversalIO::UIOCommand cmd, uniset::ObjectId backid )
{ {
if( lst.empty() ) if( lst.empty() )
return uniset::IDSeq_var(); return uniset::IDSeq_var();
......
...@@ -177,7 +177,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept ...@@ -177,7 +177,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207 #if __GLIBCXX__ >= 20151207
std::ostringstream fmt; std::ostringstream fmt;
fmt << "%Od" << brk << "%Om" << brk << "%Y"; fmt << "%Od" << brk << "%Om" << brk << "%Y";
return (*this) << std::put_time(&tms,fmt.str().c_str()); return (*this) << std::put_time(&tms, fmt.str().c_str());
#else #else
return (*this) << std::setw(2) << std::setfill('0') << tms.tm_mday << brk return (*this) << std::setw(2) << std::setfill('0') << tms.tm_mday << brk
<< std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << brk << std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << brk
...@@ -200,16 +200,17 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept ...@@ -200,16 +200,17 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207 #if __GLIBCXX__ >= 20151207
std::ostringstream fmt; std::ostringstream fmt;
fmt << "%OH" << brk << "%OM" << brk << "%OS"; fmt << "%OH" << brk << "%OM" << brk << "%OS";
(*this) << std::put_time(&tms,fmt.str().c_str()); (*this) << std::put_time(&tms, fmt.str().c_str());
#else #else
*this << std::setw(2) << std::setfill('0') << tms.tm_hour << brk *this << std::setw(2) << std::setfill('0') << tms.tm_hour << brk
<< std::setw(2) << std::setfill('0') << tms.tm_min << brk << std::setw(2) << std::setfill('0') << tms.tm_min << brk
<< std::setw(2) << std::setfill('0') << tms.tm_sec; << std::setw(2) << std::setfill('0') << tms.tm_sec;
#endif #endif
if( show_usec ) if( show_usec )
(*this) << "." << std::setw(6) << (tv.tv_nsec/1000); (*this) << "." << std::setw(6) << (tv.tv_nsec / 1000);
else if( show_msec ) else if( show_msec )
(*this) << "." << std::setw(3) << (tv.tv_nsec/1000000); (*this) << "." << std::setw(3) << (tv.tv_nsec / 1000000);
return *this; return *this;
} }
...@@ -227,20 +228,20 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept ...@@ -227,20 +228,20 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
std::tm tms = *std::localtime(&tv.tv_sec); std::tm tms = *std::localtime(&tv.tv_sec);
#if __GLIBCXX__ >= 20151207 #if __GLIBCXX__ >= 20151207
*this << std::put_time(&tms,"%Od/%Om/%Y %OH:%OM:%OS"); *this << std::put_time(&tms, "%Od/%Om/%Y %OH:%OM:%OS");
#else #else
*this << std::setw(2) << std::setfill('0') << tms.tm_mday << "/" *this << std::setw(2) << std::setfill('0') << tms.tm_mday << "/"
<< std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << "/" << std::setw(2) << std::setfill('0') << tms.tm_mon + 1 << "/"
<< std::setw(4) << std::setfill('0') << tms.tm_year + 1900 << " " << std::setw(4) << std::setfill('0') << tms.tm_year + 1900 << " "
<< std::setw(2) << std::setfill('0') << tms.tm_hour << ":" << std::setw(2) << std::setfill('0') << tms.tm_hour << ":"
<< std::setw(2) << std::setfill('0') << tms.tm_min << ":" << std::setw(2) << std::setfill('0') << tms.tm_min << ":"
<< std::setw(2) << std::setfill('0') << tms.tm_sec; << std::setw(2) << std::setfill('0') << tms.tm_sec;
#endif #endif
if( show_usec ) if( show_usec )
(*this) << "." << std::setw(6) << std::setfill('0') << (tv.tv_nsec/1000); (*this) << "." << std::setw(6) << std::setfill('0') << (tv.tv_nsec / 1000);
else if( show_msec ) else if( show_msec )
(*this) << "." << std::setw(3) << std::setfill('0') << (tv.tv_nsec/1000000); (*this) << "." << std::setw(3) << std::setfill('0') << (tv.tv_nsec / 1000000);
return *this; return *this;
} }
......
...@@ -226,6 +226,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop ) ...@@ -226,6 +226,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
ostringstream err; ostringstream err;
err << myname << "(evprepare): " << ex.what(); err << myname << "(evprepare): " << ex.what();
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << err.str() << endl; mylog.crit() << err.str() << endl;
...@@ -368,6 +369,7 @@ nlohmann::json LogServer::httpGetShortInfo() ...@@ -368,6 +369,7 @@ nlohmann::json LogServer::httpGetShortInfo()
uniset_rwmutex_rlock l(mutSList); uniset_rwmutex_rlock l(mutSList);
auto& jsess = jdata["sessions"]; auto& jsess = jdata["sessions"];
for( const auto& s : slist ) for( const auto& s : slist )
jsess.push_back(s->httpGetShortInfo()); jsess.push_back(s->httpGetShortInfo());
} }
......
...@@ -82,9 +82,9 @@ bool ProxyManager::activateObject() ...@@ -82,9 +82,9 @@ bool ProxyManager::activateObject()
try try
{ {
ulogrep << myname << "(registered): попытка " ulogrep << myname << "(registered): попытка "
<< i + 1 << " регистриую (id=" << it.first << ") " << i + 1 << " регистриую (id=" << it.first << ") "
<< " (pname=" << it.second->getName() << ") " << " (pname=" << it.second->getName() << ") "
<< uniset_conf()->oind->getNameById(it.first) << endl; << uniset_conf()->oind->getNameById(it.first) << endl;
ui->registered(it.first, getRef(), true); ui->registered(it.first, getRef(), true);
break; break;
......
...@@ -529,14 +529,16 @@ void UniSetActivator::init() ...@@ -529,14 +529,16 @@ void UniSetActivator::init()
abortScript = conf->getArgParam("--uniset-abort-script", ""); abortScript = conf->getArgParam("--uniset-abort-script", "");
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 ) if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 )
{ {
httpHost = conf->getArgParam("--activator-httpserver-host", "localhost"); httpHost = conf->getArgParam("--activator-httpserver-host", "localhost");
ostringstream s; ostringstream s;
s << (getId()==DefaultObjectId ? 8080 : getId() ); s << (getId() == DefaultObjectId ? 8080 : getId() );
httpPort = conf->getArgInt("--activator-httpserver-port", s.str()); httpPort = conf->getArgInt("--activator-httpserver-port", s.str());
ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl; ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
} }
#endif #endif
orb = conf->getORB(); orb = conf->getORB();
...@@ -668,12 +670,13 @@ void UniSetActivator::run( bool thread ) ...@@ -668,12 +670,13 @@ void UniSetActivator::run( bool thread )
set_signals(true); set_signals(true);
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( !httpHost.empty() ) if( !httpHost.empty() )
{ {
try try
{ {
auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this()); auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this());
httpserv = make_shared<UHttp::UHttpServer>(reg,httpHost,httpPort); httpserv = make_shared<UHttp::UHttpServer>(reg, httpHost, httpPort);
httpserv->start(); httpserv->start();
} }
catch( std::exception& ex ) catch( std::exception& ex )
...@@ -681,6 +684,7 @@ void UniSetActivator::run( bool thread ) ...@@ -681,6 +684,7 @@ void UniSetActivator::run( bool thread )
uwarn << myname << "(run): init http server error: " << ex.what() << endl; uwarn << myname << "(run): init http server error: " << ex.what() << endl;
} }
} }
#endif #endif
if( thread ) if( thread )
...@@ -719,8 +723,10 @@ void UniSetActivator::stop() ...@@ -719,8 +723,10 @@ void UniSetActivator::stop()
ulogsys << myname << "(stop): discard request ok." << endl; ulogsys << myname << "(stop): discard request ok." << endl;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( httpserv ) if( httpserv )
httpserv->stop(); httpserv->stop();
#endif #endif
} }
...@@ -876,6 +882,7 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U ...@@ -876,6 +882,7 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U
return httpGet(p); return httpGet(p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpGet(p); return obj->httpGet(p);
...@@ -894,9 +901,9 @@ nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParame ...@@ -894,9 +901,9 @@ nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParame
//! \todo Доделать обработку параметров beg,lim на случай большого количества объектов (и частичных запросов) //! \todo Доделать обработку параметров beg,lim на случай большого количества объектов (и частичных запросов)
size_t lim = 1000; size_t lim = 1000;
getAllObjectsList(vec,lim); getAllObjectsList(vec, lim);
for( const auto& o: vec ) for( const auto& o : vec )
jdata.push_back(o->getName()); jdata.push_back(o->getName());
return jdata; return jdata;
...@@ -908,6 +915,7 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco:: ...@@ -908,6 +915,7 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
return httpHelp(p); return httpHelp(p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpHelp(p); return obj->httpHelp(p);
...@@ -919,11 +927,12 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco:: ...@@ -919,11 +927,12 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
nlohmann::json UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p) nlohmann::json UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p)
{ {
if( name == myname ) if( name == myname )
return httpRequest(req,p); return httpRequest(req, p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpRequest(req,p); return obj->httpRequest(req, p);
ostringstream err; ostringstream err;
err << "Object '" << name << "' not found"; err << "Object '" << name << "' not found";
......
...@@ -368,8 +368,8 @@ void UniSetManager::objects(OManagerCommand cmd) ...@@ -368,8 +368,8 @@ void UniSetManager::objects(OManagerCommand cmd)
ostringstream err; ostringstream err;
err << myname << "(objects): Caught omniORB::fatalException:" << endl; err << myname << "(objects): Caught omniORB::fatalException:" << endl;
err << myname << "(objects): file: " << fe.file() err << myname << "(objects): file: " << fe.file()
<< " line: " << fe.line() << " line: " << fe.line()
<< " mesg: " << fe.errmsg() << endl; << " mesg: " << fe.errmsg() << endl;
ucrit << err.str(); ucrit << err.str();
...@@ -412,7 +412,8 @@ bool UniSetManager::deactivateObject() ...@@ -412,7 +412,8 @@ bool UniSetManager::deactivateObject()
const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& name ) const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& name )
{ {
uniset_rwmutex_rlock lock(olistMutex); uniset_rwmutex_rlock lock(olistMutex);
for( auto&& o: olist )
for( auto && o : olist )
{ {
if( o->getName() == name ) if( o->getName() == name )
return o; return o;
...@@ -424,7 +425,8 @@ const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& nam ...@@ -424,7 +425,8 @@ const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& nam
const std::shared_ptr<UniSetManager> UniSetManager::findManager( const string& name ) const std::shared_ptr<UniSetManager> UniSetManager::findManager( const string& name )
{ {
uniset_rwmutex_rlock lock(mlistMutex); uniset_rwmutex_rlock lock(mlistMutex);
for( auto&& m: mlist )
for( auto && m : mlist )
{ {
if( m->getName() == name ) if( m->getName() == name )
return m; return m;
...@@ -437,11 +439,13 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string& ...@@ -437,11 +439,13 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
{ {
{ {
auto obj = findObject(name); auto obj = findObject(name);
if( obj ) if( obj )
return obj; return obj;
} }
auto man = findManager(name); auto man = findManager(name);
if( man ) if( man )
{ {
auto obj = dynamic_pointer_cast<UniSetObject>(man); auto obj = dynamic_pointer_cast<UniSetObject>(man);
...@@ -449,9 +453,10 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string& ...@@ -449,9 +453,10 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
} }
// ищем в глубину у каждого менеджера // ищем в глубину у каждого менеджера
for( const auto& m: mlist ) for( const auto& m : mlist )
{ {
auto obj = m->deepFindObject(name); auto obj = m->deepFindObject(name);
if( obj ) if( obj )
return obj; return obj;
} }
...@@ -465,18 +470,19 @@ void UniSetManager::getAllObjectsList( std::vector<std::shared_ptr<UniSetObject> ...@@ -465,18 +470,19 @@ void UniSetManager::getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>
vec.push_back(get_ptr()); vec.push_back(get_ptr());
// добавить подчинённые объекты // добавить подчинённые объекты
for( const auto& o: olist ) for( const auto& o : olist )
{ {
vec.push_back(o); vec.push_back(o);
if( lim > 0 && vec.size() >= lim ) if( lim > 0 && vec.size() >= lim )
return; return;
} }
// добавить рекурсивно по менеджерам // добавить рекурсивно по менеджерам
for( const auto& m: mlist ) for( const auto& m : mlist )
{ {
// вызываем рекурсивно // вызываем рекурсивно
m->getAllObjectsList(vec,lim); m->getAllObjectsList(vec, lim);
} }
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
...@@ -30,7 +30,7 @@ using namespace uniset; ...@@ -30,7 +30,7 @@ using namespace uniset;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
float uniset::fcalibrate( float raw, float rawMin, float rawMax, float uniset::fcalibrate( float raw, float rawMin, float rawMax,
float calMin, float calMax, bool limit ) float calMin, float calMax, bool limit )
{ {
if( rawMax == rawMin ) return 0; // деление на 0!!! if( rawMax == rawMin ) return 0; // деление на 0!!!
......
...@@ -41,16 +41,19 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec ...@@ -41,16 +41,19 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
{ {
{ {
std::lock_guard<std::mutex> lck(wlist_mutex); std::lock_guard<std::mutex> lck(wlist_mutex);
if( std::find(wlist.begin(), wlist.end(), w) != wlist.end() ) if( std::find(wlist.begin(), wlist.end(), w) != wlist.end() )
{ {
cerr << "(CommonEventLoop::evrun): " << w->wname() << " ALREADY ADDED.." << endl; cerr << "(CommonEventLoop::evrun): " << w->wname() << " ALREADY ADDED.." << endl;
return false; return false;
} }
wlist.push_back(w); wlist.push_back(w);
} }
{ {
std::lock_guard<std::mutex> lck(thr_mutex); std::lock_guard<std::mutex> lck(thr_mutex);
if( !thr ) if( !thr )
{ {
thr = make_shared<std::thread>( [ = ] { CommonEventLoop::defaultLoop(); } ); thr = make_shared<std::thread>( [ = ] { CommonEventLoop::defaultLoop(); } );
...@@ -58,7 +61,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec ...@@ -58,7 +61,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
std::unique_lock<std::mutex> locker(prep_mutex); std::unique_lock<std::mutex> locker(prep_mutex);
// ожидаем запуска loop // ожидаем запуска loop
// иначе evprep.send() улетит в никуда // иначе evprep.send() улетит в никуда
prep_event.wait_for(locker,std::chrono::milliseconds(waitTimeout_msec), [=]() prep_event.wait_for(locker, std::chrono::milliseconds(waitTimeout_msec), [ = ]()
{ {
return ( isrunning == true ); return ( isrunning == true );
} ); } );
...@@ -86,7 +89,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec ...@@ -86,7 +89,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
evprep.send(); // будим default loop evprep.send(); // будим default loop
// ожидаем обработки evprepare (которая будет в defaultLoop) // ожидаем обработки evprepare (которая будет в defaultLoop)
prep_event.wait_for(locker,std::chrono::milliseconds(waitTimeout_msec), [=]() prep_event.wait_for(locker, std::chrono::milliseconds(waitTimeout_msec), [ = ]()
{ {
return ( prep_notify == true ); return ( prep_notify == true );
} ); } );
...@@ -137,7 +140,7 @@ bool CommonEventLoop::evstop( EvWatcher* w ) ...@@ -137,7 +140,7 @@ bool CommonEventLoop::evstop( EvWatcher* w )
} }
wlist.erase( std::remove( wlist.begin(), wlist.end(), w ), wlist.end() ); wlist.erase( std::remove( wlist.begin(), wlist.end(), w ), wlist.end() );
// wlist.remove(w); // wlist.remove(w);
if( !wlist.empty() ) if( !wlist.empty() )
return false; return false;
...@@ -170,6 +173,7 @@ void CommonEventLoop::onPrepare() noexcept ...@@ -170,6 +173,7 @@ void CommonEventLoop::onPrepare() noexcept
prep_notify = false; prep_notify = false;
{ {
std::lock_guard<std::mutex> lock(prep_mutex); std::lock_guard<std::mutex> lock(prep_mutex);
if( wprep ) if( wprep )
{ {
try try
......
...@@ -175,7 +175,7 @@ void IOController::setUndefinedState( uniset::ObjectId sid, CORBA::Boolean undef ...@@ -175,7 +175,7 @@ void IOController::setUndefinedState( uniset::ObjectId sid, CORBA::Boolean undef
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IOController::localSetUndefinedState( IOStateList::iterator& li, void IOController::localSetUndefinedState( IOStateList::iterator& li,
bool undefined, const uniset::ObjectId sid ) bool undefined, const uniset::ObjectId sid )
{ {
// сохранение текущего состояния // сохранение текущего состояния
if( li == ioList.end() ) if( li == ioList.end() )
...@@ -410,8 +410,8 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& usi, bool force ...@@ -410,8 +410,8 @@ void IOController::ioRegistration( std::shared_ptr<USensorInfo>& usi, bool force
try try
{ {
ulogrep << myname ulogrep << myname
<< "(ioRegistration): регистрирую " << "(ioRegistration): регистрирую "
<< uniset_conf()->oind->getNameById(usi->si.id) << endl; << uniset_conf()->oind->getNameById(usi->si.id) << endl;
ui->registered( usi->si.id, getRef(), true ); ui->registered( usi->si.id, getRef(), true );
return; return;
...@@ -849,15 +849,17 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p ) ...@@ -849,15 +849,17 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
auto& jhelp = jdata[myname]["help"]; auto& jhelp = jdata[myname]["help"];
jhelp["get"]["desc"] = "get value for sensor"; jhelp["get"]["desc"] = "get value for sensor";
jhelp["get"]["params"] = { jhelp["get"]["params"] =
{"id1,name2,id3","get value for id1,name2,id3 sensors"}, {
{"shortInfo","get short information for sensors"} {"id1,name2,id3", "get value for id1,name2,id3 sensors"},
{"shortInfo", "get short information for sensors"}
}; };
jhelp["sensors"]["desc"] = "get all sensors."; jhelp["sensors"]["desc"] = "get all sensors.";
jhelp["sensors"]["params"] = { jhelp["sensors"]["params"] =
{"nameonly","get only name sensors"}, {
{"offset=N","get from N record"}, {"nameonly", "get only name sensors"},
{"limit=M","limit of records"} {"offset=N", "get from N record"},
{"limit=M", "limit of records"}
}; };
return jdata; return jdata;
...@@ -866,12 +868,12 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p ) ...@@ -866,12 +868,12 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
nlohmann::json IOController::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IOController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
if( req == "get" ) if( req == "get" )
return request_get(req,p); return request_get(req, p);
if( req == "sensors" ) if( req == "sensors" )
return request_sensors(req,p); return request_sensors(req, p);
return UniSetManager::httpRequest(req,p); return UniSetManager::httpRequest(req, p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p )
...@@ -885,6 +887,7 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu ...@@ -885,6 +887,7 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
auto conf = uniset_conf(); auto conf = uniset_conf();
auto slist = uniset::getSInfoList( p[0].first, conf ); auto slist = uniset::getSInfoList( p[0].first, conf );
if( slist.empty() ) if( slist.empty() )
{ {
ostringstream err; ostringstream err;
...@@ -893,20 +896,22 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu ...@@ -893,20 +896,22 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
} }
bool shortInfo = false; bool shortInfo = false;
if( p.size() > 1 && p[1].first=="shortInfo" )
if( p.size() > 1 && p[1].first == "shortInfo" )
shortInfo = true; shortInfo = true;
// ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl; // ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl;
nlohmann::json jdata; nlohmann::json jdata;
auto& jsens = jdata[myname]["sensors"]; auto& jsens = jdata[myname]["sensors"];
for( const auto& s: slist ) for( const auto& s : slist )
{ {
try try
{ {
auto sinf = ioList.find(s.si.id); auto sinf = ioList.find(s.si.id);
if( sinf == ioList.end() ) if( sinf == ioList.end() )
{ {
string sid( std::to_string(s.si.id) ); string sid( std::to_string(s.si.id) );
...@@ -960,12 +965,13 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor ...@@ -960,12 +965,13 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor
jsens["default_val"] = s->default_val; jsens["default_val"] = s->default_val;
jsens["dbignore"] = s->dbignore; jsens["dbignore"] = s->dbignore;
jsens["nchanges"] = s->nchanges; jsens["nchanges"] = s->nchanges;
jsens["calibration"] = { jsens["calibration"] =
{ "cmin",s->ci.minCal}, {
{ "cmax",s->ci.maxCal}, { "cmin", s->ci.minCal},
{ "rmin",s->ci.minRaw}, { "cmax", s->ci.maxCal},
{ "rmax",s->ci.maxRaw}, { "rmin", s->ci.minRaw},
{ "precision",s->ci.precision} { "rmax", s->ci.maxRaw},
{ "precision", s->ci.precision}
}; };
// ::CORBA::Boolean undefined; // ::CORBA::Boolean undefined;
...@@ -984,7 +990,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI ...@@ -984,7 +990,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
size_t offset = 0; size_t offset = 0;
size_t limit = 0; size_t limit = 0;
for( const auto& p: params ) for( const auto& p : params )
{ {
if( p.first == "offset" ) if( p.first == "offset" )
offset = uni_atoi(p.second); offset = uni_atoi(p.second);
...@@ -994,7 +1000,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI ...@@ -994,7 +1000,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
size_t endnum = offset + limit; size_t endnum = offset + limit;
for( auto it=myioBegin(); it!=myioEnd(); ++it,num++ ) for( auto it = myioBegin(); it != myioEnd(); ++it, num++ )
{ {
if( limit > 0 && num >= endnum ) if( limit > 0 && num >= endnum )
break; break;
...@@ -1002,7 +1008,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI ...@@ -1002,7 +1008,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
if( offset > 0 && num < offset ) if( offset > 0 && num < offset )
continue; continue;
getSensorInfo(jdata, it->second,false); getSensorInfo(jdata, it->second, false);
} }
jdata["count"] = num; jdata["count"] = num;
......
...@@ -88,10 +88,12 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -88,10 +88,12 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
{ {
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
if( lostConsumers.size() > 0 ) if( lostConsumers.size() > 0 )
{ {
inf << "-------------------------- lost consumers list [maxAttemtps=" << maxAttemtps << "] ------------------" << endl; inf << "-------------------------- lost consumers list [maxAttemtps=" << maxAttemtps << "] ------------------" << endl;
for( const auto& l: lostConsumers )
for( const auto& l : lostConsumers )
{ {
inf << " " << "(" << setw(6) << l.first << ")" inf << " " << "(" << setw(6) << l.first << ")"
<< setw(35) << std::left << ORepHelpers::getShortName(oind->getMapName(l.first)) << setw(35) << std::left << ORepHelpers::getShortName(oind->getMapName(l.first))
...@@ -99,6 +101,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -99,6 +101,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
<< endl; << endl;
} }
} }
inf << "----------------------------------------------------------------------------------" << endl; inf << "----------------------------------------------------------------------------------" << endl;
} }
...@@ -200,7 +203,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -200,7 +203,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
{ {
uniset_rwmutex_wrlock l(lst.mut); uniset_rwmutex_wrlock l(lst.mut);
for( auto&& it : lst.clst ) for( auto && it : lst.clst )
{ {
if( it.id == ci.id && it.node == ci.node ) if( it.id == ci.id && it.node == ci.node )
{ {
...@@ -211,7 +214,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -211,7 +214,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что заказчик опять "на связи" // выставляем флаг, что заказчик опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id); auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false; c->second.lost = false;
return false; return false;
...@@ -233,7 +237,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -233,7 +237,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что клиент опять "на связи" // выставляем флаг, что клиент опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id); auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false; c->second.lost = false;
return true; return true;
...@@ -547,6 +552,7 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag ...@@ -547,6 +552,7 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag
{ {
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto& c = lostConsumers[li->id]; auto& c = lostConsumers[li->id];
// если уже выставлен флаг что "заказчик" пропал, то не надо увеличивать "счётчик" // если уже выставлен флаг что "заказчик" пропал, то не надо увеличивать "счётчик"
// видимо мы уже зафиксировали его пропажу на другом датчике... // видимо мы уже зафиксировали его пропажу на другом датчике...
if( !c.lost ) if( !c.lost )
...@@ -602,7 +608,7 @@ void IONotifyController::initItem( std::shared_ptr<USensorInfo>& usi, IOControll ...@@ -602,7 +608,7 @@ void IONotifyController::initItem( std::shared_ptr<USensorInfo>& usi, IOControll
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void IONotifyController::dumpOrdersList( const uniset::ObjectId sid, void IONotifyController::dumpOrdersList( const uniset::ObjectId sid,
const IONotifyController::ConsumerListInfo& lst ) const IONotifyController::ConsumerListInfo& lst )
{ {
if( restorer == NULL ) if( restorer == NULL )
return; return;
...@@ -848,8 +854,8 @@ bool IONotifyController::removeThreshold( ThresholdExtList& lst, ThresholdInfoEx ...@@ -848,8 +854,8 @@ bool IONotifyController::removeThreshold( ThresholdExtList& lst, ThresholdInfoEx
} }
// -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------
void IONotifyController::checkThreshold( IOController::IOStateList::iterator& li, void IONotifyController::checkThreshold( IOController::IOStateList::iterator& li,
const uniset::ObjectId sid, const uniset::ObjectId sid,
bool send_msg ) bool send_msg )
{ {
if( li == myioEnd() ) if( li == myioEnd() )
li = myiofind(sid); li = myiofind(sid);
...@@ -1142,8 +1148,8 @@ void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& u ...@@ -1142,8 +1148,8 @@ void IONotifyController::onChangeUndefinedState( std::shared_ptr<USensorInfo>& u
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
IDSeq* IONotifyController::askSensorsSeq( const uniset::IDSeq& lst, IDSeq* IONotifyController::askSensorsSeq( const uniset::IDSeq& lst,
const uniset::ConsumerInfo& ci, const uniset::ConsumerInfo& ci,
UniversalIO::UIOCommand cmd) UniversalIO::UIOCommand cmd)
{ {
uniset::IDList badlist; // cписок не найденных идентификаторов uniset::IDList badlist; // cписок не найденных идентификаторов
...@@ -1172,7 +1178,7 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p) ...@@ -1172,7 +1178,7 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
{ {
nlohmann::json jdata = IOController::httpHelp(p); nlohmann::json jdata = IOController::httpHelp(p);
jdata[myname]["help"]["consumers"]["desc"] = "get consumers list"; jdata[myname]["help"]["consumers"]["desc"] = "get consumers list";
jdata[myname]["help"]["consumers"]["params"] = {"sensor1,sensor2,sensor3","get consumers for sensors"}; jdata[myname]["help"]["consumers"]["params"] = {"sensor1,sensor2,sensor3", "get consumers for sensors"};
jdata[myname]["help"]["lost"]["desc"] = "get lost consumers list"; jdata[myname]["help"]["lost"]["desc"] = "get lost consumers list";
return std::move(jdata); return std::move(jdata);
} }
...@@ -1180,12 +1186,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p) ...@@ -1180,12 +1186,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
nlohmann::json IONotifyController::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IONotifyController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
if( req == "consumers" ) if( req == "consumers" )
return request_consumers(req,p); return request_consumers(req, p);
if( req == "lost" ) if( req == "lost" )
return request_lost(req,p); return request_lost(req, p);
return IOController::httpRequest(req,p); return IOController::httpRequest(req, p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request_consumers( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IONotifyController::request_consumers( const string& req, const Poco::URI::QueryParameters& p )
...@@ -1198,6 +1204,7 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P ...@@ -1198,6 +1204,7 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
std::list<ParamSInfo> slist; std::list<ParamSInfo> slist;
if( p.size() > 0 ) if( p.size() > 0 )
{ {
if( !p[0].first.empty() ) if( !p[0].first.empty() )
...@@ -1218,9 +1225,10 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P ...@@ -1218,9 +1225,10 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
{ {
auto& jnotfound = json[myname]["notfound"]; auto& jnotfound = json[myname]["notfound"];
for( const auto& s: slist ) for( const auto& s : slist )
{ {
auto a = askIOList.find(s.si.id); auto a = askIOList.find(s.si.id);
if( a == askIOList.end() ) if( a == askIOList.end() )
{ {
jnotfound.push_back(std::to_string(s.si.id)); jnotfound.push_back(std::to_string(s.si.id));
...@@ -1228,15 +1236,16 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P ...@@ -1228,15 +1236,16 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
} }
// Включаем в ответ все, даже если список заказчиков пустой // Включаем в ответ все, даже если список заказчиков пустой
jdata.push_back( getConsumers(a->first,a->second,false) ); jdata.push_back( getConsumers(a->first, a->second, false) );
} }
} }
else // Проход по всему списку else // Проход по всему списку
{ {
for( auto&& a : askIOList ) for( auto && a : askIOList )
{ {
// добавляем только датчики с непустым списком заказчиков // добавляем только датчики с непустым списком заказчиков
auto jret = getConsumers(a.first,a.second,true); auto jret = getConsumers(a.first, a.second, true);
if( !jret.empty() ) if( !jret.empty() )
jdata.push_back( std::move(jret) ); jdata.push_back( std::move(jret) );
} }
...@@ -1287,7 +1296,7 @@ nlohmann::json IONotifyController::request_lost( const string& req, const Poco:: ...@@ -1287,7 +1296,7 @@ nlohmann::json IONotifyController::request_lost( const string& req, const Poco::
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
for( const auto& c: lostConsumers ) for( const auto& c : lostConsumers )
{ {
string cid( std::to_string(c.first) ); string cid( std::to_string(c.first) );
auto& jcons = jdata[cid]; auto& jcons = jdata[cid];
......
...@@ -359,12 +359,13 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -359,12 +359,13 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
continue; continue;
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
if( !getBaseInfo(xml,it.getCurrent(),si) )
if( !getBaseInfo(xml, it.getCurrent(), si) )
{ {
ostringstream err; ostringstream err;
err << ic->getName() err << ic->getName()
<< "(read_thresholds): не смог получить информацию о пороге" << "(read_thresholds): не смог получить информацию о пороге"
<< " для датчика " << it.getProp("name"); << " для датчика " << it.getProp("name");
ucrit << err.str() << endl; ucrit << err.str() << endl;
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
...@@ -375,8 +376,8 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -375,8 +376,8 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
{ {
ostringstream err; ostringstream err;
err << ic->getName() err << ic->getName()
<< "(read_thresholds): датчик " << it.getProp("name") << "(read_thresholds): датчик " << it.getProp("name")
<< " НЕ НАЙДЕН В СПИСКЕ датчиков"; << " НЕ НАЙДЕН В СПИСКЕ датчиков";
ucrit << err.str() << endl; ucrit << err.str() << endl;
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
...@@ -398,9 +399,9 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod ...@@ -398,9 +399,9 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
{ {
ostringstream err; ostringstream err;
err << ic->getName() err << ic->getName()
<< "(read_thresholds): не смог получить информацию о пороге" << "(read_thresholds): не смог получить информацию о пороге"
<< " для датчика " << " для датчика "
<< uniset_conf()->oind->getNameById(si.id); << uniset_conf()->oind->getNameById(si.id);
ucrit << err.str() << endl; ucrit << err.str() << endl;
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
......
...@@ -118,7 +118,7 @@ const Poco::Timespan UniSetTimer::millisecToPoco( const timeout_t msec ) noexcep ...@@ -118,7 +118,7 @@ const Poco::Timespan UniSetTimer::millisecToPoco( const timeout_t msec ) noexcep
if( msec == WaitUpTime ) if( msec == WaitUpTime )
{ {
// int days, int hours, int minutes, int seconds, int microSeconds // int days, int hours, int minutes, int seconds, int microSeconds
return Poco::Timespan(std::numeric_limits<int>::max(),0,0,0,0); return Poco::Timespan(std::numeric_limits<int>::max(), 0, 0, 0, 0);
} }
// msec --> usec // msec --> usec
...@@ -130,7 +130,7 @@ const Poco::Timespan UniSetTimer::microsecToPoco( const timeout_t usec ) noexcep ...@@ -130,7 +130,7 @@ const Poco::Timespan UniSetTimer::microsecToPoco( const timeout_t usec ) noexcep
if( usec == WaitUpTime ) if( usec == WaitUpTime )
{ {
// int days, int hours, int minutes, int seconds, int microSeconds // int days, int hours, int minutes, int seconds, int microSeconds
return Poco::Timespan(std::numeric_limits<int>::max(),0,0,0,0); return Poco::Timespan(std::numeric_limits<int>::max(), 0, 0, 0, 0);
} }
return Poco::Timespan( long(usec / 1000000), long(usec % 1000000) ); return Poco::Timespan( long(usec / 1000000), long(usec % 1000000) );
......
...@@ -7,17 +7,17 @@ using namespace std; ...@@ -7,17 +7,17 @@ using namespace std;
using namespace uniset; using namespace uniset;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class UTestSupplier: class UTestSupplier:
public UHttp::IHttpRequest public UHttp::IHttpRequest
{ {
public: public:
UTestSupplier(){} UTestSupplier() {}
virtual ~UTestSupplier(){} virtual ~UTestSupplier() {}
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& params ) override virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& params ) override
{ {
nlohmann::json j; nlohmann::json j;
for( const auto& p: params ) for( const auto& p : params )
j[p.first] = p.second; j[p.first] = p.second;
j["test"] = 42; j["test"] = 42;
...@@ -27,9 +27,10 @@ class UTestSupplier: ...@@ -27,9 +27,10 @@ class UTestSupplier:
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j["test"]["help"] = { j["test"]["help"] =
{"cmd1","help for cmd1"}, {
{"cmd2","help for cmd2"} {"cmd1", "help for cmd1"},
{"cmd2", "help for cmd2"}
}; };
return j; return j;
...@@ -44,11 +45,11 @@ class UTestSupplier: ...@@ -44,11 +45,11 @@ class UTestSupplier:
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
class UTestRequestRegistry: class UTestRequestRegistry:
public UHttp::IHttpRequestRegistry public UHttp::IHttpRequestRegistry
{ {
public: public:
UTestRequestRegistry(){} UTestRequestRegistry() {}
virtual ~UTestRequestRegistry(){} virtual ~UTestRequestRegistry() {}
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
...@@ -70,9 +71,10 @@ class UTestRequestRegistry: ...@@ -70,9 +71,10 @@ class UTestRequestRegistry:
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j["TestObject"]["help"] = { j["TestObject"]["help"] =
{"cmd1","help for cmd1"}, {
{"cmd2","help for cmd2"} {"cmd1", "help for cmd1"},
{"cmd2", "help for cmd2"}
}; };
return j; return j;
...@@ -97,10 +99,10 @@ int main(int argc, const char** argv) ...@@ -97,10 +99,10 @@ int main(int argc, const char** argv)
auto reg = std::make_shared<UTestRequestRegistry>(); auto reg = std::make_shared<UTestRequestRegistry>();
auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg); auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg);
auto http = make_shared<UHttp::UHttpServer>(ireg,"localhost", 5555); auto http = make_shared<UHttp::UHttpServer>(ireg, "localhost", 5555);
http->log()->level(Debug::ANY); http->log()->level(Debug::ANY);
cout << "start http test server localhost:5555" << endl; cout << "start http test server localhost:5555" << endl;
http->start(); http->start();
pause(); pause();
......
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