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