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

make style (atyle)

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