Commit b438c2e7 authored by Pavel Vainerman's avatar Pavel Vainerman

Добавил использование astyle в проекте, сделал глобальный make style

parent ceef1366
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
SUBDIRS = UniSetTypes Processes
include $(top_builddir)/include.mk
\ No newline at end of file
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
# Каталоги для размещения генерируемых CC- и HH-файлов соответственно
......@@ -13,3 +13,5 @@ include $(top_builddir)/IDL/idl.mk
idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/Processes
include $(top_builddir)/include.mk
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
# Каталоги для размещения генерируемых CC- и HH-файлов соответственно
......@@ -13,3 +13,5 @@ include $(top_builddir)/IDL/idl.mk
idl_include_HEADERS = *.idl
idl_includedir = $(datadir)/idl/@PACKAGE@/UniSetTypes
include $(top_builddir)/include.mk
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
FIRSTSUBDIRS=IDL
......@@ -24,3 +24,5 @@ if HAVE_COVERAGE
COVERAGE_DIRS=$(COVERAGE_DEFAULT_DIRS)
include $(top_builddir)/testsuite/testcoverage-common.mk
endif
include $(top_builddir)/include.mk
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = @PACKAGE@-admin
@PACKAGE@_admin_SOURCES = admin.cc
@PACKAGE@_admin_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_admin_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_admin_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/include.mk
......@@ -10,113 +10,113 @@
/*! Ничего не делающая реализация MBSlave для тестирования */
class MBSlave
{
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485=false );
~MBSlave();
public:
MBSlave( ModbusRTU::ModbusAddr addr, const std::string& dev, const std::string& speed, bool use485 = false );
~MBSlave();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply2( long val )
{
replyVal2 = val;
}
inline void setReply3( long val )
{
replyVal3 = val;
}
void execute(); /*!< основной цикл работы */
void execute(); /*!< основной цикл работы */
void setLog( std::shared_ptr<DebugStream> dlog );
void setLog( std::shared_ptr<DebugStream> dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusRTUSlave для обмена по RS */
ModbusRTUSlaveSlot* rscomm;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
bool verbose;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
typedef std::map<ModbusRTU::mbErrCode, unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
long replyVal;
long replyVal2;
long replyVal3;
private:
typedef std::map<int, std::string> FileList;
FileList flist;
#endif
long replyVal;
long replyVal2;
long replyVal3;
private:
};
// -------------------------------------------------------------------------
......
......@@ -9,110 +9,110 @@
/*! Ничего не делающая реализация MBTCPServer для тестирования */
class MBTCPServer
{
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port=502, bool verbose=false );
~MBTCPServer();
public:
MBTCPServer( ModbusRTU::ModbusAddr myaddr, const std::string& inetaddr, int port = 502, bool verbose = false );
~MBTCPServer();
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setVerbose( bool state )
{
verbose = state;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setReply( long val )
{
replyVal = val;
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
inline void setIgnoreAddrMode( bool state )
{
if( sslot )
sslot->setIgnoreAddrMode(state);
}
void execute(); /*!< основной цикл работы */
void setLog( std::shared_ptr<DebugStream> dlog );
void execute(); /*!< основной цикл работы */
void setLog( std::shared_ptr<DebugStream> dlog );
protected:
// действия при завершении работы
void sigterm( int signo );
protected:
// действия при завершении работы
void sigterm( int signo );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x01 */
ModbusRTU::mbErrCode readCoilStatus( ModbusRTU::ReadCoilMessage& query,
ModbusRTU::ReadCoilRetMessage& reply );
/*! обработка 0x02 */
ModbusRTU::mbErrCode readInputStatus( ModbusRTU::ReadInputStatusMessage& query,
ModbusRTU::ReadInputStatusRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x03 */
ModbusRTU::mbErrCode readOutputRegisters( ModbusRTU::ReadOutputMessage& query,
ModbusRTU::ReadOutputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x04 */
ModbusRTU::mbErrCode readInputRegisters( ModbusRTU::ReadInputMessage& query,
ModbusRTU::ReadInputRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x05 */
ModbusRTU::mbErrCode forceSingleCoil( ModbusRTU::ForceSingleCoilMessage& query,
ModbusRTU::ForceSingleCoilRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x0F */
ModbusRTU::mbErrCode forceMultipleCoils( ModbusRTU::ForceCoilsMessage& query,
ModbusRTU::ForceCoilsRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x10 */
ModbusRTU::mbErrCode writeOutputRegisters( ModbusRTU::WriteOutputMessage& query,
ModbusRTU::WriteOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
/*! обработка 0x06 */
ModbusRTU::mbErrCode writeOutputSingleRegister( ModbusRTU::WriteSingleOutputMessage& query,
ModbusRTU::WriteSingleOutputRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode diagnostics( ModbusRTU::DiagnosticMessage& query,
ModbusRTU::DiagnosticRetMessage& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
ModbusRTU::mbErrCode read4314( ModbusRTU::MEIMessageRDI& query,
ModbusRTU::MEIMessageRetRDI& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запросов на чтение ошибок */
ModbusRTU::mbErrCode journalCommand( ModbusRTU::JournalCommandMessage& query,
ModbusRTU::JournalCommandRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса на установку времени */
ModbusRTU::mbErrCode setDateTime( ModbusRTU::SetDateTimeMessage& query,
ModbusRTU::SetDateTimeRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
/*! обработка запроса удалённого сервиса */
ModbusRTU::mbErrCode remoteService( ModbusRTU::RemoteServiceMessage& query,
ModbusRTU::RemoteServiceRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
ModbusRTU::mbErrCode fileTransfer( ModbusRTU::FileTransferMessage& query,
ModbusRTU::FileTransferRetMessage& reply );
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
/*! интерфейс ModbusSlave для обмена по RS */
ModbusTCPServerSlot* sslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
bool verbose;
long replyVal;
bool verbose;
long replyVal;
#if 0
typedef std::map<ModbusRTU::mbErrCode,unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
typedef std::map<ModbusRTU::mbErrCode, unsigned int> ExchangeErrorMap;
ExchangeErrorMap errmap; /*!< статистика обмена */
ModbusRTU::mbErrCode prev;
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
// можно было бы сделать unsigned, но аналоговые датчики у нас имеют
// тип long. А это число передаётся в графику в виде аналогового датчика
long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList;
FileList flist;
#endif
typedef std::map<int, std::string> FileList;
FileList flist;
#endif
private:
private:
};
// -------------------------------------------------------------------------
......
......@@ -19,3 +19,5 @@ bin_PROGRAMS = @PACKAGE@-mbrtutest @PACKAGE@-mbrtuslave-echo \
#@PACKAGE@_mbtest2_SOURCES = mbtester2.cc
#@PACKAGE@_mbtest2_LDADD = $(top_builddir)/lib/libUniSet2.la
include $(top_builddir)/include.mk
......@@ -8,132 +8,140 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "use485F", no_argument, 0, 'y' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
printf("-h|--help - this message\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-y|--use485F] - use RS485 Fastwel.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-c|--const-reply] val1 [val2 val3] - Reply val for all queries\n");
}
// --------------------------------------------------------------------------
static char* checkArg( int ind, int argc, char* argv[] );
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
auto dlog = make_shared<DebugStream>();
int use485 = 0;
int replyVal=-1;
int replyVal2=-1;
int replyVal3=-1;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'y':
use485 = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< endl;
dlog->addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr,dev,speed,use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal!=-1 )
mbs.setReply(replyVal);
if( replyVal2!=-1 )
mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(mbslave): " << ex.what() << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
int main( int argc, char** argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
auto dlog = make_shared<DebugStream>();
int use485 = 0;
int replyVal = -1;
int replyVal2 = -1;
int replyVal3 = -1;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'y':
use485 = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
if( checkArg(optind, argc, argv) )
replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind + 1, argc, argv) )
replyVal3 = uni_atoi(argv[optind + 1]);
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< endl;
dlog->addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
MBSlave mbs(myaddr, dev, speed, use485);
mbs.setLog(dlog);
mbs.setVerbose(verb);
if( replyVal != -1 )
mbs.setReply(replyVal);
if( replyVal2 != -1 )
mbs.setReply2(replyVal2);
if( replyVal3 != -1 )
mbs.setReply3(replyVal3);
mbs.execute();
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(mbslave): " << ex.what() << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] )
{
if( i<argc && (argv[i])[0]!='-' )
return argv[i];
if( i < argc && (argv[i])[0] != '-' )
return argv[i];
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -8,132 +8,134 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "speed", required_argument, 0, 's' },
{ "f485", no_argument, 0, 'g' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
printf("-h|--help - this message\n");
printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-d|--device] dev - use device dev. Default: /dev/ttyS0\n");
printf("[-a|--myaddr] addr - Modbus address for this slave. Default: 0x01.\n");
printf("[-s|--speed] speed - 9600,14400,19200,38400,57600,115200. Default: 38400.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-g|--f485] - Use 485 Fastwel\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
int main( int argc, char** argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
int f485 = 0;
string dev("/dev/ttyS0");
string speed("38400");
ModbusRTU::ModbusAddr myaddr = 0x01;
int tout = 2000;
DebugStream dlog;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
try
{
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'd':
dev = string(optarg);
break;
case 'd':
dev = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 's':
speed = string(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 't':
tout = uni_atoi(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'v':
verb = 1;
break;
case 'v':
verb = 1;
break;
case 'g':
f485 = 1;
break;
case 'g':
f485 = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
if( verb )
{
cout << "(init): dev=" << dev << " speed=" << speed
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< " timeout=" << tout << " msec "
<< endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
if( f485 )
{
ComPort485F* cp;
if( f485 )
{
ComPort485F* cp;
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev, 5);
else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev, 6);
else
{
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1;
}
MBSlave mbs(cp,myaddr,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr,dev,speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(mbslave): " << ex.what() << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
MBSlave mbs(cp, myaddr, speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
else
{
MBSlave mbs(myaddr, dev, speed);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.execute();
}
}
catch( ModbusRTU::mbException& ex )
{
cerr << "(mbtester): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(mbslave): " << ex.what() << endl;
}
catch(...)
{
cerr << "(mbslave): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -8,115 +8,118 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "reply-all", no_argument, 0, 'r' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' },
{ "myaddr", required_argument, 0, 'a' },
{ "port", required_argument, 0, 'p' },
{ "reply-all", no_argument, 0, 'r' },
{ "const-reply", required_argument, 0, 'c' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-r|--reply-all] - Reply to all RTU-addresses.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
printf("Example: uniset-mbtcpserver-echo -i localhost -p 2049 -v \n");
printf("-h|--help - this message\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] ip - Server listen ip. Default 127.0.0.1\n");
printf("[-a|--myaddr] addr - Modbus address for master. Default: 0x01.\n");
printf("[-r|--reply-all] - Reply to all RTU-addresses.\n");
printf("[-p|--port] port - Server port. Default: 502.\n");
printf("[-c|--const-reply] val - Reply 'val' for all queries\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
auto dlog = make_shared<DebugStream>();
bool ignoreAddr = false;
int replyVal=-1;
int main( int argc, char** argv )
{
std::ios::sync_with_stdio(false);
int optindex = 0;
int opt = 0;
int verb = 0;
int port = 502;
string iaddr("127.0.0.1");
ModbusRTU::ModbusAddr myaddr = 0x01;
auto dlog = make_shared<DebugStream>();
bool ignoreAddr = false;
int replyVal = -1;
ost::Thread::setException(ost::Thread::throwException);
try
{
while( (opt = getopt_long(argc, argv, "hva:p:i:brc:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
ost::Thread::setException(ost::Thread::throwException);
case 'i':
iaddr = string(optarg);
break;
try
{
while( (opt = getopt_long(argc, argv, "hva:p:i:brc:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'p':
port = uni_atoi(optarg);
break;
case 'i':
iaddr = string(optarg);
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
case 'a':
myaddr = ModbusRTU::str2mbAddr(optarg);
break;
case 'r':
ignoreAddr = true;
break;
case 'v':
verb = 1;
break;
case 'c':
replyVal = uni_atoi(optarg);
break;
case 'r':
ignoreAddr = true;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
case 'c':
replyVal = uni_atoi(optarg);
break;
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< endl;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
dlog->addLevel( Debug::ANY );
}
if( verb )
{
cout << "(init): iaddr: " << iaddr << ":" << port
<< " myaddr=" << ModbusRTU::addr2str(myaddr)
<< endl;
MBTCPServer mbs(myaddr, iaddr, port, verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
dlog->addLevel( Debug::ANY );
}
if( replyVal != -1 )
mbs.setReply(replyVal);
MBTCPServer mbs(myaddr,iaddr,port,verb);
mbs.setLog(dlog);
mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
mbs.setReply(replyVal);
mbs.execute();
}
catch( const ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( const std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
mbs.execute();
}
catch( const ModbusRTU::mbException& ex )
{
cerr << "(mbtcpserver): " << ex << endl;
}
catch( const std::exception& e )
{
cerr << "(mbtcpserver): " << e.what() << endl;
}
catch(...)
{
cerr << "(mbtcpserver): catch(...)" << endl;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
SUBDIRS = scripts Admin NullController SViewer-text \
SMonit MBTester codegen SImitator ULog
include $(top_builddir)/include.mk
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = @PACKAGE@-nullController
@PACKAGE@_nullController_SOURCES = NullController.cc main.cc
@PACKAGE@_nullController_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_nullController_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_nullController_CPPFLAGS = -I$(top_builddir)/lib $(SIGC_CFLAGS)
include $(top_builddir)/include.mk
......@@ -8,28 +8,28 @@ using namespace std;
// --------------------------------------------------------------------------------
NullController::NullController( ObjectId id, const string& askdump,
const std::string& s_filterField,
const std::string& s_filterValue,
const std::string& c_filterField,
const std::string& c_filterValue,
bool _dumpingToDB ):
IONotifyController(id),
dumpingToDB(_dumpingToDB)
const std::string& s_filterField,
const std::string& s_filterValue,
const std::string& c_filterField,
const std::string& c_filterValue,
bool _dumpingToDB ):
IONotifyController(id),
dumpingToDB(_dumpingToDB)
{
restorer = NULL;
restorer = NULL;
shared_ptr<NCRestorer_XML> askd = make_shared<NCRestorer_XML>(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
shared_ptr<NCRestorer_XML> askd = make_shared<NCRestorer_XML>(askdump);
askd->setItemFilter(s_filterField, s_filterValue);
askd->setConsumerFilter(c_filterField, c_filterValue);
restorer = std::static_pointer_cast<NCRestorer>(askd);
restorer = std::static_pointer_cast<NCRestorer>(askd);
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/
/*
// askd->setReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setNCReadItem( sigc::mem_fun(this,&NullController::readSItem) );
askd->setReadThresholdItem( sigc::mem_fun(this,&NullController::readTItem) );
askd->setReadConsumerItem( sigc::mem_fun(this,&NullController::readCItem) );
*/
}
// --------------------------------------------------------------------------------
......@@ -39,8 +39,8 @@ NullController::~NullController()
// --------------------------------------------------------------------------------
void NullController::dumpToDB()
{
if( dumpingToDB )
IONotifyController::dumpToDB();
if( dumpingToDB )
IONotifyController::dumpToDB();
}
// --------------------------------------------------------------------------------
/*
......
......@@ -7,28 +7,28 @@
#include "NCRestorer.h"
// --------------------------------------------------------------------------
class NullController:
public IONotifyController
public IONotifyController
{
public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField="",
const std::string& s_filterValue="",
const std::string& c_filterField="",
const std::string& c_filterValue="",
bool _dumpingToDB=false );
public:
NullController( UniSetTypes::ObjectId id, const std::string& restorfile,
const std::string& s_filterField = "",
const std::string& s_filterValue = "",
const std::string& c_filterField = "",
const std::string& c_filterValue = "",
bool _dumpingToDB = false );
virtual ~NullController();
virtual ~NullController();
protected:
protected:
virtual void dumpToDB();
virtual void dumpToDB();
// bool readSItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec);
// bool readSItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec, NCRestorer::SInfo& inf );
// bool readTItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec);
// bool readCItem( UniXML& xml, UniXML::iterator& it, xmlNode* sec);
private:
bool dumpingToDB;
private:
bool dumpingToDB;
};
// --------------------------------------------------------------------------
......
......@@ -9,82 +9,86 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
cout << "Usage: uniset-nullController"
<< "--confile configure.xml. По умолчанию: configure.xml." << endl
<< " --name ObjectId [--confile configure.xml] [--askfile filename] \n"
<< " --s-filter-field name - поле для фильтрования списка датчиков\n"
<< " --s-filter-value value - значение для поля фильтрования списка датчиков \n"
<< " --c-filter-field name - поле для фильтрования списка заказчиков по каждому датчику\n"
<< " --c-filter-value value - значение для поля фильтрования списка заказчиков по каждому датчику\n"
<< " --dbDumping [0,1] - создавать ли dump-файл \n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
std::ios::sync_with_stdio(false);
try
{
if( argc <=1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
std::ios::sync_with_stdio(false);
if( !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
try
{
if( argc <= 1 )
{
cerr << "\nНе указаны необходимые параметры\n\n";
short_usage();
return 0;
}
auto conf = uniset_init(argc,argv,"configure.xml");
if( !strcmp(argv[1], "--help") )
{
short_usage();
return 0;
}
auto conf = uniset_init(argc, argv, "configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
if( askfile.empty())
askfile = conf->getConfFileName();
if( name.empty())
{
cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0;
}
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection() + "/" + name);
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(nullController): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getControllersSection() << endl;
return 0;
}
auto nc = make_shared<NullController>(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping);
auto act = UniSetActivator::Instance();
act->add(nc);
act->run(false);
return 0;
}
catch( const std::exception& ex )
{
cerr << "(nullController::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
// определяем ask-файл
string askfile = conf->getArgParam("--askfile");
return 1;
if( askfile.empty())
askfile = conf->getConfFileName();
// определяем фильтр
string s_field = conf->getArgParam("--s-filter-field");
string s_fvalue = conf->getArgParam("--s-filter-value");
string c_field = conf->getArgParam("--c-filter-field");
string c_fvalue = conf->getArgParam("--c-filter-value");
// надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping");
auto nc = make_shared<NullController>(ID, askfile, s_field, s_fvalue, c_field, c_fvalue, dbDumping);
auto act = UniSetActivator::Instance();
act->add(nc);
act->run(false);
return 0;
}
catch( const std::exception& ex )
{
cerr << "(nullController::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(nullController::main): catch ..." << endl;
}
return 1;
}
bin_PROGRAMS = @PACKAGE@-simitator
@PACKAGE@_simitator_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_simitator_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_simitator_SOURCES = main.cc
include $(top_builddir)/include.mk
bin_PROGRAMS = @PACKAGE@-smonit
@PACKAGE@_smonit_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_smonit_SOURCES = smonitor.cc
include $(top_builddir)/include.mk
......@@ -7,55 +7,57 @@
using namespace UniSetTypes;
using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
int main( int argc, const char** argv )
{
std::ios::sync_with_stdio(false);
try
{
if( argc>1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
auto conf = uniset_init(argc,argv,"configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
auto act = UniSetActivator::Instance();
auto smon = make_shared<SMonitor>(ID);
act->add(smon);
SystemMessage sm(SystemMessage::StartUp);
act->broadcast( sm.transport_msg() );
act->run(false);
return 0;
}
catch( const Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch( const std::exception& ex )
{
cout << "(main): exception: " << ex.what() << endl;
}
catch(...)
{
cout << "(main): Unknown exception!!"<< endl;
}
return 1;
std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && ( !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h") ) )
{
cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n"
<< " --confile configure.xml \n";
return 0;
}
auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getObjectsSection() << endl;
return 0;
}
auto act = UniSetActivator::Instance();
auto smon = make_shared<SMonitor>(ID);
act->add(smon);
SystemMessage sm(SystemMessage::StartUp);
act->broadcast( sm.transport_msg() );
act->run(false);
return 0;
}
catch( const Exception& ex )
{
cout << "(main):" << ex << endl;
}
catch( const std::exception& ex )
{
cout << "(main): exception: " << ex.what() << endl;
}
catch(...)
{
cout << "(main): Unknown exception!!" << endl;
}
return 1;
}
// ------------------------------------------------------------------------------------------
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
bin_PROGRAMS = @PACKAGE@-sviewer-text
@PACKAGE@_sviewer_text_SOURCES = main.cc
@PACKAGE@_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_sviewer_text_LDADD = $(top_builddir)/lib/libUniSet2.la
@PACKAGE@_sviewer_text_CPPFLAGS = -I$(top_builddir)/lib
include $(top_builddir)/include.mk
......@@ -8,46 +8,49 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
cout << "Usage: uniset-sviewer-text [--fullname] [--polltime msec] [--confile uniset-confile]\n";
}
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
{
std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
auto conf = uniset_init(argc,argv,"configure.xml");
bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
fullname = true;
SViewer sv(conf->getControllersSection(),!fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch( const std::exception& ex )
{
cerr << "(main): Поймали исключение " << ex.what() << endl;
}
catch(...)
{
cerr << "(main): Неизвестное исключение!!!!"<< endl;
}
return 1;
int main(int argc, const char** argv)
{
std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && !strcmp(argv[1], "--help") )
{
short_usage();
return 0;
}
auto conf = uniset_init(argc, argv, "configure.xml");
bool fullname = false;
if( findArgParam("--fullname", conf->getArgc(), conf->getArgv()) != -1 )
fullname = true;
SViewer sv(conf->getControllersSection(), !fullname);
timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS )
{
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
sv.monitor(timeMS);
}
else
sv.view();
return 0;
}
catch( const std::exception& ex )
{
cerr << "(main): Поймали исключение " << ex.what() << endl;
}
catch(...)
{
cerr << "(main): Неизвестное исключение!!!!" << endl;
}
return 1;
}
......@@ -20,3 +20,4 @@ noinst_PROGRAMS = @PACKAGE@-test-logserver @PACKAGE@-log-stdin
@PACKAGE@_log2val_SOURCES = log2val.cc
@PACKAGE@_log2val_LDADD = $(top_builddir)/lib/libUniSet2.la
include $(top_builddir)/include.mk
......@@ -9,95 +9,97 @@
using namespace UniSetTypes;
using namespace std;
// -------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "verbose", no_argument, 0, 'v' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "verbose", no_argument, 0, 'v' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h - this message\n");
printf("-v - Print all messages to stdout\n");
printf("-i addr - LogServer ip or hostname. Default: localhost.\n");
printf("-p port - LogServer port. Default: 3333.\n");
printf("-h - this message\n");
printf("-v - Print all messages to stdout\n");
printf("-i addr - LogServer ip or hostname. Default: localhost.\n");
printf("-p port - LogServer port. Default: 3333.\n");
}
// --------------------------------------------------------------------------
int main( int argc, char* argv[], char* envp[] )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
try
{
while( (opt = getopt_long(argc, argv, "hvi:p:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
addr = string(optarg);
break;
case 'p':
port = atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
cout << "(init): listen " << addr << ":" << port << endl;
auto log = make_shared<DebugStream>();
LogServer ls(log);
ls.run(addr,port,true);
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
try
{
while( (opt = getopt_long(argc, argv, "hvi:p:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
addr = string(optarg);
break;
case 'p':
port = atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
cout << "(init): listen " << addr << ":" << port << endl;
auto log = make_shared<DebugStream>();
LogServer ls(log);
ls.run(addr, port, true);
char buf[10000];
while( true )
{
size_t r = read(fileno(stdin), buf, sizeof(buf) - 1);
if( r > 0 )
{
buf[r] = '\0';
(*(log.get())) << buf;
}
}
}
catch( const SystemError& err )
{
cerr << "(log-stdin): " << err << endl;
return 1;
}
catch( const Exception& ex )
{
cerr << "(log-stdin): " << ex << endl;
return 1;
}
catch(...)
{
cerr << "(log-stdin): catch(...)" << endl;
return 1;
}
char buf[10000];
while( true )
{
size_t r = read(fileno(stdin), buf, sizeof(buf)-1);
if( r > 0 )
{
buf[r] = '\0';
(*(log.get())) << buf;
}
}
}
catch( const SystemError& err )
{
cerr << "(log-stdin): " << err << endl;
return 1;
}
catch( const Exception& ex )
{
cerr << "(log-stdin): " << ex << endl;
return 1;
}
catch(...)
{
cerr << "(log-stdin): catch(...)" << endl;
return 1;
}
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -16,105 +16,106 @@ using namespace std;
// -------------------------------------------------------------------------
static void print_help()
{
printf("\n");
printf("Usage: uniset2-logserver-wrap listen-addr listen-port PROGRAMM ARGS..\n");
printf("\n");
printf("\n");
printf("Usage: uniset2-logserver-wrap listen-addr listen-port PROGRAMM ARGS..\n");
printf("\n");
}
// --------------------------------------------------------------------------
int main( int argc, char* argv[], char* envp[] )
{
if( argc < 4 )
{
print_help();
return 1;
}
string addr(argv[1]);
int port = atoi(argv[2]);
int pid;
int cp[2]; /* Child to parent pipe */
if( pipe(cp) < 0)
{
perror("Can't make pipe");
exit(1);
}
try
{
switch( pid = fork() )
{
case -1:
{
perror("Can't fork");
exit(1);
}
case 0:
{
/* Child. */
close(cp[0]);
close( fileno(stdout) );
dup2(cp[1],fileno(stdout));
close( fileno(stderr) );
dup2(fileno(stdout),fileno(stderr));
execvpe(argv[3], argv + 3, envp);
perror("No exec");
kill(getppid(), SIGQUIT);
exit(1);
}
break;
default:
{
/* Parent. */
close(cp[1]);
auto zlog = make_shared<DebugStream>();
zlog->addLevel(Debug::ANY);
LogServer ls(zlog);
cout << "wrap: server " << addr << ":" << port << endl;
ls.run( addr, port, true );
char buf[5000];
while( true )
{
ssize_t r = read(cp[0], &buf, sizeof(buf)-1 );
if( r > 0 )
{
buf[r] = '\0';
(*(zlog.get())) << buf;
}
}
exit(0);
}
break;
}
}
catch( const SystemError& err )
{
cerr << "(logserver-wrap): " << err << endl;
return 1;
}
catch( const Exception& ex )
{
cerr << "(logserver-wrap): " << ex << endl;
return 1;
}
catch(...)
{
cerr << "(logserver-wrap): catch(...)" << endl;
return 1;
}
return 0;
if( argc < 4 )
{
print_help();
return 1;
}
string addr(argv[1]);
int port = atoi(argv[2]);
int pid;
int cp[2]; /* Child to parent pipe */
if( pipe(cp) < 0)
{
perror("Can't make pipe");
exit(1);
}
try
{
switch( pid = fork() )
{
case -1:
{
perror("Can't fork");
exit(1);
}
case 0:
{
/* Child. */
close(cp[0]);
close( fileno(stdout) );
dup2(cp[1], fileno(stdout));
close( fileno(stderr) );
dup2(fileno(stdout), fileno(stderr));
execvpe(argv[3], argv + 3, envp);
perror("No exec");
kill(getppid(), SIGQUIT);
exit(1);
}
break;
default:
{
/* Parent. */
close(cp[1]);
auto zlog = make_shared<DebugStream>();
zlog->addLevel(Debug::ANY);
LogServer ls(zlog);
cout << "wrap: server " << addr << ":" << port << endl;
ls.run( addr, port, true );
char buf[5000];
while( true )
{
ssize_t r = read(cp[0], &buf, sizeof(buf) - 1 );
if( r > 0 )
{
buf[r] = '\0';
(*(zlog.get())) << buf;
}
}
exit(0);
}
break;
}
}
catch( const SystemError& err )
{
cerr << "(logserver-wrap): " << err << endl;
return 1;
}
catch( const Exception& ex )
{
cerr << "(logserver-wrap): " << ex << endl;
return 1;
}
catch(...)
{
cerr << "(logserver-wrap): catch(...)" << endl;
return 1;
}
return 0;
}
// --------------------------------------------------------------------------
......@@ -10,170 +10,176 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "verbose", no_argument, 0, 'v' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "add", required_argument, 0, 'a' },
{ "del", required_argument, 0, 'd' },
{ "set", required_argument, 0, 's' },
{ "off", required_argument, 0, 'o' },
{ "on", required_argument, 0, 'n' },
{ "rotate", required_argument, 0, 'r' },
{ "logname", required_argument, 0, 'l' },
{ "command-only", no_argument, 0, 'b' },
{ "timeout", required_argument, 0, 'w' },
{ "reconnect-delay", required_argument, 0, 'x' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "verbose", no_argument, 0, 'v' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "add", required_argument, 0, 'a' },
{ "del", required_argument, 0, 'd' },
{ "set", required_argument, 0, 's' },
{ "off", required_argument, 0, 'o' },
{ "on", required_argument, 0, 'n' },
{ "rotate", required_argument, 0, 'r' },
{ "logname", required_argument, 0, 'l' },
{ "command-only", no_argument, 0, 'b' },
{ "timeout", required_argument, 0, 'w' },
{ "reconnect-delay", required_argument, 0, 'x' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h, --help - this message\n");
printf("-v, --verbose - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - LogServer ip or hostname.\n");
printf("[-p|--port] port - LogServer port.\n");
printf("[-l|--logname] name - Send command only for 'logname'.\n");
printf("[-b|--command-only] - Send command and break. (No read logs).\n");
printf("[-w|--timeout] msec - Timeout for wait data. Default: 0 - endless waiting\n");
printf("[-x|--reconnect-delay] msec - Pause for repeat connect to LogServer. Default: 5000 msec.\n");
printf("\n");
printf("Commands:\n");
printf("[--add | -a] info,warn,crit,... - Add log levels.\n");
printf("[--del | -d] info,warn,crit,... - Delete log levels.\n");
printf("[--set | -s] info,warn,crit,... - Set log levels.\n");
printf("--off, -o - Off the write log file (if enabled).\n");
printf("--on, -n - On the write log file (if before disabled).\n");
printf("--rotate, -r - rotate log file.\n");
printf("-h, --help - this message\n");
printf("-v, --verbose - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - LogServer ip or hostname.\n");
printf("[-p|--port] port - LogServer port.\n");
printf("[-l|--logname] name - Send command only for 'logname'.\n");
printf("[-b|--command-only] - Send command and break. (No read logs).\n");
printf("[-w|--timeout] msec - Timeout for wait data. Default: 0 - endless waiting\n");
printf("[-x|--reconnect-delay] msec - Pause for repeat connect to LogServer. Default: 5000 msec.\n");
printf("\n");
printf("Commands:\n");
printf("[--add | -a] info,warn,crit,... - Add log levels.\n");
printf("[--del | -d] info,warn,crit,... - Delete log levels.\n");
printf("[--set | -s] info,warn,crit,... - Set log levels.\n");
printf("--off, -o - Off the write log file (if enabled).\n");
printf("--on, -n - On the write log file (if before disabled).\n");
printf("--rotate, -r - rotate log file.\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
int main( int argc, char** argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
DebugStream dlog;
int cmd = LogServerTypes::cmdNOP;
int data = 0;
string sdata("");
int cmdonly = 0;
string logname("");
timeout_t tout = 0;
timeout_t rdelay = 5000;
try
{
while( (opt = getopt_long(argc, argv, "hva:p:i:d:s:l:onrbx:w:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'a':
{
cmd = LogServerTypes::cmdAddLevel;
sdata = string(optarg);
}
break;
case 'd':
{
cmd = LogServerTypes::cmdDelLevel;
sdata = string(optarg);
}
break;
case 's':
{
cmd = LogServerTypes::cmdSetLevel;
sdata = string(optarg);
}
break;
case 'o':
cmd = LogServerTypes::cmdOffLogFile;
break;
case 'n':
cmd = LogServerTypes::cmdOnLogFile;
break;
case 'r':
cmd = LogServerTypes::cmdRotate;
break;
case 'i':
addr = string(optarg);
break;
case 'l':
logname = string(optarg);
break;
case 'b':
cmdonly = 1;
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'x':
rdelay = uni_atoi(optarg);
break;
case 'w':
tout = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): read from " << addr << ":" << port << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
LogReader lr;
lr.setCommandOnlyMode(cmdonly);
lr.setinTimeout(tout);
lr.setReconnectDelay(rdelay);
if( !sdata.empty() )
{
data = (int)Debug::value(sdata);
if( verb )
cout << "SEND COMMAND: '" << (LogServerTypes::Command)cmd << " data='" << sdata << "'" << endl;
}
lr.readlogs( addr, port, (LogServerTypes::Command)cmd, data, logname, verb );
}
catch( const SystemError& err )
{
cerr << "(log): " << err << endl;
}
catch( const Exception& ex )
{
cerr << "(log): " << ex << endl;
}
catch(...)
{
cerr << "(log): catch(...)" << endl;
}
return 0;
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
DebugStream dlog;
int cmd = LogServerTypes::cmdNOP;
int data = 0;
string sdata("");
int cmdonly = 0;
string logname("");
timeout_t tout = 0;
timeout_t rdelay = 5000;
try
{
while( (opt = getopt_long(argc, argv, "hva:p:i:d:s:l:onrbx:w:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'a':
{
cmd = LogServerTypes::cmdAddLevel;
sdata = string(optarg);
}
break;
case 'd':
{
cmd = LogServerTypes::cmdDelLevel;
sdata = string(optarg);
}
break;
case 's':
{
cmd = LogServerTypes::cmdSetLevel;
sdata = string(optarg);
}
break;
case 'o':
cmd = LogServerTypes::cmdOffLogFile;
break;
case 'n':
cmd = LogServerTypes::cmdOnLogFile;
break;
case 'r':
cmd = LogServerTypes::cmdRotate;
break;
case 'i':
addr = string(optarg);
break;
case 'l':
logname = string(optarg);
break;
case 'b':
cmdonly = 1;
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'x':
rdelay = uni_atoi(optarg);
break;
case 'w':
tout = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): read from " << addr << ":" << port << endl;
dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
LogReader lr;
lr.setCommandOnlyMode(cmdonly);
lr.setinTimeout(tout);
lr.setReconnectDelay(rdelay);
if( !sdata.empty() )
{
data = (int)Debug::value(sdata);
if( verb )
cout << "SEND COMMAND: '" << (LogServerTypes::Command)cmd << " data='" << sdata << "'" << endl;
}
lr.readlogs( addr, port, (LogServerTypes::Command)cmd, data, logname, verb );
}
catch( const SystemError& err )
{
cerr << "(log): " << err << endl;
}
catch( const Exception& ex )
{
cerr << "(log): " << ex << endl;
}
catch(...)
{
cerr << "(log): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
......@@ -5,18 +5,18 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
int main( int argc, char **argv )
int main( int argc, char** argv )
{
if( argc < 2 || (argc > 1 && ( !strcmp(argv[1],"--help") || !strcmp(argv[1],"-h"))) )
{
cout << "Usage: lo2gval [ info,warn,crit,level1...level9,init,repository,system,exception | any ]" << endl;
return 0;
}
if( argc < 2 || (argc > 1 && ( !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) )
{
cout << "Usage: lo2gval [ info,warn,crit,level1...level9,init,repository,system,exception | any ]" << endl;
return 0;
}
const string s(argv[1]);
const string s(argv[1]);
cout << (int)Debug::value(s) << endl;
cout << (int)Debug::value(s) << endl;
return 0;
return 0;
}
// --------------------------------------------------------------------------
......@@ -10,148 +10,151 @@
using namespace UniSetTypes;
using namespace std;
// --------------------------------------------------------------------------
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "verbose", no_argument, 0, 'v' },
{ "delay", required_argument, 0, 'd' },
{ "max-sessions", required_argument, 0, 'm' },
{ NULL, 0, 0, 0 }
static struct option longopts[] =
{
{ "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' },
{ "verbose", no_argument, 0, 'v' },
{ "delay", required_argument, 0, 'd' },
{ "max-sessions", required_argument, 0, 'm' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h|--help - this message\n");
// printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - Inet address for listen connections.\n");
printf("[-p|--port] port - Bind port.\n");
printf("[-d|--delay] msec - Delay for generate message. Default 5000.\n");
printf("[-m|--max-sessions] num - Maximum count sessions for server. Default: 5\n");
printf("-h|--help - this message\n");
// printf("[-t|--timeout] msec - Timeout. Default: 2000.\n");
printf("[-v|--verbose] - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - Inet address for listen connections.\n");
printf("[-p|--port] port - Bind port.\n");
printf("[-d|--delay] msec - Delay for generate message. Default 5000.\n");
printf("[-m|--max-sessions] num - Maximum count sessions for server. Default: 5\n");
}
// --------------------------------------------------------------------------
int main( int argc, char **argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
//int tout = 2000;
timeout_t delay = 5000;
int msess = 5;
try
{
while( (opt = getopt_long(argc, argv, "hvi:p:d:m:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
addr = string(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'd':
delay = uni_atoi(optarg);
break;
case 'm':
msess = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): listen " << addr << ":" << port
// << " timeout=" << tout << " msec "
<< endl;
// dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
auto la = make_shared<LogAgregator>();
auto dlog = make_shared<DebugStream>();
dlog->setLogName("dlog");
la->add(dlog);
auto dlog2 = la->create("dlog2");
if( la->getLog("dlog") == nullptr )
{
cerr << "Not found 'dlog'" << endl;
return 1;
}
if( la->getLog("dlog2") == nullptr )
{
cerr << "Not found 'dlog2'" << endl;
return 1;
}
LogServer ls(la);
ls.setMaxSessionCount(msess);
dlog->addLevel(Debug::ANY);
dlog2->addLevel(Debug::ANY);
ls.run( addr, port, true );
if( verb )
ls.setSessionLog(Debug::ANY);
unsigned int i=0;
while( true )
// for( int n=0; n<2; n++ )
{
dlog->any() << "[" << ++i << "] Test message for log" << endl;
dlog->info() << ": dlog : INFO message" << endl;
dlog->warn() << ": dlog : WARN message" << endl;
dlog->crit() << ": dlog : CRIT message" << endl;
dlog2->info() << ": dlog2: INFO message" << endl;
dlog2->warn() << ": dlog2: WARN message" << endl;
dlog2->crit() << ": dlog2: CRIT message" << endl;
msleep(delay);
}
}
catch( const SystemError& err )
{
cerr << "(logserver): " << err << endl;
}
catch( const Exception& ex )
{
cerr << "(logserver): " << ex << endl;
}
catch(...)
{
cerr << "(logserver): catch(...)" << endl;
}
return 0;
int main( int argc, char** argv )
{
int optindex = 0;
int opt = 0;
int verb = 0;
string addr("localhost");
int port = 3333;
//int tout = 2000;
timeout_t delay = 5000;
int msess = 5;
try
{
while( (opt = getopt_long(argc, argv, "hvi:p:d:m:", longopts, &optindex)) != -1 )
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
addr = string(optarg);
break;
case 'p':
port = uni_atoi(optarg);
break;
case 'd':
delay = uni_atoi(optarg);
break;
case 'm':
msess = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
if( verb )
{
cout << "(init): listen " << addr << ":" << port
// << " timeout=" << tout << " msec "
<< endl;
// dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
auto la = make_shared<LogAgregator>();
auto dlog = make_shared<DebugStream>();
dlog->setLogName("dlog");
la->add(dlog);
auto dlog2 = la->create("dlog2");
if( la->getLog("dlog") == nullptr )
{
cerr << "Not found 'dlog'" << endl;
return 1;
}
if( la->getLog("dlog2") == nullptr )
{
cerr << "Not found 'dlog2'" << endl;
return 1;
}
LogServer ls(la);
ls.setMaxSessionCount(msess);
dlog->addLevel(Debug::ANY);
dlog2->addLevel(Debug::ANY);
ls.run( addr, port, true );
if( verb )
ls.setSessionLog(Debug::ANY);
unsigned int i = 0;
while( true )
// for( int n=0; n<2; n++ )
{
dlog->any() << "[" << ++i << "] Test message for log" << endl;
dlog->info() << ": dlog : INFO message" << endl;
dlog->warn() << ": dlog : WARN message" << endl;
dlog->crit() << ": dlog : CRIT message" << endl;
dlog2->info() << ": dlog2: INFO message" << endl;
dlog2->warn() << ": dlog2: WARN message" << endl;
dlog2->crit() << ": dlog2: CRIT message" << endl;
msleep(delay);
}
}
catch( const SystemError& err )
{
cerr << "(logserver): " << err << endl;
}
catch( const Exception& ex )
{
cerr << "(logserver): " << ex << endl;
}
catch(...)
{
cerr << "(logserver): catch(...)" << endl;
}
return 0;
}
// --------------------------------------------------------------------------
......@@ -8,4 +8,5 @@ xsl_DATA = *.xsl skel*
all-local:
chmod 'a+x' @PACKAGE@-codegen
include $(top_builddir)/include.mk
......@@ -5,45 +5,46 @@
using namespace UniSetTypes;
using namespace std;
// -----------------------------------------------------------------------------
int main( int argc, const char **argv )
int main( int argc, const char** argv )
{
try
{
auto conf = uniset_init(argc, argv);
try
{
auto conf = uniset_init(argc, argv);
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() );
string logfilename = conf->getArgParam("--logfile", "Skel.log");
string logname( conf->getLogDir() + logfilename );
ulog.logFile( logname.c_str() );
auto act = UniSetActivator::Instance();
xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL )
{
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
auto act = UniSetActivator::Instance();
xmlNode* cnode = conf->getNode("Skel");
Skel o("Skel",cnode);
act.add(o.get_ptr());
if( cnode == NULL )
{
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1;
}
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
Skel o("Skel", cnode);
act.add(o.get_ptr());
ulogany << "\n\n\n";
ulogany << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlogany << "\n\n\n";
dlogany << "(Skel::main): -------------- Skel START -------------------------\n\n";
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(Skel::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
SystemMessage sm(SystemMessage::StartUp);
act.broadcast( sm.transport_msg() );
return 0;
ulogany << "\n\n\n";
ulogany << "(Skel::main): -------------- Skel START -------------------------\n\n";
dlogany << "\n\n\n";
dlogany << "(Skel::main): -------------- Skel START -------------------------\n\n";
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(Skel::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(Skel::main): catch(...)" << endl;
}
return 0;
}
// -----------------------------------------------------------------------------
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
Skel::Skel( UniSetTypes::ObjectId id, xmlNode* confnode ):
Skel_SK( id, confnode )
Skel_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,19 +15,19 @@ Skel::~Skel()
// -----------------------------------------------------------------------------
Skel::Skel()
{
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << "(Skel): init failed!!!!!!!!!!!!!!!" << endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void Skel::step()
{
}
// -----------------------------------------------------------------------------
void Skel::sensorInfo( const SensorMessage *sm )
void Skel::sensorInfo( const SensorMessage* sm )
{
}
// -----------------------------------------------------------------------------
void Skel::timerInfo( const TimerMessage *tm )
void Skel::timerInfo( const TimerMessage* tm )
{
}
// -----------------------------------------------------------------------------
......
......@@ -5,21 +5,21 @@
#include "Skel_SK.h"
// -----------------------------------------------------------------------------
class Skel:
public Skel_SK
public Skel_SK
{
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("Skel") );
virtual ~Skel();
public:
Skel( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("Skel") );
virtual ~Skel();
protected:
Skel();
protected:
Skel();
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage *sm );
virtual void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
virtual void step();
virtual void sensorInfo( UniSetTypes::SensorMessage* sm );
virtual void timerInfo( UniSetTypes::TimerMessage* tm );
virtual void askSensors( UniversalIO::UIOCommand cmd );
private:
private:
};
// -----------------------------------------------------------------------------
#endif // Skel_H_
......
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGen::TestGen( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGen_SK( id, confnode )
TestGen_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,8 +15,8 @@ TestGen::~TestGen()
// -----------------------------------------------------------------------------
TestGen::TestGen()
{
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl;
throw Exception();
cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw Exception();
}
// -----------------------------------------------------------------------------
void TestGen::step()
......@@ -27,18 +27,18 @@ void TestGen::step()
cout << dumpIO() << endl;
}
// -----------------------------------------------------------------------------
void TestGen::sensorInfo( const SensorMessage *sm )
void TestGen::sensorInfo( const SensorMessage* sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGen::timerInfo( const TimerMessage *tm )
void TestGen::timerInfo( const TimerMessage* tm )
{
}
// -----------------------------------------------------------------------------
void TestGen::sigterm( int signo )
{
TestGen_SK::sigterm(signo);
TestGen_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,22 +5,22 @@
#include "TestGen_SK.h"
// -----------------------------------------------------------------------------
class TestGen:
public TestGen_SK
public TestGen_SK
{
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGen") );
virtual ~TestGen();
public:
TestGen( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGen") );
virtual ~TestGen();
protected:
TestGen();
protected:
TestGen();
virtual void step() override;
virtual void sensorInfo( const UniSetTypes::SensorMessage *sm ) override;
virtual void timerInfo( const UniSetTypes::TimerMessage *tm ) override;
virtual void sigterm( int signo ) override;
virtual void step() override;
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sigterm( int signo ) override;
private:
private:
};
// -----------------------------------------------------------------------------
#endif // TestGen_H_
......
......@@ -5,7 +5,7 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
TestGenAlone::TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode ):
TestGenAlone_SK( id, confnode )
TestGenAlone_SK( id, confnode )
{
}
// -----------------------------------------------------------------------------
......@@ -15,21 +15,21 @@ TestGenAlone::~TestGenAlone()
// -----------------------------------------------------------------------------
void TestGenAlone::step()
{
cout << strval(in_input2_s) << endl;
cout << strval(in_input2_s) << endl;
}
// -----------------------------------------------------------------------------
void TestGenAlone::sensorInfo( SensorMessage *sm )
void TestGenAlone::sensorInfo( SensorMessage* sm )
{
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
if( sm->id == input1_s )
out_output1_c = in_input1_s; // sm->state
}
// -----------------------------------------------------------------------------
void TestGenAlone::timerInfo( TimerMessage *tm )
void TestGenAlone::timerInfo( TimerMessage* tm )
{
}
// -----------------------------------------------------------------------------
void TestGenAlone::sigterm( int signo )
{
TestGenAlone_SK::sigterm(signo);
TestGenAlone_SK::sigterm(signo);
}
// -----------------------------------------------------------------------------
......@@ -5,20 +5,20 @@
#include "TestGenAlone_SK.h"
// -----------------------------------------------------------------------------
class TestGenAlone:
public TestGenAlone_SK
public TestGenAlone_SK
{
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGenAlone") );
virtual ~TestGenAlone();
public:
TestGenAlone( UniSetTypes::ObjectId id, xmlNode* confnode = UniSetTypes::uniset_conf()->getNode("TestGenAlone") );
virtual ~TestGenAlone();
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage *sm );
void timerInfo( UniSetTypes::TimerMessage *tm );
virtual void sigterm( int signo );
protected:
virtual void step();
void sensorInfo( UniSetTypes::SensorMessage* sm );
void timerInfo( UniSetTypes::TimerMessage* tm );
virtual void sigterm( int signo );
private:
private:
};
// -----------------------------------------------------------------------------
#endif // TestGenAlone_H_
......
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
bin_SCRIPTS = @PACKAGE@-start.sh @PACKAGE@-stop.sh @PACKAGE@-functions.sh
include $(top_builddir)/include.mk
......@@ -33,6 +33,9 @@ AM_PROG_LIBTOOL
LIBVER=2:0:0
AC_SUBST(LIBVER)
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"
AC_SUBST(ASTYLE_OPT)
# Checks for libraries.
PKG_CHECK_MODULES(XML, libxml-2.0)
PKG_CHECK_MODULES(OMNI, omniORB4)
......
############################################################################
# This file is part of the UniSet library #
# This file is part of the UniSet library #
############################################################################
DOC_CFG_USER = *Dox.cfg
......
......@@ -20,7 +20,7 @@
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#ifndef DBServer_MySQL_H_
#define DBServer_MySQL_H_
// --------------------------------------------------------------------------
......@@ -32,7 +32,7 @@
//------------------------------------------------------------------------------------------
/*!
\page page_DBServer_MySQL (DBServer_MySQL) Реализация сервиса ведения БД на основе MySQL
- \ref sec_DBS_Comm
- \ref sec_DBS_Conf
- \ref sec_DBS_Tables
......@@ -131,62 +131,62 @@ CREATE TABLE `main_emergencyrecords` (
\endcode
*/
class DBServer_MySQL:
public DBServer
class DBServer_MySQL:
public DBServer
{
public:
DBServer_MySQL( UniSetTypes::ObjectId id );
DBServer_MySQL();
~DBServer_MySQL();
public:
DBServer_MySQL( UniSetTypes::ObjectId id );
DBServer_MySQL();
~DBServer_MySQL();
static const Debug::type DBLogInfoLevel = Debug::LEVEL9;
static const Debug::type DBLogInfoLevel = Debug::LEVEL9;
protected:
typedef std::map<int, std::string> DBTableMap;
protected:
typedef std::map<int, std::string> DBTableMap;
virtual void initDB(MySQLInterface *db){};
virtual void initDBTableMap(DBTableMap& tblMap){};
virtual void initDB(MySQLInterface* db) {};
virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( MySQLInterface* db );
bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( MySQLInterface* db );
inline const char* tblName(int key)
{
return tblMap[key].c_str();
}
inline const char* tblName(int key)
{
return tblMap[key].c_str();
}
enum Timers
{
PingTimer, /*!< таймер на переодическую проверку соединения с сервером БД */
ReconnectTimer, /*!< таймер на повторную попытку соединения с сервером БД (или восстановления связи) */
lastNumberOfTimer
};
enum Timers
{
PingTimer, /*!< таймер на переодическую проверку соединения с сервером БД */
ReconnectTimer, /*!< таймер на повторную попытку соединения с сервером БД (или восстановления связи) */
lastNumberOfTimer
};
MySQLInterface *db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
MySQLInterface* db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
bool activate;
bool activate;
typedef std::queue<std::string> QueryBuffer;
typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
void flushBuffer();
UniSetTypes::uniset_rwmutex mqbuf;
void flushBuffer();
UniSetTypes::uniset_rwmutex mqbuf;
private:
DBTableMap tblMap;
private:
DBTableMap tblMap;
};
//------------------------------------------------------------------------------------------
......
......@@ -21,7 +21,9 @@ mysql_test_SOURCES = test.cc
devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/mysql
pkgconfigdir = $(libdir)/pkgconfig
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSet2MySQL.pc
include $(top_builddir)/include.mk
endif
......@@ -29,185 +29,191 @@ using namespace UniSetTypes;
// -----------------------------------------------------------------------------------------
MySQLInterface::MySQLInterface():
lastQ(""),
connected(false)
lastQ(""),
connected(false)
{
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql,MYSQL_OPT_COMPRESS,0);
mysql = new MYSQL();
mysql_init(mysql);
// mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
mysql_options(mysql, MYSQL_OPT_COMPRESS, 0);
}
MySQLInterface::~MySQLInterface()
{
close();
delete mysql;
close();
delete mysql;
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::connect( const string& host, const string& user, const string& pswd, const string& dbname)
{
if( !mysql_real_connect(mysql,host.c_str(), user.c_str(),pswd.c_str(),dbname.c_str(),0,NULL,0) )
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
if( !mysql_real_connect(mysql, host.c_str(), user.c_str(), pswd.c_str(), dbname.c_str(), 0, NULL, 0) )
{
cout << error() << endl;
mysql_close(mysql);
connected = false;
return false;
}
connected = true;
return true;
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::close()
{
mysql_close(mysql);
return true;
mysql_close(mysql);
return true;
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::insert( const string& q )
{
if( !mysql )
return false;
if( !mysql )
return false;
if( mysql_query(mysql,q.c_str()) )
return false;
if( mysql_query(mysql, q.c_str()) )
return false;
return true;
return true;
}
// -----------------------------------------------------------------------------------------
MySQLResult MySQLInterface::query( const std::string& q )
{
if( !mysql )
return MySQLResult();
if( !mysql )
return MySQLResult();
if( mysql_query(mysql, q.c_str()) )
{
cerr << error() << endl;
return MySQLResult();
}
if( mysql_query(mysql,q.c_str()) )
{
cerr << error() << endl;
return MySQLResult();
}
lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( !res || mysql_num_rows(res)==0 )
return MySQLResult();
if( !res || mysql_num_rows(res) == 0 )
return MySQLResult();
return MySQLResult(res,true);
return MySQLResult(res, true);
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::query_ok( const string& q )
{
if( !mysql )
return false;
if( !mysql )
return false;
if( mysql_query(mysql, q.c_str()) )
return false;
lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( mysql_query(mysql,q.c_str()) )
return false;
if( !res || mysql_num_rows(res) == 0 )
{
if( res )
mysql_free_result(res);
lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( !res || mysql_num_rows(res)==0 )
{
if( res )
mysql_free_result(res);
return false;
}
return false;
}
mysql_free_result(res);
return true;
mysql_free_result(res);
return true;
}
// -----------------------------------------------------------------------------------------
const string MySQLInterface::error()
{
return mysql_error(mysql);
return mysql_error(mysql);
}
// -----------------------------------------------------------------------------------------
const string MySQLInterface::lastQuery()
{
return lastQ;
return lastQ;
}
// -----------------------------------------------------------------------------------------
int MySQLInterface::insert_id()
{
if( !mysql )
return 0;
if( !mysql )
return 0;
return mysql_insert_id(mysql);
return mysql_insert_id(mysql);
}
// -----------------------------------------------------------------------------------------
const char* MySQLInterface::gethostinfo()
{
return mysql_get_host_info(mysql);
return mysql_get_host_info(mysql);
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::ping()
{
if( !mysql || !connected )
return false;
if( !mysql || !connected )
return false;
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
// внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql);
}
// -----------------------------------------------------------------------------------------
bool MySQLInterface::isConnection()
{
return ping(); //!mysql;
return ping(); //!mysql;
}
// -----------------------------------------------------------------------------------------
string MySQLInterface::addslashes( const string& str )
{
ostringstream tmp;
for( unsigned int i=0; i<str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
ostringstream tmp;
return tmp.str();
for( unsigned int i = 0; i < str.size(); i++ )
{
// if( !strcmp(str[i],'\'') )
if( str[i] == '\'' )
tmp << "\\";
tmp << str[i];
}
return tmp.str();
}
// -----------------------------------------------------------------------------------------
int num_cols( MySQLResult::iterator& it )
{
return it->size();
return it->size();
}
// -----------------------------------------------------------------------------------------
int as_int( MySQLResult::iterator& it, int col )
{
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
// if( col<0 || col >it->size() )
// return 0;
return uni_atoi( (*it)[col] );
}
// -----------------------------------------------------------------------------------------
double as_double( MySQLResult::iterator& it, int col )
{
return atof( ((*it)[col]).c_str() );
return atof( ((*it)[col]).c_str() );
}
// -----------------------------------------------------------------------------------------
string as_string( MySQLResult::iterator& it, int col )
{
return ((*it)[col]);
return ((*it)[col]);
}
// -----------------------------------------------------------------------------------------
int as_int( MySQLResult::COL::iterator& it )
{
return uni_atoi( (*it) );
return uni_atoi( (*it) );
}
// -----------------------------------------------------------------------------------------
double as_double( MySQLResult::COL::iterator& it )
{
return atof( (*it).c_str() );
return atof( (*it).c_str() );
}
// -----------------------------------------------------------------------------------------
std::string as_string( MySQLResult::COL::iterator& it )
{
return (*it);
return (*it);
}
// -----------------------------------------------------------------------------------------
#if 0
MySQLResult::COL get_col( MySQLResult::ROW::iterator& it )
{
return (*it);
return (*it);
}
#endif
// -----------------------------------------------------------------------------------------
......@@ -218,19 +224,20 @@ MySQLResult::~MySQLResult()
// -----------------------------------------------------------------------------------------
MySQLResult::MySQLResult( MYSQL_RES* myres, bool finalize )
{
MYSQL_ROW row;
unsigned int nfields = mysql_num_fields(myres);
MYSQL_ROW row;
unsigned int nfields = mysql_num_fields(myres);
while( (row = mysql_fetch_row(myres)) )
{
COL c;
while( (row = mysql_fetch_row(myres)) )
{
COL c;
for( unsigned int i = 0; i<nfields; i++ )
c.push_back( (row[i]!=0 ? string(row[i]):"") );
for( unsigned int i = 0; i < nfields; i++ )
c.push_back( (row[i] != 0 ? string(row[i]) : "") );
res.push_back(c);
}
res.push_back(c);
}
if( finalize )
mysql_free_result(myres);
if( finalize )
mysql_free_result(myres);
}
// -----------------------------------------------------------------------------------------
......@@ -36,74 +36,89 @@ class MySQLResult;
// ----------------------------------------------------------------------------
class MySQLInterface
{
public:
public:
MySQLInterface();
~MySQLInterface();
MySQLInterface();
~MySQLInterface();
// MySQLResult listFields( const std::string& table, const std::string& wild );
// MySQLResult listFields( const std::string& table, const std::string& wild );
bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname);
bool close();
bool connect( const std::string& host, const std::string& user, const std::string& pswd,
const std::string& dbname);
bool close();
bool query_ok( const std::string& q );
bool query_ok( const std::string& q );
// \param finalize - освободить буфер после запроса
MySQLResult query( const std::string& q );
// \param finalize - освободить буфер после запроса
MySQLResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
std::string addslashes(const std::string& str);
std::string addslashes(const std::string& str);
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*!
проверка связи с БД.
в случае отсутсвия попытка восстановить...
*/
bool ping();
/*! связь с БД установлена (была) */
bool isConnection();
/*! связь с БД установлена (была) */
bool isConnection();
int insert_id();
int insert_id();
const std::string error();
const std::string error();
// *******************
const char* gethostinfo();
protected:
// *******************
const char* gethostinfo();
protected:
private:
private:
MYSQL *mysql;
std::string lastQ;
bool connected;
MYSQL* mysql;
std::string lastQ;
bool connected;
};
// ----------------------------------------------------------------------------------
class MySQLResult
{
public:
MySQLResult(){}
MySQLResult( MYSQL_RES* r, bool finalize=true );
~MySQLResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef ROW::iterator iterator;
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline operator bool(){ return !res.empty(); }
inline size_t size(){ return res.size(); }
inline bool empty(){ return res.empty(); }
protected:
ROW res;
public:
MySQLResult() {}
MySQLResult( MYSQL_RES* r, bool finalize = true );
~MySQLResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef ROW::iterator iterator;
inline iterator begin()
{
return res.begin();
}
inline iterator end()
{
return res.end();
}
inline operator bool()
{
return !res.empty();
}
inline size_t size()
{
return res.size();
}
inline bool empty()
{
return res.empty();
}
protected:
ROW res;
};
// ----------------------------------------------------------------------------------
int num_cols( MySQLResult::iterator& );
......
......@@ -8,63 +8,66 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
std::ios::sync_with_stdio(false);
auto conf = uniset_init(argc,argv,"configure.xml");
try
{
if( argc > 1 && !strcmp(argv[1], "--help") )
{
short_usage();
return 0;
}
ObjectId ID = conf->getDBServer();
auto conf = uniset_init(argc, argv, "configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданный в "
<< conf->getConfFileName() << endl;
}
ObjectId ID = conf->getDBServer();
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
DBServer_MySQL dbs(ID);
auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr());
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(DBServer::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданный в "
<< conf->getConfFileName() << endl;
}
return 0;
ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_MySQL dbs(ID);
auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr());
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(DBServer::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
}
......@@ -8,50 +8,54 @@ using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
std::string dbname("test-db");
if( argc > 1 )
dbname = string(argv[1]);
try
{
MySQLInterface db;
if( !db.connect("localhost","dbadmin","dbadmin",dbname) )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
MySQLResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( MySQLResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
MySQLResult::COL col(*it);
for( MySQLResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch( const Exception& ex )
{
cerr << "(test): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(test): " << ex.what() << endl;
}
return 0;
std::string dbname("test-db");
if( argc > 1 )
dbname = string(argv[1]);
try
{
MySQLInterface db;
if( !db.connect("localhost", "dbadmin", "dbadmin", dbname) )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
MySQLResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( MySQLResult::iterator it = r.begin(); it != r.end(); it++ )
{
cout << "ROW: ";
MySQLResult::COL col(*it);
for( MySQLResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch( const Exception& ex )
{
cerr << "(test): " << ex << endl;
}
catch( const std::exception& ex )
{
cerr << "(test): " << ex.what() << endl;
}
return 0;
}
......@@ -20,7 +20,7 @@
/*! \file
* \author Pavel Vainerman
*/
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#ifndef DBServer_SQLite_H_
#define DBServer_SQLite_H_
// --------------------------------------------------------------------------
......@@ -32,7 +32,7 @@
//------------------------------------------------------------------------------------------
/*!
\page page_DBServer_SQLite (DBServer_SQLite) Реализация сервиса ведения БД на основе SQLite
- \ref sec_DBS_Comm
- \ref sec_DBS_Conf
- \ref sec_DBS_Tables
......@@ -131,62 +131,62 @@ CREATE TABLE `main_emergencyrecords` (
\endcode
*/
class DBServer_SQLite:
public DBServer
class DBServer_SQLite:
public DBServer
{
public:
DBServer_SQLite( UniSetTypes::ObjectId id );
DBServer_SQLite();
~DBServer_SQLite();
public:
DBServer_SQLite( UniSetTypes::ObjectId id );
DBServer_SQLite();
~DBServer_SQLite();
static const Debug::type DBLogInfoLevel = Debug::LEVEL9;
static const Debug::type DBLogInfoLevel = Debug::LEVEL9;
protected:
typedef std::map<int, std::string> DBTableMap;
protected:
typedef std::map<int, std::string> DBTableMap;
virtual void initDB( SQLiteInterface *db ){};
virtual void initDBTableMap(DBTableMap& tblMap){};
virtual void initDB( SQLiteInterface* db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( SQLiteInterface* db );
bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( SQLiteInterface* db );
inline const char* tblName(int key)
{
return tblMap[key].c_str();
}
inline const char* tblName(int key)
{
return tblMap[key].c_str();
}
enum Timers
{
PingTimer, /*!< таймер на переодическую проверку соединения с сервером БД */
ReconnectTimer, /*!< таймер на повторную попытку соединения с сервером БД (или восстановления связи) */
lastNumberOfTimer
};
enum Timers
{
PingTimer, /*!< таймер на переодическую проверку соединения с сервером БД */
ReconnectTimer, /*!< таймер на повторную попытку соединения с сервером БД (или восстановления связи) */
lastNumberOfTimer
};
SQLiteInterface *db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
SQLiteInterface* db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
bool activate;
bool activate;
typedef std::queue<std::string> QueryBuffer;
typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
void flushBuffer();
UniSetTypes::uniset_rwmutex mqbuf;
void flushBuffer();
UniSetTypes::uniset_rwmutex mqbuf;
private:
DBTableMap tblMap;
private:
DBTableMap tblMap;
};
//------------------------------------------------------------------------------------------
......
......@@ -22,8 +22,10 @@ sqlite_test_SOURCES = test.cc
devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/sqlite
pkgconfigdir = $(libdir)/pkgconfig
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libUniSet2SQLite.pc
include $(top_builddir)/include.mk
endif
\ No newline at end of file
\ No newline at end of file
......@@ -85,72 +85,96 @@ class SQLiteResult;
// ----------------------------------------------------------------------------
class SQLiteInterface
{
public:
public:
SQLiteInterface();
~SQLiteInterface();
SQLiteInterface();
~SQLiteInterface();
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
bool connect( const std::string& dbfile, bool create = false );
bool close();
bool isConnection();
bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; }
void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout()
{
return opTimeout;
}
inline void setOperationCheckPause( timeout_t msec ){ opCheckPause = msec; }
inline timeout_t getOperationCheckPause(){ return opCheckPause; }
inline void setOperationCheckPause( timeout_t msec )
{
opCheckPause = msec;
}
inline timeout_t getOperationCheckPause()
{
return opCheckPause;
}
SQLiteResult query( const std::string& q );
const std::string lastQuery();
SQLiteResult query( const std::string& q );
const std::string lastQuery();
bool insert( const std::string& q );
int insert_id();
bool insert( const std::string& q );
int insert_id();
std::string error();
std::string error();
protected:
protected:
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
bool wait( sqlite3_stmt* stmt, int result );
static bool checkResult( int rc );
private:
private:
sqlite3* db;
// sqlite3_stmt* curStmt;
sqlite3* db;
// sqlite3_stmt* curStmt;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
std::string lastQ;
std::string lastE;
bool queryok; // успешность текущего запроса
bool connected;
timeout_t opTimeout;
timeout_t opCheckPause;
timeout_t opTimeout;
timeout_t opCheckPause;
};
// ----------------------------------------------------------------------------------
class SQLiteResult
{
public:
SQLiteResult(){}
SQLiteResult( sqlite3_stmt* s, bool finalize=true );
~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef ROW::iterator iterator;
inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); }
inline operator bool(){ return !res.empty(); }
inline int size(){ return res.size(); }
inline bool empty(){ return res.empty(); }
protected:
ROW res;
public:
SQLiteResult() {}
SQLiteResult( sqlite3_stmt* s, bool finalize = true );
~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::deque<COL> ROW;
typedef ROW::iterator iterator;
inline iterator begin()
{
return res.begin();
}
inline iterator end()
{
return res.end();
}
inline operator bool()
{
return !res.empty();
}
inline int size()
{
return res.size();
}
inline bool empty()
{
return res.empty();
}
protected:
ROW res;
};
// ----------------------------------------------------------------------------
int num_cols( SQLiteResult::iterator& );
......
......@@ -8,64 +8,67 @@ using namespace std;
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && !strcmp(argv[1],"--help") )
{
short_usage();
return 0;
}
std::ios::sync_with_stdio(false);
auto conf = uniset_init(argc,argv,"configure.xml");
try
{
if( argc > 1 && !strcmp(argv[1], "--help") )
{
short_usage();
return 0;
}
ObjectId ID = conf->getDBServer();
auto conf = uniset_init(argc, argv, "configure.xml");
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ObjectId ID = conf->getDBServer();
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
// определяем ID объекта
string name = conf->getArgParam("--name");
DBServer_SQLite dbs(ID);
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr());
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(DBServer::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
return 0;
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_SQLite dbs(ID);
auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr());
act->run(false);
}
catch( const std::exception& ex )
{
cerr << "(DBServer::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(DBServer::main): catch ..." << endl;
}
return 0;
}
......@@ -8,44 +8,48 @@ using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch( const std::exception& ex )
{
cerr << "(test): " << ex.what() << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
return 0;
try
{
SQLiteInterface db;
if( !db.connect("test.db") )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
stringstream q;
q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str());
if( !r )
{
cerr << "db connect error: " << db.error() << endl;
return 1;
}
for( SQLiteResult::iterator it = r.begin(); it != r.end(); it++ )
{
cout << "ROW: ";
SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl;
}
db.close();
}
catch( const std::exception& ex )
{
cerr << "(test): " << ex.what() << endl;
}
catch(...)
{
cerr << "(test): catch ..." << endl;
}
return 0;
}
......@@ -9,58 +9,61 @@
/*! Интерфейс для работы с в/в */
class ComediInterface
{
public:
ComediInterface( const std::string& dev );
~ComediInterface();
public:
ComediInterface( const std::string& dev );
~ComediInterface();
int getAnalogChannel( int subdev, int channel, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
int getAnalogChannel( int subdev, int channel, int range = 0, int aref = AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range=0, int aref=AREF_GROUND )
throw(UniSetTypes::Exception);
void setAnalogChannel( int subdev, int channel, int data, int range = 0, int aref = AREF_GROUND )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
bool getDigitalChannel( int subdev, int channel )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
void setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception);
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
// Конфигурирование входов / выходов
enum ChannelType
{
DI = INSN_CONFIG_DIO_INPUT,
DO = INSN_CONFIG_DIO_OUTPUT,
AI = 100, // INSN_CONFIG_AIO_INPUT,
AO = 101 // INSN_CONFIG_AIO_OUTPUT
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
enum SubdevType
{
Unknown = 0,
TBI24_0 = 1,
TBI0_24 = 2,
TBI16_8 = 3,
GRAYHILL = 4
};
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
static std::string type2str( SubdevType t );
static SubdevType str2type( const std::string& s );
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureSubdev( int subdev, SubdevType type ) throw(UniSetTypes::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range=0, int aref=0 )
throw(UniSetTypes::Exception);
void configureChannel( int subdev, int channel, ChannelType type, int range = 0, int aref = 0 )
throw(UniSetTypes::Exception);
inline const std::string devname(){ return dname; }
inline const std::string devname()
{
return dname;
}
protected:
protected:
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
comedi_t* card; /*!< интерфейс для работы с картами в/в */
std::string dname;
private:
private:
};
// -----------------------------------------------------------------------------
#endif // ComediInterface_H_
......
......@@ -47,5 +47,7 @@ pkgconfig_DATA = libUniSet2IOControl.pc
all-local:
ln -sf ../IOControl/$(devel_include_HEADERS) ../include
include $(top_builddir)/include.mk
endif
# end of ENABLE_IO
......@@ -9,71 +9,74 @@ using namespace UniSetTypes;
using namespace std;
using namespace UniSetExtensions;
// --------------------------------------------------------------------------
int main(int argc, const char **argv)
int main(int argc, const char** argv)
{
std::ios::sync_with_stdio(false);
if( argc>1 && strcmp(argv[1],"--help")==0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv);
return 0;
}
std::ios::sync_with_stdio(false);
try
{
auto conf = uniset_init(argc, argv);
if( argc > 1 && strcmp(argv[1], "--help") == 0 )
{
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc, argv);
return 0;
}
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog()->logFile( logname );
ulog()->logFile( logname );
try
{
auto conf = uniset_init(argc, argv);
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
string logfilename = conf->getArgParam("--io-logfile", "iocontrol.log");
string logname( conf->getLogDir() + logfilename );
dlog()->logFile( logname );
ulog()->logFile( logname );
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() )
shmID = conf->getControllerID(sID);
else
shmID = getSharedMemoryID();
auto ic = IOControl::init_iocontrol(argc,argv,shmID);
if( !ic )
{
dcrit << "(iocontrol): init не прошёл..." << endl;
return 1;
}
if( shmID == DefaultObjectId )
{
cerr << sID << "? SharedMemoryID not found in "
<< conf->getControllersSection() << " section" << endl;
return 1;
}
auto act = UniSetActivator::Instance();
act->add(ic);
SystemMessage sm(SystemMessage::StartUp);
act->broadcast( sm.transport_msg() );
auto ic = IOControl::init_iocontrol(argc, argv, shmID);
ulogany << "\n\n\n";
ulogany << "(main): -------------- IOControl START -------------------------\n\n";
dlogany << "\n\n\n";
dlogany << "(main): -------------- IOControl START -------------------------\n\n";
act->run(true);
msleep(500);
ic->execute();
return 0;
}
catch( const std::exception& ex )
{
dcrit << "(iocontrol): " << ex.what() << endl;
}
catch(...)
{
dcrit << "(iocontrol): catch(...)" << endl;
}
if( !ic )
{
dcrit << "(iocontrol): init не прошёл..." << endl;
return 1;
}
return 1;
auto act = UniSetActivator::Instance();
act->add(ic);
SystemMessage sm(SystemMessage::StartUp);
act->broadcast( sm.transport_msg() );
ulogany << "\n\n\n";
ulogany << "(main): -------------- IOControl START -------------------------\n\n";
dlogany << "\n\n\n";
dlogany << "(main): -------------- IOControl START -------------------------\n\n";
act->run(true);
msleep(500);
ic->execute();
return 0;
}
catch( const std::exception& ex )
{
dcrit << "(iocontrol): " << ex.what() << endl;
}
catch(...)
{
dcrit << "(iocontrol): catch(...)" << endl;
}
return 1;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment