Commit b438c2e7 authored by Pavel Vainerman's avatar Pavel Vainerman

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

parent ceef1366
...@@ -3,3 +3,5 @@ ...@@ -3,3 +3,5 @@
############################################################################ ############################################################################
SUBDIRS = UniSetTypes Processes SUBDIRS = UniSetTypes Processes
include $(top_builddir)/include.mk
\ No newline at end of file
...@@ -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
...@@ -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
...@@ -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
...@@ -7,3 +7,4 @@ bin_PROGRAMS = @PACKAGE@-admin ...@@ -7,3 +7,4 @@ bin_PROGRAMS = @PACKAGE@-admin
@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
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
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 )
...@@ -100,7 +100,7 @@ class MBSlave ...@@ -100,7 +100,7 @@ class MBSlave
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;
...@@ -110,7 +110,7 @@ class MBSlave ...@@ -110,7 +110,7 @@ class MBSlave
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;
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
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 )
...@@ -98,7 +98,7 @@ class MBTCPServer ...@@ -98,7 +98,7 @@ class MBTCPServer
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;
...@@ -108,7 +108,7 @@ class MBTCPServer ...@@ -108,7 +108,7 @@ class MBTCPServer
long askCount; /*!< количество принятых запросов */ long askCount; /*!< количество принятых запросов */
typedef std::map<int,std::string> FileList; typedef std::map<int, std::string> FileList;
FileList flist; FileList flist;
#endif #endif
......
...@@ -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,7 +8,8 @@ ...@@ -8,7 +8,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
...@@ -33,7 +34,7 @@ static void print_help() ...@@ -33,7 +34,7 @@ static void print_help()
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
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;
...@@ -44,13 +45,13 @@ int main( int argc, char **argv ) ...@@ -44,13 +45,13 @@ int main( int argc, char **argv )
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)
{ {
...@@ -80,10 +81,13 @@ int main( int argc, char **argv ) ...@@ -80,10 +81,13 @@ int main( int argc, char **argv )
case 'c': case 'c':
replyVal = uni_atoi(optarg); replyVal = uni_atoi(optarg);
if( checkArg(optind,argc,argv) )
if( checkArg(optind, argc, argv) )
replyVal2 = uni_atoi(argv[optind]); replyVal2 = uni_atoi(argv[optind]);
if( checkArg(optind+1,argc,argv) )
replyVal3 = uni_atoi(argv[optind+1]); if( checkArg(optind + 1, argc, argv) )
replyVal3 = uni_atoi(argv[optind + 1]);
break; break;
case '?': case '?':
...@@ -102,15 +106,19 @@ int main( int argc, char **argv ) ...@@ -102,15 +106,19 @@ int main( int argc, char **argv )
dlog->addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); dlog->addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
MBSlave mbs(myaddr,dev,speed,use485); MBSlave mbs(myaddr, dev, speed, use485);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
if( replyVal!=-1 )
if( replyVal != -1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
if( replyVal2!=-1 )
if( replyVal2 != -1 )
mbs.setReply2(replyVal2); mbs.setReply2(replyVal2);
if( replyVal3!=-1 )
if( replyVal3 != -1 )
mbs.setReply3(replyVal3); mbs.setReply3(replyVal3);
mbs.execute(); mbs.execute();
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
...@@ -131,7 +139,7 @@ int main( int argc, char **argv ) ...@@ -131,7 +139,7 @@ int main( int argc, char **argv )
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
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,7 +8,8 @@ ...@@ -8,7 +8,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "device", required_argument, 0, 'd' }, { "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
...@@ -30,7 +31,7 @@ static void print_help() ...@@ -30,7 +31,7 @@ static void print_help()
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;
...@@ -46,7 +47,7 @@ int main( int argc, char **argv ) ...@@ -46,7 +47,7 @@ int main( int argc, char **argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:c:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:d:s:c:", longopts, &optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
...@@ -98,24 +99,25 @@ int main( int argc, char **argv ) ...@@ -98,24 +99,25 @@ int main( int argc, char **argv )
if( f485 ) if( f485 )
{ {
ComPort485F* cp; ComPort485F* cp;
if( dev == "/dev/ttyS2" ) if( dev == "/dev/ttyS2" )
cp = new ComPort485F(dev,5); cp = new ComPort485F(dev, 5);
else if( dev == "/dev/ttyS3" ) else if( dev == "/dev/ttyS3" )
cp = new ComPort485F(dev,6); cp = new ComPort485F(dev, 6);
else else
{ {
cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl; cerr << "dev must be /dev/ttyS2 or /dev/tytS3" << endl;
return 1; 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();
......
...@@ -8,7 +8,8 @@ ...@@ -8,7 +8,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
...@@ -31,7 +32,7 @@ static void print_help() ...@@ -31,7 +32,7 @@ static void print_help()
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;
...@@ -42,13 +43,13 @@ int main( int argc, char **argv ) ...@@ -42,13 +43,13 @@ int main( int argc, char **argv )
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); ost::Thread::setException(ost::Thread::throwException);
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:p:i:brc:",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:p:i:brc:", longopts, &optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
...@@ -96,12 +97,14 @@ int main( int argc, char **argv ) ...@@ -96,12 +97,14 @@ int main( int argc, char **argv )
dlog->addLevel( Debug::ANY ); dlog->addLevel( Debug::ANY );
} }
MBTCPServer mbs(myaddr,iaddr,port,verb); MBTCPServer mbs(myaddr, iaddr, port, verb);
mbs.setLog(dlog); mbs.setLog(dlog);
mbs.setVerbose(verb); mbs.setVerbose(verb);
mbs.setIgnoreAddrMode(ignoreAddr); mbs.setIgnoreAddrMode(ignoreAddr);
if( replyVal!=-1 )
if( replyVal != -1 )
mbs.setReply(replyVal); mbs.setReply(replyVal);
mbs.execute(); mbs.execute();
} }
catch( const ModbusRTU::mbException& ex ) catch( const ModbusRTU::mbException& ex )
......
...@@ -5,5 +5,4 @@ ...@@ -5,5 +5,4 @@
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
...@@ -7,3 +7,4 @@ bin_PROGRAMS = @PACKAGE@-nullController ...@@ -7,3 +7,4 @@ bin_PROGRAMS = @PACKAGE@-nullController
@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
...@@ -13,8 +13,8 @@ NullController::NullController( ObjectId id, const string& askdump, ...@@ -13,8 +13,8 @@ NullController::NullController( ObjectId id, const string& askdump,
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;
...@@ -24,12 +24,12 @@ dumpingToDB(_dumpingToDB) ...@@ -24,12 +24,12 @@ dumpingToDB(_dumpingToDB)
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) );
*/ */
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
......
...@@ -11,11 +11,11 @@ class NullController: ...@@ -11,11 +11,11 @@ class NullController:
{ {
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();
...@@ -23,9 +23,9 @@ class NullController: ...@@ -23,9 +23,9 @@ class NullController:
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;
......
...@@ -22,33 +22,36 @@ static void short_usage() ...@@ -22,33 +22,36 @@ static void short_usage()
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 try
{ {
if( argc <=1 ) if( argc <= 1 )
{ {
cerr << "\nНе указаны необходимые параметры\n\n"; cerr << "\nНе указаны необходимые параметры\n\n";
short_usage(); short_usage();
return 0; return 0;
} }
if( !strcmp(argv[1],"--help") ) if( !strcmp(argv[1], "--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
auto conf = uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( name.empty()) if( name.empty())
{ {
cerr << "(nullController): не задан ObjectId!!! (--name)\n"; cerr << "(nullController): не задан ObjectId!!! (--name)\n";
return 0; return 0;
} }
ObjectId ID = conf->oind->getIdByName(conf->getControllersSection()+"/"+name); ObjectId ID = conf->oind->getIdByName(conf->getControllersSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(nullController): идентификатор '" << name cerr << "(nullController): идентификатор '" << name
...@@ -59,6 +62,7 @@ int main(int argc, char** argv) ...@@ -59,6 +62,7 @@ int main(int argc, char** argv)
// определяем ask-файл // определяем ask-файл
string askfile = conf->getArgParam("--askfile"); string askfile = conf->getArgParam("--askfile");
if( askfile.empty()) if( askfile.empty())
askfile = conf->getConfFileName(); askfile = conf->getConfFileName();
...@@ -71,7 +75,7 @@ int main(int argc, char** argv) ...@@ -71,7 +75,7 @@ int main(int argc, char** argv)
// надо ли писать изменения в БД // надо ли писать изменения в БД
bool dbDumping = conf->getArgInt("--dbDumping"); bool dbDumping = conf->getArgInt("--dbDumping");
auto nc = make_shared<NullController>(ID,askfile,s_field,s_fvalue,c_field,c_fvalue,dbDumping); auto nc = make_shared<NullController>(ID, askfile, s_field, s_fvalue, c_field, c_fvalue, dbDumping);
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act->add(nc); act->add(nc);
act->run(false); act->run(false);
......
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
...@@ -23,31 +23,34 @@ struct ExtInfo: ...@@ -23,31 +23,34 @@ struct ExtInfo:
UniversalIO::IOType iotype; UniversalIO::IOType iotype;
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
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 try
{ {
// help // help
// ------------------------------------- // -------------------------------------
if( argc>1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) ) if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{ {
help_print(); help_print();
return 0; return 0;
} }
// ------------------------------------- // -------------------------------------
auto conf = uniset_init(argc, argv, "configure.xml" ); auto conf = uniset_init(argc, argv, "configure.xml" );
UInterface ui(conf); UInterface ui(conf);
string sid(conf->getArgParam("--sid")); string sid(conf->getArgParam("--sid"));
if( sid.empty() ) if( sid.empty() )
{ {
cerr << endl << "Use --sid id1,..,idXX" << endl << endl; cerr << endl << "Use --sid id1,..,idXX" << endl << endl;
return 1; return 1;
} }
std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid,conf); std::list<UniSetTypes::ParamSInfo> lst = UniSetTypes::getSInfoList(sid, conf);
if( lst.empty() ) if( lst.empty() )
{ {
...@@ -56,9 +59,11 @@ int main( int argc, char **argv ) ...@@ -56,9 +59,11 @@ int main( int argc, char **argv )
} }
std::list<ExtInfo> l; std::list<ExtInfo> l;
for( std::list<UniSetTypes::ParamSInfo>::iterator it = lst.begin(); it!=lst.end(); ++it )
for( std::list<UniSetTypes::ParamSInfo>::iterator it = lst.begin(); it != lst.end(); ++it )
{ {
UniversalIO::IOType t = conf->getIOType( it->si.id ); UniversalIO::IOType t = conf->getIOType( it->si.id );
if( t != UniversalIO::AI && t != UniversalIO::AO ) if( t != UniversalIO::AI && t != UniversalIO::AO )
{ {
cerr << endl << "Неверный типа датчика '" << t << "' для id='" << it->fname << "'. Тип должен быть AI или AO." << endl << endl; cerr << endl << "Неверный типа датчика '" << t << "' для id='" << it->fname << "'. Тип должен быть AI или AO." << endl << endl;
...@@ -76,7 +81,8 @@ int main( int argc, char **argv ) ...@@ -76,7 +81,8 @@ int main( int argc, char **argv )
int amin = conf->getArgInt("--min", "0"); int amin = conf->getArgInt("--min", "0");
int amax = conf->getArgInt("--max", "100"); int amax = conf->getArgInt("--max", "100");
if( amin>amax )
if( amin > amax )
{ {
int temp = amax; int temp = amax;
amax = amin; amax = amin;
...@@ -84,14 +90,16 @@ int main( int argc, char **argv ) ...@@ -84,14 +90,16 @@ int main( int argc, char **argv )
} }
int astep = conf->getArgInt("--step", "1"); int astep = conf->getArgInt("--step", "1");
if( astep<=0 )
if( astep <= 0 )
{ {
cerr << endl << "Ошибка, используйте --step val - любое положительное число" << endl << endl; cerr << endl << "Ошибка, используйте --step val - любое положительное число" << endl << endl;
return 1; return 1;
} }
int amsec = conf->getArgInt("--pause", "200"); int amsec = conf->getArgInt("--pause", "200");
if(amsec<=10)
if(amsec <= 10)
{ {
cerr << endl << "Ошибка, используйте --pause val - любое положительное число > 10" << endl << endl; cerr << endl << "Ошибка, используйте --pause val - любое положительное число > 10" << endl << endl;
return 1; return 1;
...@@ -107,19 +115,21 @@ int main( int argc, char **argv ) ...@@ -107,19 +115,21 @@ int main( int argc, char **argv )
cout << " pause = " << amsec << endl; cout << " pause = " << amsec << endl;
cout << "------------------------------" << endl << endl; cout << "------------------------------" << endl << endl;
int i = amin-astep, j = amax; int i = amin - astep, j = amax;
while(1) while(1)
{ {
if(i>=amax) if(i >= amax)
{ {
j -= astep; j -= astep;
if(j<amin) // Принудительная установка нижней границы датчика
if(j < amin) // Принудительная установка нижней границы датчика
j = amin; j = amin;
cout << "\r" << " i = " << j <<" "<< flush;
for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it ) cout << "\r" << " i = " << j << " " << flush;
for( std::list<ExtInfo>::iterator it = l.begin(); it != l.end(); ++it )
{ {
try try
{ {
...@@ -127,11 +137,11 @@ int main( int argc, char **argv ) ...@@ -127,11 +137,11 @@ int main( int argc, char **argv )
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
cerr << endl << "save id="<< it->fname << " " << ex << endl; cerr << endl << "save id=" << it->fname << " " << ex << endl;
} }
} }
if(j<=amin) if(j <= amin)
{ {
i = amin; i = amin;
j = amax; j = amax;
...@@ -140,11 +150,13 @@ int main( int argc, char **argv ) ...@@ -140,11 +150,13 @@ int main( int argc, char **argv )
else else
{ {
i += astep; i += astep;
if(i>amax) // Принудительная установка верхней границы датчика
if(i > amax) // Принудительная установка верхней границы датчика
i = amax; i = amax;
cout << "\r" << " i = " << i <<" "<< flush;
for( std::list<ExtInfo>::iterator it=l.begin(); it!=l.end(); ++it ) cout << "\r" << " i = " << i << " " << flush;
for( std::list<ExtInfo>::iterator it = l.begin(); it != l.end(); ++it )
{ {
try try
{ {
...@@ -152,10 +164,11 @@ int main( int argc, char **argv ) ...@@ -152,10 +164,11 @@ int main( int argc, char **argv )
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
cerr << endl << "save id="<< it->fname << " " << ex << endl; cerr << endl << "save id=" << it->fname << " " << ex << endl;
} }
} }
} }
msleep(amsec); msleep(amsec);
} }
} }
......
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,25 +7,27 @@ ...@@ -7,25 +7,27 @@
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,... " cout << "Usage: uniset-smonit [ args ] --sid id1@node1,Sensor2@node2,id2,sensorname3,... "
// << " --script scriptname \n" // << " --script scriptname \n"
<< " --confile configure.xml \n"; << " --confile configure.xml \n";
return 0; return 0;
} }
auto conf = uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID(DefaultObjectId); ObjectId ID(DefaultObjectId);
string name = conf->getArgParam("--name", "TestProc"); string name = conf->getArgParam("--name", "TestProc");
ID = conf->getObjectID(name); ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(main): идентификатор '" << name cerr << "(main): идентификатор '" << name
...@@ -53,7 +55,7 @@ int main( int argc, const char **argv ) ...@@ -53,7 +55,7 @@ int main( int argc, const char **argv )
} }
catch(...) catch(...)
{ {
cout << "(main): Unknown exception!!"<< endl; cout << "(main): Unknown exception!!" << endl;
} }
return 1; return 1;
......
...@@ -6,3 +6,5 @@ bin_PROGRAMS = @PACKAGE@-sviewer-text ...@@ -6,3 +6,5 @@ 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
...@@ -11,25 +11,28 @@ static void short_usage() ...@@ -11,25 +11,28 @@ 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(); short_usage();
return 0; return 0;
} }
auto conf = uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
bool fullname = false; bool fullname = false;
if( findArgParam("--fullname",conf->getArgc(),conf->getArgv()) != -1 )
if( findArgParam("--fullname", conf->getArgc(), conf->getArgv()) != -1 )
fullname = true; fullname = true;
SViewer sv(conf->getControllersSection(),!fullname); SViewer sv(conf->getControllersSection(), !fullname);
timeout_t timeMS = conf->getArgInt("--polltime"); timeout_t timeMS = conf->getArgInt("--polltime");
if( timeMS ) if( timeMS )
{ {
cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl; cout << "(main): просматриваем с периодом " << timeMS << "[мсек]" << endl;
...@@ -46,7 +49,7 @@ int main(int argc, const char **argv) ...@@ -46,7 +49,7 @@ int main(int argc, const char **argv)
} }
catch(...) catch(...)
{ {
cerr << "(main): Неизвестное исключение!!!!"<< endl; cerr << "(main): Неизвестное исключение!!!!" << endl;
} }
return 1; 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,7 +9,8 @@ ...@@ -9,7 +9,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
...@@ -35,7 +36,7 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -35,7 +36,7 @@ int main( int argc, char* argv[], char* envp[] )
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)
{ {
...@@ -68,13 +69,14 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -68,13 +69,14 @@ int main( int argc, char* argv[], char* envp[] )
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]; char buf[10000];
while( true ) while( true )
{ {
size_t r = read(fileno(stdin), buf, sizeof(buf)-1); size_t r = read(fileno(stdin), buf, sizeof(buf) - 1);
if( r > 0 ) if( r > 0 )
{ {
buf[r] = '\0'; buf[r] = '\0';
......
...@@ -57,10 +57,10 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -57,10 +57,10 @@ int main( int argc, char* argv[], char* envp[] )
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");
...@@ -86,7 +86,8 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -86,7 +86,8 @@ int main( int argc, char* argv[], char* envp[] )
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'; buf[r] = '\0';
......
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
...@@ -50,7 +51,7 @@ static void print_help() ...@@ -50,7 +51,7 @@ static void print_help()
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;
...@@ -68,7 +69,7 @@ int main( int argc, char **argv ) ...@@ -68,7 +69,7 @@ int main( int argc, char **argv )
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)
{ {
...@@ -82,24 +83,29 @@ int main( int argc, char **argv ) ...@@ -82,24 +83,29 @@ int main( int argc, char **argv )
sdata = string(optarg); sdata = string(optarg);
} }
break; break;
case 'd': case 'd':
{ {
cmd = LogServerTypes::cmdDelLevel; cmd = LogServerTypes::cmdDelLevel;
sdata = string(optarg); sdata = string(optarg);
} }
break; break;
case 's': case 's':
{ {
cmd = LogServerTypes::cmdSetLevel; cmd = LogServerTypes::cmdSetLevel;
sdata = string(optarg); sdata = string(optarg);
} }
break; break;
case 'o': case 'o':
cmd = LogServerTypes::cmdOffLogFile; cmd = LogServerTypes::cmdOffLogFile;
break; break;
case 'n': case 'n':
cmd = LogServerTypes::cmdOnLogFile; cmd = LogServerTypes::cmdOnLogFile;
break; break;
case 'r': case 'r':
cmd = LogServerTypes::cmdRotate; cmd = LogServerTypes::cmdRotate;
break; break;
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
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;
......
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
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' }, { "help", no_argument, 0, 'h' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
...@@ -23,7 +24,7 @@ static struct option longopts[] = { ...@@ -23,7 +24,7 @@ static struct option longopts[] = {
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");
...@@ -31,7 +32,7 @@ static void print_help() ...@@ -31,7 +32,7 @@ static void print_help()
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;
...@@ -44,7 +45,7 @@ int main( int argc, char **argv ) ...@@ -44,7 +45,7 @@ int main( int argc, char **argv )
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)
{ {
...@@ -82,10 +83,10 @@ int main( int argc, char **argv ) ...@@ -82,10 +83,10 @@ int main( int argc, char **argv )
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>();
...@@ -119,12 +120,14 @@ int main( int argc, char **argv ) ...@@ -119,12 +120,14 @@ int main( int argc, char **argv )
dlog2->addLevel(Debug::ANY); dlog2->addLevel(Debug::ANY);
ls.run( addr, port, true ); ls.run( addr, port, true );
if( verb ) if( verb )
ls.setSessionLog(Debug::ANY); ls.setSessionLog(Debug::ANY);
unsigned int i=0; unsigned int i = 0;
while( true ) while( true )
// for( int n=0; n<2; n++ ) // for( int n=0; n<2; n++ )
{ {
dlog->any() << "[" << ++i << "] Test message for log" << endl; dlog->any() << "[" << ++i << "] Test message for log" << endl;
dlog->info() << ": dlog : INFO message" << endl; dlog->info() << ": dlog : INFO message" << endl;
......
...@@ -9,3 +9,4 @@ all-local: ...@@ -9,3 +9,4 @@ all-local:
chmod 'a+x' @PACKAGE@-codegen chmod 'a+x' @PACKAGE@-codegen
include $(top_builddir)/include.mk
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
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
{ {
...@@ -17,13 +17,14 @@ int main( int argc, const char **argv ) ...@@ -17,13 +17,14 @@ int main( int argc, const char **argv )
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
xmlNode* cnode = conf->getNode("Skel"); xmlNode* cnode = conf->getNode("Skel");
if( cnode == NULL ) if( cnode == NULL )
{ {
dlog.crit() << "(Skel): not found <Skel> in conffile" << endl; dlog.crit() << "(Skel): not found <Skel> in conffile" << endl;
return 1; return 1;
} }
Skel o("Skel",cnode); Skel o("Skel", cnode);
act.add(o.get_ptr()); act.add(o.get_ptr());
SystemMessage sm(SystemMessage::StartUp); SystemMessage sm(SystemMessage::StartUp);
......
...@@ -15,7 +15,7 @@ Skel::~Skel() ...@@ -15,7 +15,7 @@ Skel::~Skel()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
Skel::Skel() Skel::Skel()
{ {
cerr << "(Skel): init failed!!!!!!!!!!!!!!!"<< endl; cerr << "(Skel): init failed!!!!!!!!!!!!!!!" << endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -23,11 +23,11 @@ void Skel::step() ...@@ -23,11 +23,11 @@ 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 )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -15,8 +15,8 @@ class Skel: ...@@ -15,8 +15,8 @@ class Skel:
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:
......
...@@ -15,7 +15,7 @@ TestGen::~TestGen() ...@@ -15,7 +15,7 @@ TestGen::~TestGen()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TestGen::TestGen() TestGen::TestGen()
{ {
cerr << ": init failed!!!!!!!!!!!!!!!"<< endl; cerr << ": init failed!!!!!!!!!!!!!!!" << endl;
throw Exception(); throw Exception();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -27,13 +27,13 @@ void TestGen::step() ...@@ -27,13 +27,13 @@ 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 )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -16,8 +16,8 @@ class TestGen: ...@@ -16,8 +16,8 @@ class TestGen:
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:
......
...@@ -18,13 +18,13 @@ void TestGenAlone::step() ...@@ -18,13 +18,13 @@ 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 )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -14,8 +14,8 @@ class TestGenAlone: ...@@ -14,8 +14,8 @@ class 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:
......
...@@ -4,3 +4,4 @@ ...@@ -4,3 +4,4 @@
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)
......
...@@ -68,7 +68,7 @@ DBServer_MySQL::DBServer_MySQL(): ...@@ -68,7 +68,7 @@ DBServer_MySQL::DBServer_MySQL():
qbufSize(200), qbufSize(200),
lastRemove(false) lastRemove(false)
{ {
// init(); // init();
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -88,7 +88,7 @@ DBServer_MySQL::~DBServer_MySQL() ...@@ -88,7 +88,7 @@ DBServer_MySQL::~DBServer_MySQL()
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::sysCommand( const UniSetTypes::SystemMessage *sm ) void DBServer_MySQL::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
switch( sm->command ) switch( sm->command )
{ {
...@@ -124,15 +124,15 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -124,15 +124,15 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
data << "UPDATE " << tblName(cem->type) data << "UPDATE " << tblName(cem->type)
<< " SET confirm='" << cem->confirm << "'" << " SET confirm='" << cem->confirm << "'"
<< " WHERE sensor_id='" << cem->sensor_id << "'" << " WHERE sensor_id='" << cem->sensor_id << "'"
<< " AND date='" << dateToString(cem->time, "-")<<" '" << " AND date='" << dateToString(cem->time, "-") << " '"
<< " AND time='" << timeToString(cem->time, ":") <<" '" << " AND time='" << timeToString(cem->time, ":") << " '"
<< " AND time_usec='" << cem->time_usec <<" '"; << " AND time_usec='" << cem->time_usec << " '";
dblog << myname << "(update_confirm): " << data.str() << endl; dblog << myname << "(update_confirm): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(update_confirm): db error: "<< db->error() << endl; ucrit << myname << "(update_confirm): db error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -148,14 +148,17 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -148,14 +148,17 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
bool DBServer_MySQL::writeToBase( const string& query ) bool DBServer_MySQL::writeToBase( const string& query )
{ {
dblog << myname << "(writeToBase): " << query << endl; dblog << myname << "(writeToBase): " << query << endl;
// cout << "DBServer_MySQL: " << query << endl;
// cout << "DBServer_MySQL: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
uniset_rwmutex_wrlock l(mqbuf); uniset_rwmutex_wrlock l(mqbuf);
qbuf.push(query); qbuf.push(query);
if( qbuf.size() > qbufSize ) if( qbuf.size() > qbufSize )
{ {
std::string qlost; std::string qlost;
if( lastRemove ) if( lastRemove )
qlost = qbuf.back(); qlost = qbuf.back();
else else
...@@ -166,6 +169,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -166,6 +169,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize
<< ") overflow! lost query: " << qlost << endl; << ") overflow! lost query: " << qlost << endl;
} }
return false; return false;
} }
...@@ -180,6 +184,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -180,6 +184,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
// отдельно проверять действительно ли произошла ошибка // отдельно проверять действительно ли произошла ошибка
// см. MySQLInterface::query. // см. MySQLInterface::query.
string err(db->error()); string err(db->error());
if( err.empty() ) if( err.empty() )
return true; return true;
...@@ -200,6 +205,7 @@ void DBServer_MySQL::flushBuffer() ...@@ -200,6 +205,7 @@ void DBServer_MySQL::flushBuffer()
// отдельно проверять действительно ли произошла ошибка // отдельно проверять действительно ли произошла ошибка
// см. MySQLInterface::query. // см. MySQLInterface::query.
string err(db->error()); string err(db->error());
if( !err.empty() ) if( !err.empty() )
ucrit << myname << "(writeToBase): error: " << err << ucrit << myname << "(writeToBase): error: " << err <<
" lost query: " << qbuf.front() << endl; " lost query: " << qbuf.front() << endl;
...@@ -216,7 +222,7 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -216,7 +222,7 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si )
if( !si->tm.tv_sec ) if( !si->tm.tv_sec )
{ {
struct timezone tz; struct timezone tz;
gettimeofday( const_cast<struct timeval*>(&si->tm),&tz); gettimeofday( const_cast<struct timeval*>(&si->tm), &tz);
} }
float val = (float)si->value / (float)pow10(si->ci.precision); float val = (float)si->value / (float)pow10(si->ci.precision);
...@@ -226,8 +232,8 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -226,8 +232,8 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si )
data << "INSERT INTO " << tblName(si->type) data << "INSERT INTO " << tblName(si->type)
<< "(date, time, time_usec, sensor_id, value, node) VALUES( '" << "(date, time, time_usec, sensor_id, value, node) VALUES( '"
// Поля таблицы // Поля таблицы
<< dateToString(si->sm_tv_sec,"-") << "','" // date << dateToString(si->sm_tv_sec, "-") << "','" // date
<< timeToString(si->sm_tv_sec,":") << "','" // time << timeToString(si->sm_tv_sec, ":") << "','" // time
<< si->sm_tv_usec << "','" // time_usec << si->sm_tv_usec << "','" // time_usec
<< si->id << "','" // sensor_id << si->id << "','" // sensor_id
<< val << "','" // value << val << "','" // value
...@@ -237,7 +243,7 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -237,7 +243,7 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si )
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(insert) sensor msg error: "<< db->error() << endl; ucrit << myname << "(insert) sensor msg error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -274,27 +280,28 @@ void DBServer_MySQL::init_dbserver() ...@@ -274,27 +280,28 @@ void DBServer_MySQL::init_dbserver()
} }
xmlNode* node = conf->getNode("LocalDBServer"); xmlNode* node = conf->getNode("LocalDBServer");
if( !node ) if( !node )
throw NameNotFound(string(myname+"(init): section <LocalDBServer> not found..")); throw NameNotFound(string(myname + "(init): section <LocalDBServer> not found.."));
UniXML::iterator it(node); UniXML::iterator it(node);
dblog << myname << "(init): init connection.." << endl; dblog << myname << "(init): init connection.." << endl;
string dbname(conf->getProp(node,"dbname")); string dbname(conf->getProp(node, "dbname"));
string dbnode(conf->getProp(node,"dbnode")); string dbnode(conf->getProp(node, "dbnode"));
string user(conf->getProp(node,"dbuser")); string user(conf->getProp(node, "dbuser"));
string password(conf->getProp(node,"dbpass")); string password(conf->getProp(node, "dbpass"));
tblMap[UniSetTypes::Message::SensorInfo] = "main_history"; tblMap[UniSetTypes::Message::SensorInfo] = "main_history";
tblMap[UniSetTypes::Message::Confirm] = "main_history"; tblMap[UniSetTypes::Message::Confirm] = "main_history";
PingTime = conf->getIntProp(node,"pingTime"); PingTime = conf->getIntProp(node, "pingTime");
ReconnectTime = conf->getIntProp(node,"reconnectTime"); ReconnectTime = conf->getIntProp(node, "reconnectTime");
qbufSize = conf->getArgPInt("--dbserver-buffer-size",it.getProp("bufferSize"),200); qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), 200);
if( findArgParam("--dbserver-buffer-last-remove",conf->getArgc(),conf->getArgv()) != -1 ) if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
lastRemove = true; lastRemove = true;
else if( it.getIntProp("bufferLastRemove" ) !=0 ) else if( it.getIntProp("bufferLastRemove" ) != 0 )
lastRemove = true; lastRemove = true;
else else
lastRemove = false; lastRemove = false;
...@@ -309,44 +316,46 @@ void DBServer_MySQL::init_dbserver() ...@@ -309,44 +316,46 @@ void DBServer_MySQL::init_dbserver()
if( !db->connect(dbnode, user, password, dbname) ) if( !db->connect(dbnode, user, password, dbname) )
{ {
// ostringstream err; // ostringstream err;
ucrit << myname ucrit << myname
<< "(init): DB connection error: " << "(init): DB connection error: "
<< db->error() << endl; << db->error() << endl;
// throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) ); // throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) );
askTimer(DBServer_MySQL::ReconnectTimer,ReconnectTime); askTimer(DBServer_MySQL::ReconnectTimer, ReconnectTime);
} }
else else
{ {
dblog << myname << "(init): connect [OK]" << endl; dblog << myname << "(init): connect [OK]" << endl;
connect_ok = true; connect_ok = true;
askTimer(DBServer_MySQL::ReconnectTimer,0); askTimer(DBServer_MySQL::ReconnectTimer, 0);
askTimer(DBServer_MySQL::PingTimer,PingTime); askTimer(DBServer_MySQL::PingTimer, PingTime);
// createTables(db); // createTables(db);
initDB(db); initDB(db);
initDBTableMap(tblMap); initDBTableMap(tblMap);
flushBuffer(); flushBuffer();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::createTables( MySQLInterface *db ) void DBServer_MySQL::createTables( MySQLInterface* db )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
UniXML::iterator it( conf->getNode("Tables") ); UniXML::iterator it( conf->getNode("Tables") );
if(!it) if(!it)
{ {
ucrit << myname << ": section <Tables> not found.."<< endl; ucrit << myname << ": section <Tables> not found.." << endl;
throw Exception(); throw Exception();
} }
for( it.goChildren();it;it.goNext() ) for( it.goChildren(); it; it.goNext() )
{ {
if( it.getName() != "comment" ) if( it.getName() != "comment" )
{ {
dblog << myname << "(createTables): create " << it.getName() << endl; dblog << myname << "(createTables): create " << it.getName() << endl;
ostringstream query; ostringstream query;
query << "CREATE TABLE " << conf->getProp(it,"name") << "(" << conf->getProp(it,"create") << ")"; query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")";
if( !db->query(query.str()) ) if( !db->query(query.str()) )
ucrit << myname << "(createTables): error: \t\t" << db->error() << endl; ucrit << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
...@@ -363,8 +372,8 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -363,8 +372,8 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
uwarn << myname << "(timerInfo): DB lost connection.." << endl; uwarn << myname << "(timerInfo): DB lost connection.." << endl;
connect_ok = false; connect_ok = false;
askTimer(DBServer_MySQL::PingTimer,0); askTimer(DBServer_MySQL::PingTimer, 0);
askTimer(DBServer_MySQL::ReconnectTimer,ReconnectTime); askTimer(DBServer_MySQL::ReconnectTimer, ReconnectTime);
} }
else else
{ {
...@@ -377,14 +386,16 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -377,14 +386,16 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
case DBServer_MySQL::ReconnectTimer: case DBServer_MySQL::ReconnectTimer:
{ {
dblog << myname << "(timerInfo): reconnect timer" << endl; dblog << myname << "(timerInfo): reconnect timer" << endl;
if( db->isConnection() ) if( db->isConnection() )
{ {
if( db->ping() ) if( db->ping() )
{ {
connect_ok = true; connect_ok = true;
askTimer(DBServer_MySQL::ReconnectTimer,0); askTimer(DBServer_MySQL::ReconnectTimer, 0);
askTimer(DBServer_MySQL::PingTimer,PingTime); askTimer(DBServer_MySQL::PingTimer, PingTime);
} }
connect_ok = false; connect_ok = false;
uwarn << myname << "(timerInfo): DB no connection.." << endl; uwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
......
...@@ -144,8 +144,8 @@ class DBServer_MySQL: ...@@ -144,8 +144,8 @@ class DBServer_MySQL:
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;
...@@ -169,7 +169,7 @@ class DBServer_MySQL: ...@@ -169,7 +169,7 @@ class DBServer_MySQL:
}; };
MySQLInterface *db; MySQLInterface* db;
int PingTime; int PingTime;
int ReconnectTime; int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */ bool connect_ok; /*! признак наличия соеднинения с сервером БД */
......
...@@ -24,4 +24,6 @@ devel_includedir = $(includedir)/@PACKAGE@/mysql ...@@ -24,4 +24,6 @@ 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,13 +29,13 @@ using namespace UniSetTypes; ...@@ -29,13 +29,13 @@ 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()
...@@ -47,13 +47,14 @@ MySQLInterface::~MySQLInterface() ...@@ -47,13 +47,14 @@ MySQLInterface::~MySQLInterface()
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
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; connected = true;
return true; return true;
} }
...@@ -69,7 +70,7 @@ bool MySQLInterface::insert( const string& q ) ...@@ -69,7 +70,7 @@ 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;
...@@ -80,7 +81,7 @@ MySQLResult MySQLInterface::query( const std::string& q ) ...@@ -80,7 +81,7 @@ MySQLResult MySQLInterface::query( const std::string& q )
if( !mysql ) if( !mysql )
return MySQLResult(); return MySQLResult();
if( mysql_query(mysql,q.c_str()) ) if( mysql_query(mysql, q.c_str()) )
{ {
cerr << error() << endl; cerr << error() << endl;
return MySQLResult(); return MySQLResult();
...@@ -88,10 +89,11 @@ MySQLResult MySQLInterface::query( const std::string& q ) ...@@ -88,10 +89,11 @@ MySQLResult MySQLInterface::query( const std::string& q )
lastQ = q; lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( !res || mysql_num_rows(res)==0 )
if( !res || mysql_num_rows(res) == 0 )
return MySQLResult(); return MySQLResult();
return MySQLResult(res,true); return MySQLResult(res, true);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool MySQLInterface::query_ok( const string& q ) bool MySQLInterface::query_ok( const string& q )
...@@ -99,15 +101,17 @@ bool MySQLInterface::query_ok( const string& q ) ...@@ -99,15 +101,17 @@ bool MySQLInterface::query_ok( 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;
lastQ = q; lastQ = q;
MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows MYSQL_RES* res = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( !res || mysql_num_rows(res)==0 )
if( !res || mysql_num_rows(res) == 0 )
{ {
if( res ) if( res )
mysql_free_result(res); mysql_free_result(res);
return false; return false;
} }
...@@ -156,11 +160,13 @@ bool MySQLInterface::isConnection() ...@@ -156,11 +160,13 @@ bool MySQLInterface::isConnection()
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++ )
for( unsigned int i = 0; i < str.size(); i++ )
{ {
// if( !strcmp(str[i],'\'') ) // if( !strcmp(str[i],'\'') )
if( str[i] == '\'' ) if( str[i] == '\'' )
tmp << "\\"; tmp << "\\";
tmp << str[i]; tmp << str[i];
} }
...@@ -174,8 +180,8 @@ int num_cols( MySQLResult::iterator& it ) ...@@ -174,8 +180,8 @@ int num_cols( MySQLResult::iterator& it )
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
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] );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -224,8 +230,9 @@ MySQLResult::MySQLResult( MYSQL_RES* myres, bool finalize ) ...@@ -224,8 +230,9 @@ MySQLResult::MySQLResult( MYSQL_RES* myres, bool finalize )
while( (row = mysql_fetch_row(myres)) ) while( (row = mysql_fetch_row(myres)) )
{ {
COL c; COL c;
for( unsigned int i = 0; i<nfields; i++ )
c.push_back( (row[i]!=0 ? string(row[i]):"") ); for( unsigned int i = 0; i < nfields; i++ )
c.push_back( (row[i] != 0 ? string(row[i]) : "") );
res.push_back(c); res.push_back(c);
} }
......
...@@ -41,7 +41,7 @@ class MySQLInterface ...@@ -41,7 +41,7 @@ class MySQLInterface
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);
...@@ -76,7 +76,7 @@ class MySQLInterface ...@@ -76,7 +76,7 @@ class MySQLInterface
private: private:
MYSQL *mysql; MYSQL* mysql;
std::string lastQ; std::string lastQ;
bool connected; bool connected;
}; };
...@@ -84,8 +84,8 @@ class MySQLInterface ...@@ -84,8 +84,8 @@ class MySQLInterface
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;
...@@ -93,13 +93,28 @@ class MySQLResult ...@@ -93,13 +93,28 @@ class MySQLResult
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();
}
inline operator bool()
{
return !res.empty();
}
inline size_t size()
{
return res.size();
}
inline bool empty()
{
return res.empty();
}
protected: protected:
......
...@@ -14,20 +14,22 @@ static void short_usage() ...@@ -14,20 +14,22 @@ static void short_usage()
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 try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1], "--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
auto conf = uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
...@@ -36,7 +38,8 @@ int main(int argc, char** argv) ...@@ -36,7 +38,8 @@ int main(int argc, char** argv)
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
......
...@@ -9,6 +9,7 @@ using namespace std; ...@@ -9,6 +9,7 @@ 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 ) if( argc > 1 )
dbname = string(argv[1]); dbname = string(argv[1]);
...@@ -16,7 +17,7 @@ int main(int argc, char** argv) ...@@ -16,7 +17,7 @@ int main(int argc, char** argv)
{ {
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; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
...@@ -27,18 +28,21 @@ int main(int argc, char** argv) ...@@ -27,18 +28,21 @@ int main(int argc, char** argv)
q << "SELECT * from main_history"; q << "SELECT * from main_history";
MySQLResult r = db.query(q.str()); MySQLResult r = db.query(q.str());
if( !r ) if( !r )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
for( MySQLResult::iterator it=r.begin(); it!=r.end(); it++ ) for( MySQLResult::iterator it = r.begin(); it != r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
MySQLResult::COL col(*it); MySQLResult::COL col(*it);
for( MySQLResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
for( MySQLResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | "; cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl; cout << endl;
} }
......
...@@ -67,7 +67,7 @@ DBServer_SQLite::DBServer_SQLite(): ...@@ -67,7 +67,7 @@ DBServer_SQLite::DBServer_SQLite():
qbufSize(200), qbufSize(200),
lastRemove(false) lastRemove(false)
{ {
// init(); // init();
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
{ {
ostringstream msg; ostringstream msg;
...@@ -86,7 +86,7 @@ DBServer_SQLite::~DBServer_SQLite() ...@@ -86,7 +86,7 @@ DBServer_SQLite::~DBServer_SQLite()
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::sysCommand( const UniSetTypes::SystemMessage *sm ) void DBServer_SQLite::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
DBServer::sysCommand(sm); DBServer::sysCommand(sm);
...@@ -123,15 +123,15 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -123,15 +123,15 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
data << "UPDATE " << tblName(cem->type) data << "UPDATE " << tblName(cem->type)
<< " SET confirm='" << cem->confirm << "'" << " SET confirm='" << cem->confirm << "'"
<< " WHERE sensor_id='" << cem->sensor_id << "'" << " WHERE sensor_id='" << cem->sensor_id << "'"
<< " AND date='" << dateToString(cem->time, "-")<<" '" << " AND date='" << dateToString(cem->time, "-") << " '"
<< " AND time='" << timeToString(cem->time, ":") <<" '" << " AND time='" << timeToString(cem->time, ":") << " '"
<< " AND time_usec='" << cem->time_usec <<" '"; << " AND time_usec='" << cem->time_usec << " '";
dblog << myname << "(update_confirm): " << data.str() << endl; dblog << myname << "(update_confirm): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(update_confirm): db error: "<< db->error() << endl; ucrit << myname << "(update_confirm): db error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -147,14 +147,17 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -147,14 +147,17 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
bool DBServer_SQLite::writeToBase( const string& query ) bool DBServer_SQLite::writeToBase( const string& query )
{ {
dblog << myname << "(writeToBase): " << query << endl; dblog << myname << "(writeToBase): " << query << endl;
// cout << "DBServer_SQLite: " << query << endl;
// cout << "DBServer_SQLite: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
uniset_rwmutex_wrlock l(mqbuf); uniset_rwmutex_wrlock l(mqbuf);
qbuf.push(query); qbuf.push(query);
if( qbuf.size() > qbufSize ) if( qbuf.size() > qbufSize )
{ {
std::string qlost; std::string qlost;
if( lastRemove ) if( lastRemove )
qlost = qbuf.back(); qlost = qbuf.back();
else else
...@@ -165,6 +168,7 @@ bool DBServer_SQLite::writeToBase( const string& query ) ...@@ -165,6 +168,7 @@ bool DBServer_SQLite::writeToBase( const string& query )
ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize
<< ") overflow! lost query: " << qlost << endl; << ") overflow! lost query: " << qlost << endl;
} }
return false; return false;
} }
...@@ -190,11 +194,12 @@ void DBServer_SQLite::flushBuffer() ...@@ -190,11 +194,12 @@ void DBServer_SQLite::flushBuffer()
ucrit << myname << "(writeToBase): error: " << db->error() << ucrit << myname << "(writeToBase): error: " << db->error() <<
" lost query: " << qbuf.front() << endl; " lost query: " << qbuf.front() << endl;
} }
qbuf.pop(); qbuf.pop();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si ) void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage* si )
{ {
try try
{ {
...@@ -202,7 +207,7 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si ) ...@@ -202,7 +207,7 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si )
if( !si->tm.tv_sec ) if( !si->tm.tv_sec )
{ {
struct timezone tz; struct timezone tz;
gettimeofday(const_cast<struct timeval*>(&si->tm),&tz); gettimeofday(const_cast<struct timeval*>(&si->tm), &tz);
} }
float val = (float)si->value / (float)pow10(si->ci.precision); float val = (float)si->value / (float)pow10(si->ci.precision);
...@@ -212,8 +217,8 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si ) ...@@ -212,8 +217,8 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si )
data << "INSERT INTO " << tblName(si->type) data << "INSERT INTO " << tblName(si->type)
<< "(date, time, time_usec, sensor_id, value, node) VALUES( '" << "(date, time, time_usec, sensor_id, value, node) VALUES( '"
// Поля таблицы // Поля таблицы
<< dateToString(si->sm_tv_sec,"-") << "','" // date << dateToString(si->sm_tv_sec, "-") << "','" // date
<< timeToString(si->sm_tv_sec,":") << "','" // time << timeToString(si->sm_tv_sec, ":") << "','" // time
<< si->sm_tv_usec << "'," // time_usec << si->sm_tv_usec << "'," // time_usec
<< si->id << "','" // sensor_id << si->id << "','" // sensor_id
<< val << "','" // value << val << "','" // value
...@@ -223,7 +228,7 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si ) ...@@ -223,7 +228,7 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage *si )
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(insert) sensor msg error: "<< db->error() << endl; ucrit << myname << "(insert) sensor msg error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -260,24 +265,25 @@ void DBServer_SQLite::init_dbserver() ...@@ -260,24 +265,25 @@ void DBServer_SQLite::init_dbserver()
} }
xmlNode* node = conf->getNode("LocalDBServer"); xmlNode* node = conf->getNode("LocalDBServer");
if( !node ) if( !node )
throw NameNotFound(string(myname+"(init): section <LocalDBServer> not found..")); throw NameNotFound(string(myname + "(init): section <LocalDBServer> not found.."));
UniXML::iterator it(node); UniXML::iterator it(node);
dblog << myname << "(init): init connection.." << endl; dblog << myname << "(init): init connection.." << endl;
string dbfile(conf->getProp(node,"dbfile")); string dbfile(conf->getProp(node, "dbfile"));
tblMap[UniSetTypes::Message::SensorInfo] = "main_history"; tblMap[UniSetTypes::Message::SensorInfo] = "main_history";
tblMap[UniSetTypes::Message::Confirm] = "main_history"; tblMap[UniSetTypes::Message::Confirm] = "main_history";
PingTime = conf->getIntProp(node,"pingTime"); PingTime = conf->getIntProp(node, "pingTime");
ReconnectTime = conf->getIntProp(node,"reconnectTime"); ReconnectTime = conf->getIntProp(node, "reconnectTime");
qbufSize = conf->getArgPInt("--dbserver-buffer-size",it.getProp("bufferSize"),200); qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), 200);
if( findArgParam("--dbserver-buffer-last-remove",conf->getArgc(),conf->getArgv()) != -1 ) if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
lastRemove = true; lastRemove = true;
else if( it.getIntProp("bufferLastRemove" ) !=0 ) else if( it.getIntProp("bufferLastRemove" ) != 0 )
lastRemove = true; lastRemove = true;
else else
lastRemove = false; lastRemove = false;
...@@ -286,45 +292,47 @@ void DBServer_SQLite::init_dbserver() ...@@ -286,45 +292,47 @@ void DBServer_SQLite::init_dbserver()
<< " pingTime=" << PingTime << " pingTime=" << PingTime
<< " ReconnectTime=" << ReconnectTime << endl; << " ReconnectTime=" << ReconnectTime << endl;
if( !db->connect(dbfile,false) ) if( !db->connect(dbfile, false) )
{ {
// ostringstream err; // ostringstream err;
ucrit << myname ucrit << myname
<< "(init): DB connection error: " << "(init): DB connection error: "
<< db->error() << endl; << db->error() << endl;
// throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) ); // throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) );
askTimer(DBServer_SQLite::ReconnectTimer,ReconnectTime); askTimer(DBServer_SQLite::ReconnectTimer, ReconnectTime);
} }
else else
{ {
dblog << myname << "(init): connect [OK]" << endl; dblog << myname << "(init): connect [OK]" << endl;
connect_ok = true; connect_ok = true;
askTimer(DBServer_SQLite::ReconnectTimer,0); askTimer(DBServer_SQLite::ReconnectTimer, 0);
askTimer(DBServer_SQLite::PingTimer,PingTime); askTimer(DBServer_SQLite::PingTimer, PingTime);
// createTables(db); // createTables(db);
initDB(db); initDB(db);
initDBTableMap(tblMap); initDBTableMap(tblMap);
flushBuffer(); flushBuffer();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::createTables( SQLiteInterface *db ) void DBServer_SQLite::createTables( SQLiteInterface* db )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
UniXML::iterator it( conf->getNode("Tables") ); UniXML::iterator it( conf->getNode("Tables") );
if(!it) if(!it)
{ {
ucrit << myname << ": section <Tables> not found.."<< endl; ucrit << myname << ": section <Tables> not found.." << endl;
throw Exception(); throw Exception();
} }
for( it.goChildren();it;it.goNext() ) for( it.goChildren(); it; it.goNext() )
{ {
if( it.getName() != "comment" ) if( it.getName() != "comment" )
{ {
dblog << myname << "(createTables): create " << it.getName() << endl; dblog << myname << "(createTables): create " << it.getName() << endl;
ostringstream query; ostringstream query;
query << "CREATE TABLE " << conf->getProp(it,"name") << "(" << conf->getProp(it,"create") << ")"; query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")";
if( !db->query(query.str()) ) if( !db->query(query.str()) )
ucrit << myname << "(createTables): error: \t\t" << db->error() << endl; ucrit << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
...@@ -341,8 +349,8 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -341,8 +349,8 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
uwarn << myname << "(timerInfo): DB lost connection.." << endl; uwarn << myname << "(timerInfo): DB lost connection.." << endl;
connect_ok = false; connect_ok = false;
askTimer(DBServer_SQLite::PingTimer,0); askTimer(DBServer_SQLite::PingTimer, 0);
askTimer(DBServer_SQLite::ReconnectTimer,ReconnectTime); askTimer(DBServer_SQLite::ReconnectTimer, ReconnectTime);
} }
else else
{ {
...@@ -355,14 +363,16 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -355,14 +363,16 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
case DBServer_SQLite::ReconnectTimer: case DBServer_SQLite::ReconnectTimer:
{ {
dblog << myname << "(timerInfo): reconnect timer" << endl; dblog << myname << "(timerInfo): reconnect timer" << endl;
if( db->isConnection() ) if( db->isConnection() )
{ {
if( db->ping() ) if( db->ping() )
{ {
connect_ok = true; connect_ok = true;
askTimer(DBServer_SQLite::ReconnectTimer,0); askTimer(DBServer_SQLite::ReconnectTimer, 0);
askTimer(DBServer_SQLite::PingTimer,PingTime); askTimer(DBServer_SQLite::PingTimer, PingTime);
} }
connect_ok = false; connect_ok = false;
uwarn << myname << "(timerInfo): DB no connection.." << endl; uwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
......
...@@ -144,8 +144,8 @@ class DBServer_SQLite: ...@@ -144,8 +144,8 @@ class DBServer_SQLite:
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;
...@@ -169,7 +169,7 @@ class DBServer_SQLite: ...@@ -169,7 +169,7 @@ class DBServer_SQLite:
}; };
SQLiteInterface *db; SQLiteInterface* db;
int PingTime; int PingTime;
int ReconnectTime; int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */ bool connect_ok; /*! признак наличия соеднинения с сервером БД */
......
...@@ -25,5 +25,7 @@ devel_includedir = $(includedir)/@PACKAGE@/sqlite ...@@ -25,5 +25,7 @@ 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
...@@ -31,13 +31,13 @@ using namespace UniSetTypes; ...@@ -31,13 +31,13 @@ using namespace UniSetTypes;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
SQLiteInterface::SQLiteInterface(): SQLiteInterface::SQLiteInterface():
db(0), db(0),
lastQ(""), lastQ(""),
lastE(""), lastE(""),
queryok(false), queryok(false),
connected(false), connected(false),
opTimeout(300), opTimeout(300),
opCheckPause(50) opCheckPause(50)
{ {
} }
...@@ -49,14 +49,14 @@ SQLiteInterface::~SQLiteInterface() ...@@ -49,14 +49,14 @@ SQLiteInterface::~SQLiteInterface()
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::ping() bool SQLiteInterface::ping()
{ {
return db && ( sqlite3_db_status(db,0,NULL,NULL,0) == SQLITE_OK ); return db && ( sqlite3_db_status(db, 0, NULL, NULL, 0) == SQLITE_OK );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::connect( const string& dbfile, bool create ) bool SQLiteInterface::connect( const string& dbfile, bool create )
{ {
// т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами" // т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами"
// if( !create && !UniSetTypes::file_exist(dbfile) ) // if( !create && !UniSetTypes::file_exist(dbfile) )
// return false; // return false;
int flags = create ? 0 : SQLITE_OPEN_READWRITE; int flags = create ? 0 : SQLITE_OPEN_READWRITE;
...@@ -91,8 +91,9 @@ bool SQLiteInterface::close() ...@@ -91,8 +91,9 @@ bool SQLiteInterface::close()
void SQLiteInterface::setOperationTimeout( timeout_t msec ) void SQLiteInterface::setOperationTimeout( timeout_t msec )
{ {
opTimeout = msec; opTimeout = msec;
if( db ) if( db )
sqlite3_busy_timeout(db,opTimeout); sqlite3_busy_timeout(db, opTimeout);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::insert( const string& q ) bool SQLiteInterface::insert( const string& q )
...@@ -120,13 +121,13 @@ bool SQLiteInterface::insert( const string& q ) ...@@ -120,13 +121,13 @@ bool SQLiteInterface::insert( const string& q )
} }
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
queryok=true; queryok = true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::checkResult( int rc ) bool SQLiteInterface::checkResult( int rc )
{ {
if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED || rc==SQLITE_INTERRUPT || rc==SQLITE_IOERR ) if( rc == SQLITE_BUSY || rc == SQLITE_LOCKED || rc == SQLITE_INTERRUPT || rc == SQLITE_IOERR )
return false; return false;
return true; return true;
...@@ -143,6 +144,7 @@ SQLiteResult SQLiteInterface::query( const string& q ) ...@@ -143,6 +144,7 @@ SQLiteResult SQLiteInterface::query( const string& q )
// Компилируем SQL запрос // Компилируем SQL запрос
sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL); sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL);
int rc = sqlite3_step(pStmt); int rc = sqlite3_step(pStmt);
if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) ) if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) )
{ {
sqlite3_finalize(pStmt); sqlite3_finalize(pStmt);
...@@ -151,17 +153,19 @@ SQLiteResult SQLiteInterface::query( const string& q ) ...@@ -151,17 +153,19 @@ SQLiteResult SQLiteInterface::query( const string& q )
} }
lastQ = q; lastQ = q;
queryok=true; queryok = true;
return SQLiteResult(pStmt,true); return SQLiteResult(pStmt, true);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result ) bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result )
{ {
PassiveTimer ptTimeout(opTimeout); PassiveTimer ptTimeout(opTimeout);
while( !ptTimeout.checkTime() ) while( !ptTimeout.checkTime() )
{ {
sqlite3_reset(stmt); sqlite3_reset(stmt);
int rc = sqlite3_step(stmt); int rc = sqlite3_step(stmt);
if( rc == result || rc == SQLITE_DONE ) if( rc == result || rc == SQLITE_DONE )
return true; return true;
...@@ -204,8 +208,8 @@ int num_cols( SQLiteResult::iterator& it ) ...@@ -204,8 +208,8 @@ int num_cols( SQLiteResult::iterator& it )
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
int as_int( SQLiteResult::iterator& it, int col ) int as_int( SQLiteResult::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] );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -251,23 +255,27 @@ SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize ) ...@@ -251,23 +255,27 @@ SQLiteResult::SQLiteResult( sqlite3_stmt* s, bool finalize )
do do
{ {
int n = sqlite3_data_count(s); int n = sqlite3_data_count(s);
if( n<=0 )
if( n <= 0 )
{ {
if( finalize ) if( finalize )
sqlite3_finalize(s); sqlite3_finalize(s);
return; return;
} }
COL c; COL c;
for( int i=0; i<n; i++ ) for( int i = 0; i < n; i++ )
{ {
char* p = (char*)sqlite3_column_text(s,i); char* p = (char*)sqlite3_column_text(s, i);
if( p ) if( p )
c.push_back(p); c.push_back(p);
else else
c.push_back(""); c.push_back("");
} }
res.push_back(c); res.push_back(c);
} }
while( sqlite3_step(s) == SQLITE_ROW ); while( sqlite3_step(s) == SQLITE_ROW );
......
...@@ -96,10 +96,19 @@ class SQLiteInterface ...@@ -96,10 +96,19 @@ class SQLiteInterface
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();
...@@ -131,8 +140,8 @@ class SQLiteInterface ...@@ -131,8 +140,8 @@ class SQLiteInterface
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;
...@@ -140,13 +149,28 @@ class SQLiteResult ...@@ -140,13 +149,28 @@ class SQLiteResult
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 iterator end()
{
return res.end();
}
inline operator bool(){ return !res.empty(); } inline operator bool()
{
return !res.empty();
}
inline int size(){ return res.size(); } inline int size()
inline bool empty(){ return res.empty(); } {
return res.size();
}
inline bool empty()
{
return res.empty();
}
protected: protected:
......
...@@ -14,20 +14,22 @@ static void short_usage() ...@@ -14,20 +14,22 @@ static void short_usage()
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 try
{ {
if( argc > 1 && !strcmp(argv[1],"--help") ) if( argc > 1 && !strcmp(argv[1], "--help") )
{ {
short_usage(); short_usage();
return 0; return 0;
} }
auto conf = uniset_init(argc,argv,"configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID = conf->getDBServer(); ObjectId ID = conf->getDBServer();
// определяем ID объекта // определяем ID объекта
string name = conf->getArgParam("--name"); string name = conf->getArgParam("--name");
if( !name.empty()) if( !name.empty())
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
...@@ -36,7 +38,8 @@ int main(int argc, char** argv) ...@@ -36,7 +38,8 @@ int main(int argc, char** argv)
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
......
...@@ -11,6 +11,7 @@ int main(int argc, char** argv) ...@@ -11,6 +11,7 @@ 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; cerr << "db connect error: " << db.error() << endl;
...@@ -21,18 +22,21 @@ int main(int argc, char** argv) ...@@ -21,18 +22,21 @@ int main(int argc, char** argv)
q << "SELECT * from main_history"; q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str()); SQLiteResult r = db.query(q.str());
if( !r ) if( !r )
{ {
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
for( SQLiteResult::iterator it=r.begin(); it!=r.end(); it++ ) for( SQLiteResult::iterator it = r.begin(); it != r.end(); it++ )
{ {
cout << "ROW: "; cout << "ROW: ";
SQLiteResult::COL col(*it); SQLiteResult::COL col(*it);
for( SQLiteResult::COL::iterator cit = it->begin(); cit!=it->end(); cit++ )
for( SQLiteResult::COL::iterator cit = it->begin(); cit != it->end(); cit++ )
cout << as_string(cit) << "(" << as_double(cit) << ") | "; cout << as_string(cit) << "(" << as_double(cit) << ") | ";
cout << endl; cout << endl;
} }
......
...@@ -11,6 +11,7 @@ ComediInterface::ComediInterface( const std::string& dev ): ...@@ -11,6 +11,7 @@ ComediInterface::ComediInterface( const std::string& dev ):
dname(dev) dname(dev)
{ {
card = comedi_open(dev.c_str()); card = comedi_open(dev.c_str());
if( card == 0 ) if( card == 0 )
{ {
ostringstream err; ostringstream err;
...@@ -25,15 +26,16 @@ ComediInterface::~ComediInterface() ...@@ -25,15 +26,16 @@ ComediInterface::~ComediInterface()
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int ComediInterface::getAnalogChannel( int subdev, int channel, int range, int aref ) int ComediInterface::getAnalogChannel( int subdev, int channel, int range, int aref )
throw(UniSetTypes::Exception) throw(UniSetTypes::Exception)
{ {
lsampl_t data = 0; lsampl_t data = 0;
int ret = comedi_data_read(card, subdev, channel, range, aref, &data); int ret = comedi_data_read(card, subdev, channel, range, aref, &data);
if( ret < 0 ) if( ret < 0 )
{ {
ostringstream err; ostringstream err;
err << "(ComediInterface:getAnalogChannel): can`t read data from subdev=" << subdev err << "(ComediInterface:getAnalogChannel): can`t read data from subdev=" << subdev
<< " channel=" << channel << " range=" << range <<" aref="<< aref << " channel=" << channel << " range=" << range << " aref=" << aref
<< " dev=" << dname << " dev=" << dname
<< " err: " << ret << " (" << strerror(ret) << ")"; << " err: " << ret << " (" << strerror(ret) << ")";
throw Exception(err.str()); throw Exception(err.str());
...@@ -43,7 +45,7 @@ int ComediInterface::getAnalogChannel( int subdev, int channel, int range, int a ...@@ -43,7 +45,7 @@ int ComediInterface::getAnalogChannel( int subdev, int channel, int range, int a
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void ComediInterface::setAnalogChannel( int subdev, int channel, int data, int range, int aref ) void ComediInterface::setAnalogChannel( int subdev, int channel, int data, int range, int aref )
throw(UniSetTypes::Exception) throw(UniSetTypes::Exception)
{ {
if( comedi_data_write(card, subdev, channel, range, aref, data) < 0 ) if( comedi_data_write(card, subdev, channel, range, aref, data) < 0 )
{ {
...@@ -72,9 +74,9 @@ bool ComediInterface::getDigitalChannel( int subdev, int channel ) throw(UniSetT ...@@ -72,9 +74,9 @@ bool ComediInterface::getDigitalChannel( int subdev, int channel ) throw(UniSetT
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void ComediInterface::setDigitalChannel( int subdev, int channel, bool bit ) void ComediInterface::setDigitalChannel( int subdev, int channel, bool bit )
throw(UniSetTypes::Exception) throw(UniSetTypes::Exception)
{ {
if( comedi_dio_write(card, subdev, channel,bit) < 0 ) if( comedi_dio_write(card, subdev, channel, bit) < 0 )
{ {
ostringstream err; ostringstream err;
err << "(ComediInterface:setDigitalChannel): can`t write bit=" << bit err << "(ComediInterface:setDigitalChannel): can`t write bit=" << bit
...@@ -85,14 +87,14 @@ void ComediInterface::setDigitalChannel( int subdev, int channel, bool bit ) ...@@ -85,14 +87,14 @@ void ComediInterface::setDigitalChannel( int subdev, int channel, bool bit )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void ComediInterface::configureChannel( int subdev, int channel, ChannelType t, void ComediInterface::configureChannel( int subdev, int channel, ChannelType t,
int range, int aref ) int range, int aref )
throw(UniSetTypes::Exception) throw(UniSetTypes::Exception)
{ {
switch( t ) switch( t )
{ {
case ComediInterface::DI: case ComediInterface::DI:
case ComediInterface::DO: case ComediInterface::DO:
{ {
if( comedi_dio_config(card,subdev,channel,t) < 0 ) if( comedi_dio_config(card, subdev, channel, t) < 0 )
{ {
ostringstream err; ostringstream err;
err << "(ComediInterface:configureChannel): can`t configure (DIO) " err << "(ComediInterface:configureChannel): can`t configure (DIO) "
...@@ -110,16 +112,16 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t, ...@@ -110,16 +112,16 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t,
{ {
lsampl_t data[2]; lsampl_t data[2];
comedi_insn insn; comedi_insn insn;
memset(&insn,0,sizeof(insn)); memset(&insn, 0, sizeof(insn));
insn.insn = INSN_CONFIG; insn.insn = INSN_CONFIG;
insn.n = 2; insn.n = 2;
insn.data = data; insn.data = data;
insn.subdev = subdev; insn.subdev = subdev;
insn.chanspec = CR_PACK(channel,range,aref); insn.chanspec = CR_PACK(channel, range, aref);
data[0] = t; data[0] = t;
data[1] = t; data[1] = t;
if( comedi_do_insn(card,&insn) < 0 ) if( comedi_do_insn(card, &insn) < 0 )
{ {
ostringstream err; ostringstream err;
err << "(ComediInterface:configureChannel): can`t configure (AIO) " err << "(ComediInterface:configureChannel): can`t configure (AIO) "
...@@ -127,6 +129,7 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t, ...@@ -127,6 +129,7 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t,
<< " dev=" << dname; << " dev=" << dname;
throw Exception(err.str()); throw Exception(err.str());
} }
return; return;
} }
break; break;
...@@ -143,11 +146,11 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t, ...@@ -143,11 +146,11 @@ void ComediInterface::configureChannel( int subdev, int channel, ChannelType t,
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void ComediInterface::configureSubdev( int subdev, SubdevType type ) void ComediInterface::configureSubdev( int subdev, SubdevType type )
throw(UniSetTypes::Exception) throw(UniSetTypes::Exception)
{ {
lsampl_t data[2]; lsampl_t data[2];
comedi_insn insn; comedi_insn insn;
memset(&insn,0,sizeof(insn)); memset(&insn, 0, sizeof(insn));
insn.insn = INSN_CONFIG; insn.insn = INSN_CONFIG;
insn.n = 2; insn.n = 2;
insn.data = data; insn.data = data;
...@@ -157,7 +160,7 @@ void ComediInterface::configureSubdev( int subdev, SubdevType type ) ...@@ -157,7 +160,7 @@ void ComediInterface::configureSubdev( int subdev, SubdevType type )
data[0] = 102; data[0] = 102;
data[1] = type; data[1] = type;
if( comedi_do_insn(card,&insn) < 0 ) if( comedi_do_insn(card, &insn) < 0 )
{ {
ostringstream err; ostringstream err;
err << "(ComediInterface:configureSubdev): can`t configure subdev " err << "(ComediInterface:configureSubdev): can`t configure subdev "
......
...@@ -13,10 +13,10 @@ class ComediInterface ...@@ -13,10 +13,10 @@ class ComediInterface
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 )
...@@ -50,10 +50,13 @@ class ComediInterface ...@@ -50,10 +50,13 @@ class ComediInterface
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:
......
...@@ -168,16 +168,19 @@ class CardList: ...@@ -168,16 +168,19 @@ class CardList:
{ {
public: public:
CardList(int size) : std::vector<ComediInterface*>(size) { } CardList(int size) : std::vector<ComediInterface * >(size) { }
~CardList() { ~CardList()
for( unsigned int i=0; i<size(); i++ ) {
for( unsigned int i = 0; i < size(); i++ )
delete (*this)[i]; delete (*this)[i];
} }
inline ComediInterface* getCard(int ncard) { inline ComediInterface* getCard(int ncard)
{
if( ncard >= 0 && ncard < (int)size() ) if( ncard >= 0 && ncard < (int)size() )
return (*this)[ncard]; return (*this)[ncard];
return NULL; return NULL;
} }
...@@ -202,13 +205,13 @@ class IOControl: ...@@ -202,13 +205,13 @@ class IOControl:
public UniSetObject public UniSetObject
{ {
public: public:
IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, const std::shared_ptr<SharedMemory> shm=nullptr, int numcards=2, const std::string& prefix="io" ); IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, const std::shared_ptr<SharedMemory> shm = nullptr, int numcards = 2, const std::string& prefix = "io" );
virtual ~IOControl(); virtual ~IOControl();
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<IOControl> init_iocontrol( int argc, const char* const* argv, static std::shared_ptr<IOControl> init_iocontrol( int argc, const char* const* argv,
UniSetTypes::ObjectId icID, const std::shared_ptr<SharedMemory> ic=nullptr, UniSetTypes::ObjectId icID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="io" ); const std::string& prefix = "io" );
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
...@@ -224,7 +227,7 @@ class IOControl: ...@@ -224,7 +227,7 @@ class IOControl:
IOInfo& operator=(IOInfo&& r) = default; IOInfo& operator=(IOInfo&& r) = default;
IOInfo(): IOInfo():
subdev(DefaultSubdev),channel(DefaultChannel), subdev(DefaultSubdev), channel(DefaultChannel),
ncard(-1), ncard(-1),
aref(0), aref(0),
range(0), range(0),
...@@ -266,7 +269,7 @@ class IOControl: ...@@ -266,7 +269,7 @@ class IOControl:
struct IOPriority struct IOPriority
{ {
IOPriority(int p, int i): IOPriority(int p, int i):
priority(p),index(i){} priority(p), index(i) {}
int priority; int priority;
int index; int index;
...@@ -314,7 +317,7 @@ class IOControl: ...@@ -314,7 +317,7 @@ class IOControl:
void waitSM(); void waitSM();
bool checkCards( const std::string& func="" ); bool checkCards( const std::string& func = "" );
xmlNode* cnode; /*!< xml-узел в настроечном файле */ xmlNode* cnode; /*!< xml-узел в настроечном файле */
......
...@@ -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,14 +9,15 @@ using namespace UniSetTypes; ...@@ -9,14 +9,15 @@ 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 )
if( argc > 1 && strcmp(argv[1], "--help") == 0 )
{ {
cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl; cout << "--io-confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl; cout << "--io-logfile fname - выводить логи в файл fname. По умолчанию iocontrol.log" << endl;
IOControl::help_print(argc,argv); IOControl::help_print(argc, argv);
return 0; return 0;
} }
...@@ -24,13 +25,14 @@ int main(int argc, const char **argv) ...@@ -24,13 +25,14 @@ int main(int argc, const char **argv)
{ {
auto conf = uniset_init(argc, argv); auto conf = uniset_init(argc, argv);
string logfilename = conf->getArgParam("--io-logfile","iocontrol.log"); string logfilename = conf->getArgParam("--io-logfile", "iocontrol.log");
string logname( conf->getLogDir() + logfilename ); string logname( conf->getLogDir() + logfilename );
dlog()->logFile( logname ); dlog()->logFile( logname );
ulog()->logFile( logname ); ulog()->logFile( logname );
ObjectId shmID = DefaultObjectId; ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id"); string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() ) if( !sID.empty() )
shmID = conf->getControllerID(sID); shmID = conf->getControllerID(sID);
else else
...@@ -44,7 +46,8 @@ int main(int argc, const char **argv) ...@@ -44,7 +46,8 @@ int main(int argc, const char **argv)
} }
auto ic = IOControl::init_iocontrol(argc,argv,shmID); auto ic = IOControl::init_iocontrol(argc, argv, shmID);
if( !ic ) if( !ic )
{ {
dcrit << "(iocontrol): init не прошёл..." << endl; dcrit << "(iocontrol): init не прошёл..." << endl;
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
using namespace std; using namespace std;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
const Element::ElementID Element::DefaultElementID="?id?"; const Element::ElementID Element::DefaultElementID = "?id?";
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addChildOut( Element* el, int num ) void Element::addChildOut( Element* el, int num )
...@@ -17,7 +17,7 @@ void Element::addChildOut( Element* el, int num ) ...@@ -17,7 +17,7 @@ void Element::addChildOut( Element* el, int num )
} }
for( auto &it: outs ) for( auto& it : outs )
{ {
if( it.el == el ) if( it.el == el )
{ {
...@@ -37,12 +37,12 @@ void Element::addChildOut( Element* el, int num ) ...@@ -37,12 +37,12 @@ void Element::addChildOut( Element* el, int num )
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
outs.push_front(ChildInfo(el,num)); outs.push_front(ChildInfo(el, num));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delChildOut( Element* el ) void Element::delChildOut( Element* el )
{ {
for( auto it=outs.begin(); it!=outs.end(); ++it ) for( auto it = outs.begin(); it != outs.end(); ++it )
{ {
if( it->el == el ) if( it->el == el )
{ {
...@@ -56,24 +56,26 @@ void Element::delChildOut( Element* el ) ...@@ -56,24 +56,26 @@ void Element::delChildOut( Element* el )
void Element::setChildOut() void Element::setChildOut()
{ {
bool _myout(getOut()); bool _myout(getOut());
for( auto &it: outs )
for( auto& it : outs )
{ {
// try // try
// { // {
it.el->setIn(it.num,_myout); it.el->setIn(it.num, _myout);
// } // }
// catch(...){} // catch(...){}
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Element::find( ElementID id ) Element* Element::find( ElementID id )
{ {
for( auto &it: outs ) for( auto& it : outs )
{ {
if( it.el->getId() == id ) if( it.el->getId() == id )
return it.el; return it.el;
Element* el( it.el->find(id) ); Element* el( it.el->find(id) );
if( el != NULL ) if( el != NULL )
return el; return el;
} }
...@@ -83,7 +85,7 @@ Element* Element::find( ElementID id ) ...@@ -83,7 +85,7 @@ Element* Element::find( ElementID id )
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::addInput(int num, bool state) void Element::addInput(int num, bool state)
{ {
for( auto &it: ins ) for( auto& it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
...@@ -93,12 +95,12 @@ void Element::addInput(int num, bool state) ...@@ -93,12 +95,12 @@ void Element::addInput(int num, bool state)
} }
} }
ins.push_front(InputInfo(num,state)); ins.push_front(InputInfo(num, state));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Element::delInput( int num ) void Element::delInput( int num )
{ {
for( auto it=ins.begin(); it!=ins.end(); ++it ) for( auto it = ins.begin(); it != ins.end(); ++it )
{ {
if( it->num == num ) if( it->num == num )
{ {
......
...@@ -11,8 +11,8 @@ class LogicException: ...@@ -11,8 +11,8 @@ class LogicException:
public UniSetTypes::Exception public UniSetTypes::Exception
{ {
public: public:
LogicException():UniSetTypes::Exception("LogicException"){} LogicException(): UniSetTypes::Exception("LogicException") {}
LogicException(std::string err):UniSetTypes::Exception(err){} LogicException(std::string err): UniSetTypes::Exception(err) {}
}; };
...@@ -30,32 +30,44 @@ class Element ...@@ -30,32 +30,44 @@ class Element
internal internal
}; };
Element( ElementID id ):myid(id){}; Element( ElementID id ): myid(id) {};
virtual ~Element(){}; virtual ~Element() {};
/*!< функция вызываемая мастером для элементов, которым требуется /*!< функция вызываемая мастером для элементов, которым требуется
работа во времени. работа во времени.
По умолчанию ничего не делает. По умолчанию ничего не делает.
*/ */
virtual void tick(){} virtual void tick() {}
virtual void setIn( int num, bool state ) = 0; virtual void setIn( int num, bool state ) = 0;
virtual bool getOut() = 0; virtual bool getOut() = 0;
inline ElementID getId(){ return myid; } inline ElementID getId()
virtual std::string getType(){ return "?type?"; } {
return myid;
}
virtual std::string getType()
{
return "?type?";
}
virtual Element* find( ElementID id ); virtual Element* find( ElementID id );
virtual void addChildOut( Element* el, int in_num ); virtual void addChildOut( Element* el, int in_num );
virtual void delChildOut( Element* el ); virtual void delChildOut( Element* el );
inline int outCount(){ return outs.size(); } inline int outCount()
{
return outs.size();
}
virtual void addInput( int num, bool state=false ); virtual void addInput( int num, bool state = false );
virtual void delInput( int num ); virtual void delInput( int num );
inline int inCount(){ return ins.size(); } inline int inCount()
{
return ins.size();
}
friend std::ostream& operator<<(std::ostream& os, Element& el ) friend std::ostream& operator<<(std::ostream& os, Element& el )
{ {
...@@ -68,13 +80,13 @@ class Element ...@@ -68,13 +80,13 @@ class Element
} }
protected: protected:
Element():myid(DefaultElementID){}; // нельзя создать элемент без id Element(): myid(DefaultElementID) {}; // нельзя создать элемент без id
struct ChildInfo struct ChildInfo
{ {
ChildInfo(Element* e, int n): ChildInfo(Element* e, int n):
el(e),num(n){} el(e), num(n) {}
ChildInfo():el(0),num(0){} ChildInfo(): el(0), num(0) {}
Element* el; Element* el;
int num; int num;
...@@ -87,8 +99,8 @@ class Element ...@@ -87,8 +99,8 @@ class Element
struct InputInfo struct InputInfo
{ {
InputInfo():num(0),state(false),type(unknown){} InputInfo(): num(0), state(false), type(unknown) {}
InputInfo(int n, bool s): num(n),state(s),type(unknown){} InputInfo(int n, bool s): num(n), state(s), type(unknown) {}
int num; int num;
bool state; bool state;
InputType type; InputType type;
...@@ -109,16 +121,22 @@ class TOR: ...@@ -109,16 +121,22 @@ class TOR:
{ {
public: public:
TOR( ElementID id, int numbers=0, bool st=false ); TOR( ElementID id, int numbers = 0, bool st = false );
virtual ~TOR(); virtual ~TOR();
virtual void setIn( int num, bool state ) override; virtual void setIn( int num, bool state ) override;
virtual bool getOut() override { return myout; } virtual bool getOut() override
{
return myout;
}
virtual std::string getType() override { return "OR"; } virtual std::string getType() override
{
return "OR";
}
protected: protected:
TOR():myout(false){} TOR(): myout(false) {}
bool myout; bool myout;
...@@ -130,14 +148,17 @@ class TAND: ...@@ -130,14 +148,17 @@ class TAND:
{ {
public: public:
TAND( ElementID id, int numbers=0, bool st=false ); TAND( ElementID id, int numbers = 0, bool st = false );
virtual ~TAND(); virtual ~TAND();
virtual void setIn( int num, bool state ) override; virtual void setIn( int num, bool state ) override;
virtual std::string getType() override { return "AND"; } virtual std::string getType() override
{
return "AND";
}
protected: protected:
TAND(){} TAND() {}
private: private:
}; };
...@@ -152,17 +173,23 @@ class TNOT: ...@@ -152,17 +173,23 @@ class TNOT:
TNOT( ElementID id, bool out_default ); TNOT( ElementID id, bool out_default );
virtual ~TNOT(); virtual ~TNOT();
virtual bool getOut() override { return myout; } virtual bool getOut() override
{
return myout;
}
/* num игнорируется, т.к. элемент с одним входом /* num игнорируется, т.к. элемент с одним входом
*/ */
virtual void setIn( int num, bool state ) override ; virtual void setIn( int num, bool state ) override ;
virtual std::string getType() override { return "NOT"; } virtual std::string getType() override
virtual void addInput( int num, bool state=false ) override {} {
return "NOT";
}
virtual void addInput( int num, bool state = false ) override {}
virtual void delInput( int num ) override {} virtual void delInput( int num ) override {}
protected: protected:
TNOT():myout(false){} TNOT(): myout(false) {}
bool myout; bool myout;
private: private:
......
...@@ -9,11 +9,12 @@ using namespace UniSetTypes; ...@@ -9,11 +9,12 @@ using namespace UniSetTypes;
using namespace UniSetExtensions; using namespace UniSetExtensions;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LProcessor::LProcessor( const std::string& name ): LProcessor::LProcessor( const std::string& name ):
logname(name) logname(name)
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
sleepTime = conf->getArgPInt("--sleepTime", 200); sleepTime = conf->getArgPInt("--sleepTime", 200);
smReadyTimeout = conf->getArgInt("--sm-ready-timeout",""); smReadyTimeout = conf->getArgInt("--sm-ready-timeout", "");
if( smReadyTimeout == 0 ) if( smReadyTimeout == 0 )
smReadyTimeout = 60000; smReadyTimeout = 60000;
else if( smReadyTimeout < 0 ) else if( smReadyTimeout < 0 )
...@@ -46,6 +47,7 @@ void LProcessor::execute( const string& lfile ) ...@@ -46,6 +47,7 @@ void LProcessor::execute( const string& lfile )
{ {
dcrit << logname << "(execute): " << ex.what() << endl; dcrit << logname << "(execute): " << ex.what() << endl;
} }
msleep(sleepTime); msleep(sleepTime);
} }
} }
...@@ -65,9 +67,10 @@ void LProcessor::build( const string& lfile ) ...@@ -65,9 +67,10 @@ void LProcessor::build( const string& lfile )
// составляем карту внешних входов // составляем карту внешних входов
// считая, что в поле name записано название датчика // считая, что в поле name записано название датчика
for( Schema::EXTiterator it=sch.extBegin(); it!=sch.extEnd(); ++it ) for( Schema::EXTiterator it = sch.extBegin(); it != sch.extEnd(); ++it )
{ {
UniSetTypes::ObjectId sid = conf->getSensorID(it->name); UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
dcrit << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl; dcrit << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ДАТЧИКА: " << it->name << endl;
...@@ -79,17 +82,20 @@ void LProcessor::build( const string& lfile ) ...@@ -79,17 +82,20 @@ void LProcessor::build( const string& lfile )
ei.state = false; ei.state = false;
ei.lnk = &(*it); ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid); ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType ) if( ei.iotype == UniversalIO::UnknownIOType )
{ {
dcrit << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl; dcrit << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
continue; continue;
} }
extInputs.push_front(ei); extInputs.push_front(ei);
} }
for( Schema::OUTiterator it=sch.outBegin(); it!=sch.outEnd(); ++it ) for( Schema::OUTiterator it = sch.outBegin(); it != sch.outEnd(); ++it )
{ {
UniSetTypes::ObjectId sid = conf->getSensorID(it->name); UniSetTypes::ObjectId sid = conf->getSensorID(it->name);
if( sid == DefaultObjectId ) if( sid == DefaultObjectId )
{ {
dcrit << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl; dcrit << "НЕ НАЙДЕН ИДЕНТИФИКАТОР ВЫХОДА: " << it->name << endl;
...@@ -100,6 +106,7 @@ void LProcessor::build( const string& lfile ) ...@@ -100,6 +106,7 @@ void LProcessor::build( const string& lfile )
ei.sid = sid; ei.sid = sid;
ei.lnk = &(*it); ei.lnk = &(*it);
ei.iotype = conf->getIOType(sid); ei.iotype = conf->getIOType(sid);
if( ei.iotype == UniversalIO::UnknownIOType ) if( ei.iotype == UniversalIO::UnknownIOType )
{ {
dcrit << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl; dcrit << "Unkown iotype for sid=" << sid << "(" << it->name << ")" << endl;
...@@ -119,34 +126,34 @@ void LProcessor::build( const string& lfile ) ...@@ -119,34 +126,34 @@ void LProcessor::build( const string& lfile )
*/ */
void LProcessor::getInputs() void LProcessor::getInputs()
{ {
for( auto &it: extInputs ) for( auto& it : extInputs )
{ {
// try // try
// { // {
it.state = (bool)ui.getValue(it.sid); it.state = (bool)ui.getValue(it.sid);
// } // }
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::processing() void LProcessor::processing()
{ {
// выcтавляем все внешние входы // выcтавляем все внешние входы
for( auto &it: extInputs ) for( auto& it : extInputs )
it.lnk->to->setIn(it.lnk->numInput,it.state); it.lnk->to->setIn(it.lnk->numInput, it.state);
// проходим по всем элементам // проходим по всем элементам
for( auto &it: sch ) for( auto& it : sch )
it.second->tick(); it.second->tick();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LProcessor::setOuts() void LProcessor::setOuts()
{ {
// выcтавляем выходы // выcтавляем выходы
for( auto &it: extOuts ) for( auto& it : extOuts )
{ {
try try
{ {
ui.setValue(it.sid,it.lnk->from->getOut(),DefaultObjectId); ui.setValue(it.sid, it.lnk->from->getOut(), DefaultObjectId);
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
......
...@@ -94,7 +94,7 @@ ...@@ -94,7 +94,7 @@
class LProcessor class LProcessor
{ {
public: public:
LProcessor( const std::string& name="" ); LProcessor( const std::string& name = "" );
virtual ~LProcessor(); virtual ~LProcessor();
virtual void execute( const string& lfile ); virtual void execute( const string& lfile );
......
...@@ -44,4 +44,7 @@ all-local: ...@@ -44,4 +44,7 @@ all-local:
ln -sf ../LogicProcessor/$(devel_include_HEADERS) ../include ln -sf ../LogicProcessor/$(devel_include_HEADERS) ../include
SUBDIRS=tests SUBDIRS=tests
include $(top_builddir)/include.mk
endif endif
...@@ -14,14 +14,16 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o ...@@ -14,14 +14,16 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o
auto conf = uniset_conf(); auto conf = uniset_conf();
logname = myname; logname = myname;
shm = make_shared<SMInterface>(shmID,UniSetObject_LT::ui,objId,ic); shm = make_shared<SMInterface>(shmID, UniSetObject_LT::ui, objId, ic);
build(lfile); build(lfile);
// ********** HEARTBEAT ************* // ********** HEARTBEAT *************
string heart = conf->getArgParam("--" + prefix + "-heartbeat-id",""); // it.getProp("heartbeat_id")); string heart = conf->getArgParam("--" + prefix + "-heartbeat-id", ""); // it.getProp("heartbeat_id"));
if( !heart.empty() ) if( !heart.empty() )
{ {
sidHeartBeat = conf->getSensorID(heart); sidHeartBeat = conf->getSensorID(heart);
if( sidHeartBeat == DefaultObjectId ) if( sidHeartBeat == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
...@@ -30,13 +32,14 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o ...@@ -30,13 +32,14 @@ PassiveLProcessor::PassiveLProcessor( std::string lfile, UniSetTypes::ObjectId o
throw SystemError(err.str()); throw SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time",conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + prefix + "-heartbeat-time", conf->getHeartBeatTime());
if( heartbeatTime ) if( heartbeatTime )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + prefix + "-heartbeat-max","10", 10); maxHeartBeat = conf->getArgPInt("--" + prefix + "-heartbeat-max", "10", 10);
} }
} }
...@@ -56,11 +59,11 @@ void PassiveLProcessor::step() ...@@ -56,11 +59,11 @@ void PassiveLProcessor::step()
dcrit << myname << "(step): (hb) " << ex << std::endl; dcrit << myname << "(step): (hb) " << ex << std::endl;
} }
if( sidHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() ) if( sidHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
{ {
try try
{ {
shm->localSetValue(itHeartBeat,sidHeartBeat,maxHeartBeat,getId()); shm->localSetValue(itHeartBeat, sidHeartBeat, maxHeartBeat, getId());
ptHeartBeat.reset(); ptHeartBeat.reset();
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -80,32 +83,32 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd ) ...@@ -80,32 +83,32 @@ void PassiveLProcessor::askSensors( UniversalIO::UIOCommand cmd )
{ {
try try
{ {
for( auto &it: extInputs ) for( auto& it : extInputs )
shm->askSensor(it.sid,cmd); shm->askSensor(it.sid, cmd);
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
dcrit << myname << "(askSensors): " << ex << endl; dcrit << myname << "(askSensors): " << ex << endl;
throw SystemError(myname +"(askSensors): do not ask sensors" ); throw SystemError(myname + "(askSensors): do not ask sensors" );
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::sensorInfo( const UniSetTypes::SensorMessage*sm ) void PassiveLProcessor::sensorInfo( const UniSetTypes::SensorMessage* sm )
{ {
for( auto& it: extInputs ) for( auto& it : extInputs )
{ {
if( it.sid == sm->id ) if( it.sid == sm->id )
it.state = sm->value ? true : false; it.state = sm->value ? true : false;
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::timerInfo( const UniSetTypes::TimerMessage *tm ) void PassiveLProcessor::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
if( tm->id == tidStep ) if( tm->id == tidStep )
step(); step();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage *sm ) void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
switch( sm->command ) switch( sm->command )
{ {
...@@ -120,7 +123,7 @@ void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage *sm ) ...@@ -120,7 +123,7 @@ void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage *sm )
UniSetTypes::uniset_mutex_lock l(mutex_start, 10000); UniSetTypes::uniset_mutex_lock l(mutex_start, 10000);
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
askTimer(tidStep,LProcessor::sleepTime); askTimer(tidStep, LProcessor::sleepTime);
break; break;
} }
...@@ -148,17 +151,19 @@ void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage *sm ) ...@@ -148,17 +151,19 @@ void PassiveLProcessor::sysCommand( const UniSetTypes::SystemMessage *sm )
// переоткрываем логи // переоткрываем логи
ulogany << myname << "(sysCommand): logRotate" << std::endl; ulogany << myname << "(sysCommand): logRotate" << std::endl;
string fname (ulog()->getLogFile() ); string fname (ulog()->getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
ulog()->logFile(fname,true); ulog()->logFile(fname, true);
ulogany << myname << "(sysCommand): ***************** ulog LOG ROTATE *****************" << std::endl; ulogany << myname << "(sysCommand): ***************** ulog LOG ROTATE *****************" << std::endl;
} }
dlogany << myname << "(sysCommand): logRotate" << std::endl; dlogany << myname << "(sysCommand): logRotate" << std::endl;
fname = dlog()->getLogFile(); fname = dlog()->getLogFile();
if( !fname.empty() ) if( !fname.empty() )
{ {
dlog()->logFile(fname,true); dlog()->logFile(fname, true);
dlogany << myname << "(sysCommand): ***************** dlog LOG ROTATE *****************" << std::endl; dlogany << myname << "(sysCommand): ***************** dlog LOG ROTATE *****************" << std::endl;
} }
} }
...@@ -191,11 +196,11 @@ void PassiveLProcessor::initIterators() ...@@ -191,11 +196,11 @@ void PassiveLProcessor::initIterators()
void PassiveLProcessor::setOuts() void PassiveLProcessor::setOuts()
{ {
// выcтавляем выходы // выcтавляем выходы
for( auto &it: extOuts ) for( auto& it : extOuts )
{ {
try try
{ {
shm->setValue( it.sid,it.lnk->from->getOut() ); shm->setValue( it.sid, it.lnk->from->getOut() );
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
...@@ -210,11 +215,11 @@ void PassiveLProcessor::setOuts() ...@@ -210,11 +215,11 @@ void PassiveLProcessor::setOuts()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void PassiveLProcessor::sigterm( int signo ) void PassiveLProcessor::sigterm( int signo )
{ {
for( auto &it: extOuts ) for( auto& it : extOuts )
{ {
try try
{ {
shm->setValue(it.sid,0); shm->setValue(it.sid, 0);
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
......
...@@ -19,7 +19,7 @@ class PassiveLProcessor: ...@@ -19,7 +19,7 @@ class PassiveLProcessor:
public: public:
PassiveLProcessor( std::string schema, UniSetTypes::ObjectId objId, PassiveLProcessor( std::string schema, UniSetTypes::ObjectId objId,
UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, const std::string& prefix="lproc" ); UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr, const std::string& prefix = "lproc" );
virtual ~PassiveLProcessor(); virtual ~PassiveLProcessor();
enum Timers enum Timers
...@@ -28,17 +28,17 @@ class PassiveLProcessor: ...@@ -28,17 +28,17 @@ class PassiveLProcessor:
}; };
protected: protected:
PassiveLProcessor():shm(0),maxHeartBeat(0){}; PassiveLProcessor(): shm(0), maxHeartBeat(0) {};
virtual void step(); virtual void step();
virtual void getInputs(); virtual void getInputs();
virtual void setOuts(); virtual void setOuts();
void sysCommand( const UniSetTypes::SystemMessage *msg ) override; void sysCommand( const UniSetTypes::SystemMessage* msg ) override;
void sensorInfo( const UniSetTypes::SensorMessage*sm ) override; void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
void timerInfo( const UniSetTypes::TimerMessage *tm ) override; void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
void askSensors( const UniversalIO::UIOCommand cmd ); void askSensors( const UniversalIO::UIOCommand cmd );
// void initOutput(); // void initOutput();
// действия при завершении работы // действия при завершении работы
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
......
...@@ -13,7 +13,7 @@ Schema::Schema() ...@@ -13,7 +13,7 @@ Schema::Schema()
Schema::~Schema() Schema::~Schema()
{ {
for( auto &it: emap ) for( auto& it : emap )
{ {
if( it.second != 0 ) if( it.second != 0 )
{ {
...@@ -29,27 +29,31 @@ void Schema::link( Element::ElementID rootID, Element::ElementID childID, int nu ...@@ -29,27 +29,31 @@ void Schema::link( Element::ElementID rootID, Element::ElementID childID, int nu
Element* e2 = 0; Element* e2 = 0;
auto it = emap.find(rootID); auto it = emap.find(rootID);
if( it == emap.end() ) if( it == emap.end() )
{ {
ostringstream msg; ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!"; msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
e1 = it->second; e1 = it->second;
it = emap.find(childID); it = emap.find(childID);
if( it == emap.end() ) if( it == emap.end() )
{ {
ostringstream msg; ostringstream msg;
msg << "Schema: элемент id=" << childID << " NOT FOUND!"; msg << "Schema: элемент id=" << childID << " NOT FOUND!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
e2 = it->second; e2 = it->second;
e1->addChildOut(e2, numIn); e1->addChildOut(e2, numIn);
// сохраняем в список соединений // сохраняем в список соединений
inLinks.push_front(INLink(e1,e2,numIn)); inLinks.push_front(INLink(e1, e2, numIn));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Schema::unlink( Element::ElementID rootID, Element::ElementID childID ) void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
...@@ -58,27 +62,31 @@ void Schema::unlink( Element::ElementID rootID, Element::ElementID childID ) ...@@ -58,27 +62,31 @@ void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
Element* e2(0); Element* e2(0);
auto it = emap.find(rootID); auto it = emap.find(rootID);
if( it == emap.end() ) if( it == emap.end() )
{ {
ostringstream msg; ostringstream msg;
msg << "Schema: элемент id=" << rootID << " NOT FOUND!"; msg << "Schema: элемент id=" << rootID << " NOT FOUND!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
e1 = it->second; e1 = it->second;
it = emap.find( childID ); it = emap.find( childID );
if( it == emap.end() ) if( it == emap.end() )
{ {
ostringstream msg; ostringstream msg;
msg << "Schema: element id=" << childID << " NOT FOUND!"; msg << "Schema: element id=" << childID << " NOT FOUND!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
e2 = it->second; e2 = it->second;
e1->delChildOut(e2); e1->delChildOut(e2);
// удаляем из списка соединений // удаляем из списка соединений
for( auto lit=inLinks.begin(); lit!=inLinks.end(); ++lit ) for( auto lit = inLinks.begin(); lit != inLinks.end(); ++lit )
{ {
if( lit->from == e1 && lit->to == e2 ) if( lit->from == e1 && lit->to == e2 )
{ {
...@@ -91,6 +99,7 @@ void Schema::unlink( Element::ElementID rootID, Element::ElementID childID ) ...@@ -91,6 +99,7 @@ void Schema::unlink( Element::ElementID rootID, Element::ElementID childID )
void Schema::extlink( const string& name, Element::ElementID childID, int numIn ) void Schema::extlink( const string& name, Element::ElementID childID, int numIn )
{ {
auto it = emap.find(childID); auto it = emap.find(childID);
if( it == emap.end() ) if( it == emap.end() )
{ {
ostringstream msg; ostringstream msg;
...@@ -100,12 +109,12 @@ void Schema::extlink( const string& name, Element::ElementID childID, int numIn ...@@ -100,12 +109,12 @@ void Schema::extlink( const string& name, Element::ElementID childID, int numIn
Element* el(it->second); Element* el(it->second);
// добавляем новое соединение // добавляем новое соединение
// el->addInput(numIn); // el->addInput(numIn);
// уже должен быть // уже должен быть
// заносим в список // заносим в список
extLinks.push_front( EXTLink(name,el,numIn) ); extLinks.push_front( EXTLink(name, el, numIn) );
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Schema::manage( Element* el ) Element* Schema::manage( Element* el )
...@@ -120,7 +129,7 @@ Element* Schema::manage( Element* el ) ...@@ -120,7 +129,7 @@ Element* Schema::manage( Element* el )
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void Schema::remove( Element* el ) void Schema::remove( Element* el )
{ {
for( auto it=emap.begin(); it!=emap.end(); ++it ) for( auto it = emap.begin(); it != emap.end(); ++it )
{ {
if( it->second != el ) if( it->second != el )
{ {
...@@ -130,7 +139,7 @@ void Schema::remove( Element* el ) ...@@ -130,7 +139,7 @@ void Schema::remove( Element* el )
} }
// помечаем внутренние связи // помечаем внутренние связи
for( auto &lit: inLinks ) for( auto& lit : inLinks )
{ {
if( lit.from == el ) if( lit.from == el )
lit.from = 0; lit.from = 0;
...@@ -140,7 +149,7 @@ void Schema::remove( Element* el ) ...@@ -140,7 +149,7 @@ void Schema::remove( Element* el )
} }
// помечаем внешние связи // помечаем внешние связи
for( auto &lit: extLinks ) for( auto& lit : extLinks )
{ {
if( lit.to == el ) if( lit.to == el )
lit.to = 0; lit.to = 0;
...@@ -151,33 +160,37 @@ void Schema::remove( Element* el ) ...@@ -151,33 +160,37 @@ void Schema::remove( Element* el )
void Schema::setIn( Element::ElementID ID, int inNum, bool state ) void Schema::setIn( Element::ElementID ID, int inNum, bool state )
{ {
auto it = emap.find(ID); auto it = emap.find(ID);
if( it != emap.end() ) if( it != emap.end() )
it->second->setIn(inNum,state); it->second->setIn(inNum, state);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
bool Schema::getOut( Element::ElementID ID ) bool Schema::getOut( Element::ElementID ID )
{ {
auto it = emap.find(ID); auto it = emap.find(ID);
if( it != emap.end() ) if( it != emap.end() )
return it->second->getOut(); return it->second->getOut();
ostringstream msg; ostringstream msg;
msg << "Schema: element id=" <<ID << " NOT FOUND!"; msg << "Schema: element id=" << ID << " NOT FOUND!";
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Schema::find( Element::ElementID id ) Element* Schema::find( Element::ElementID id )
{ {
auto it = emap.find(id); auto it = emap.find(id);
if( it != emap.end() ) if( it != emap.end() )
return it->second; return it->second;
return 0; return 0;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Element* Schema::findExtLink( const string& name ) Element* Schema::findExtLink( const string& name )
{ {
// помечаем внешние связи // помечаем внешние связи
for( auto &it: extLinks ) for( auto& it : extLinks )
{ {
if( it.name == name ) if( it.name == name )
return it.to; return it.to;
......
...@@ -19,8 +19,8 @@ class Schema ...@@ -19,8 +19,8 @@ class Schema
struct INLink struct INLink
{ {
INLink(Element* f, Element* t, int ni): INLink(Element* f, Element* t, int ni):
from(f),to(t),numInput(ni){} from(f), to(t), numInput(ni) {}
INLink():from(0),to(0),numInput(0){} INLink(): from(0), to(0), numInput(0) {}
Element* from; Element* from;
Element* to; Element* to;
...@@ -32,8 +32,8 @@ class Schema ...@@ -32,8 +32,8 @@ class Schema
struct EXTLink struct EXTLink
{ {
EXTLink(std::string n, Element* t, int ni): EXTLink(std::string n, Element* t, int ni):
name(n),to(t),numInput(ni){} name(n), to(t), numInput(ni) {}
EXTLink():name(""),to(0),numInput(0){} EXTLink(): name(""), to(0), numInput(0) {}
std::string name; std::string name;
Element* to; Element* to;
...@@ -44,8 +44,8 @@ class Schema ...@@ -44,8 +44,8 @@ class Schema
struct EXTOut struct EXTOut
{ {
EXTOut(std::string n, Element* f): EXTOut(std::string n, Element* f):
name(n),from(f){} name(n), from(f) {}
EXTOut():name(""),from(0){} EXTOut(): name(""), from(0) {}
std::string name; std::string name;
Element* from; Element* from;
...@@ -59,38 +59,86 @@ class Schema ...@@ -59,38 +59,86 @@ class Schema
void setIn( Element::ElementID ID, int inNum, bool state ); void setIn( Element::ElementID ID, int inNum, bool state );
bool getOut( Element::ElementID ID ); bool getOut( Element::ElementID ID );
typedef std::unordered_map<Element::ElementID,Element*> ElementMap; typedef std::unordered_map<Element::ElementID, Element*> ElementMap;
typedef std::list<INLink> InternalList; typedef std::list<INLink> InternalList;
typedef std::list<EXTLink> ExternalList; typedef std::list<EXTLink> ExternalList;
typedef std::list<EXTOut> OutputsList; typedef std::list<EXTOut> OutputsList;
// map iterator // map iterator
typedef ElementMap::const_iterator iterator; typedef ElementMap::const_iterator iterator;
inline Schema::iterator begin(){ return emap.begin(); } inline Schema::iterator begin()
inline Schema::iterator end(){ return emap.end(); } {
inline int size(){ return emap.size(); } return emap.begin();
inline bool empty(){ return emap.empty(); } }
inline Schema::iterator end()
{
return emap.end();
}
inline int size()
{
return emap.size();
}
inline bool empty()
{
return emap.empty();
}
// int. list iterator // int. list iterator
typedef InternalList::const_iterator INTiterator; typedef InternalList::const_iterator INTiterator;
inline Schema::INTiterator intBegin(){ return inLinks.begin(); } inline Schema::INTiterator intBegin()
inline Schema::INTiterator intEnd(){ return inLinks.end(); } {
inline int intSize(){ return inLinks.size(); } return inLinks.begin();
inline bool intEmpty(){ return inLinks.empty(); } }
inline Schema::INTiterator intEnd()
{
return inLinks.end();
}
inline int intSize()
{
return inLinks.size();
}
inline bool intEmpty()
{
return inLinks.empty();
}
// ext. list iterator // ext. list iterator
typedef ExternalList::const_iterator EXTiterator; typedef ExternalList::const_iterator EXTiterator;
inline Schema::EXTiterator extBegin(){ return extLinks.begin(); } inline Schema::EXTiterator extBegin()
inline Schema::EXTiterator extEnd(){ return extLinks.end(); } {
inline int extSize(){ return extLinks.size(); } return extLinks.begin();
inline bool extEmpty(){ return extLinks.empty(); } }
inline Schema::EXTiterator extEnd()
{
return extLinks.end();
}
inline int extSize()
{
return extLinks.size();
}
inline bool extEmpty()
{
return extLinks.empty();
}
// ext. out iterator // ext. out iterator
typedef OutputsList::const_iterator OUTiterator; typedef OutputsList::const_iterator OUTiterator;
inline Schema::OUTiterator outBegin(){ return outList.begin(); } inline Schema::OUTiterator outBegin()
inline Schema::OUTiterator outEnd(){ return outList.end(); } {
inline int outSize(){ return outList.size(); } return outList.begin();
inline bool outEmpty(){ return outList.empty(); } }
inline Schema::OUTiterator outEnd()
{
return outList.end();
}
inline int outSize()
{
return outList.size();
}
inline bool outEmpty()
{
return outList.empty();
}
// find // find
Element* find(Element::ElementID id); Element* find(Element::ElementID id);
......
...@@ -23,13 +23,14 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -23,13 +23,14 @@ void SchemaXML::read( const string& xmlfile )
const string sec("elements"); const string sec("elements");
const string conn_sec("connections"); const string conn_sec("connections");
// try // try
// { // {
xml.open(xmlfile); xml.open(xmlfile);
// } // }
// catch(...){} // catch(...){}
xmlNode* root( xml.findNode(xml.getFirstNode(), sec) );
xmlNode* root( xml.findNode(xml.getFirstNode(),sec) );
if( !root ) if( !root )
{ {
ostringstream msg; ostringstream msg;
...@@ -39,6 +40,7 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -39,6 +40,7 @@ void SchemaXML::read( const string& xmlfile )
// Считываем список элементов // Считываем список элементов
UniXML::iterator it(root); UniXML::iterator it(root);
if( !it.goChildren() ) if( !it.goChildren() )
{ {
ostringstream msg; ostringstream msg;
...@@ -46,7 +48,7 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -46,7 +48,7 @@ void SchemaXML::read( const string& xmlfile )
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
for( ;it.getCurrent(); it.goNext() ) for( ; it.getCurrent(); it.goNext() )
{ {
string type(xml.getProp(it, "type")); string type(xml.getProp(it, "type"));
string ID(xml.getProp(it, "id")); string ID(xml.getProp(it, "id"));
...@@ -58,13 +60,13 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -58,13 +60,13 @@ void SchemaXML::read( const string& xmlfile )
manage( new TAND(ID, inCount) ); manage( new TAND(ID, inCount) );
else if( type == "Delay" ) else if( type == "Delay" )
{ {
int delayMS = xml.getIntProp(it,"delayMS"); int delayMS = xml.getIntProp(it, "delayMS");
manage( new TDelay(ID,delayMS,inCount) ); manage( new TDelay(ID, delayMS, inCount) );
} }
else if( type == "NOT" ) else if( type == "NOT" )
{ {
bool defout = xml.getIntProp(it,"default_out_state"); bool defout = xml.getIntProp(it, "default_out_state");
manage( new TNOT(ID,defout) ); manage( new TNOT(ID, defout) );
} }
else else
{ {
...@@ -75,7 +77,8 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -75,7 +77,8 @@ void SchemaXML::read( const string& xmlfile )
} }
// Строим связи // Строим связи
xmlNode* conNode( xml.findNode(xml.getFirstNode(),conn_sec) ); xmlNode* conNode( xml.findNode(xml.getFirstNode(), conn_sec) );
if( !conNode ) if( !conNode )
{ {
ostringstream msg; ostringstream msg;
...@@ -84,6 +87,7 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -84,6 +87,7 @@ void SchemaXML::read( const string& xmlfile )
} }
it = conNode; it = conNode;
if( !it.goChildren() ) if( !it.goChildren() )
{ {
ostringstream msg; ostringstream msg;
...@@ -91,7 +95,7 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -91,7 +95,7 @@ void SchemaXML::read( const string& xmlfile )
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
for( ;it.getCurrent(); it.goNext() ) for( ; it.getCurrent(); it.goNext() )
{ {
string type(xml.getProp(it, "type")); string type(xml.getProp(it, "type"));
string fID(xml.getProp(it, "from")); string fID(xml.getProp(it, "from"));
...@@ -100,26 +104,27 @@ void SchemaXML::read( const string& xmlfile ) ...@@ -100,26 +104,27 @@ void SchemaXML::read( const string& xmlfile )
if( type == "ext" ) if( type == "ext" )
{ {
cout <<"SchemaXML: set EXTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl; cout << "SchemaXML: set EXTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
extlink(fID,tID,toIn); extlink(fID, tID, toIn);
} }
else if( type == "int" ) else if( type == "int" )
{ {
cout <<"SchemaXML: set INTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl; cout << "SchemaXML: set INTlink: from=" << fID << " to=" << tID << " toInput=" << toIn << endl;
link(fID,tID,toIn); link(fID, tID, toIn);
} }
else if( type == "out" ) else if( type == "out" )
{ {
Element* el = find(fID); Element* el = find(fID);
if( el== 0 )
if( el == 0 )
{ {
ostringstream msg; ostringstream msg;
msg << "(SchemaXML::read): НЕ НАЙДЕН ЭЛЕМЕНТ С ID=" << fID; msg << "(SchemaXML::read): НЕ НАЙДЕН ЭЛЕМЕНТ С ID=" << fID;
throw LogicException(msg.str()); throw LogicException(msg.str());
} }
cout <<"SchemaXML: set Out: from=" << fID << " to=" << tID << endl; cout << "SchemaXML: set Out: from=" << fID << " to=" << tID << endl;
outList.push_front( EXTOut(tID,el) ); outList.push_front( EXTOut(tID, el) );
} }
} }
} }
......
...@@ -6,7 +6,7 @@ using namespace std; ...@@ -6,7 +6,7 @@ using namespace std;
using namespace UniSetExtensions; using namespace UniSetExtensions;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
TAND::TAND(ElementID id, int num, bool st): TAND::TAND(ElementID id, int num, bool st):
TOR(id,num,st) TOR(id, num, st)
{ {
} }
...@@ -16,8 +16,8 @@ TAND::~TAND() ...@@ -16,8 +16,8 @@ TAND::~TAND()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void TAND::setIn( int num, bool state ) void TAND::setIn( int num, bool state )
{ {
// cout << this << ": input " << num << " set " << state << endl; // cout << this << ": input " << num << " set " << state << endl;
for( auto &it: ins ) for( auto& it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
...@@ -34,7 +34,7 @@ void TAND::setIn( int num, bool state ) ...@@ -34,7 +34,7 @@ void TAND::setIn( int num, bool state )
// проверяем изменился ли выход // проверяем изменился ли выход
// для тригера 'AND' проверка до первого 0 // для тригера 'AND' проверка до первого 0
for( auto &it: ins ) for( auto& it : ins )
{ {
if( !it.state ) if( !it.state )
{ {
......
...@@ -10,11 +10,11 @@ TDelay::TDelay( Element::ElementID id, int delayMS, int inCount): ...@@ -10,11 +10,11 @@ TDelay::TDelay( Element::ElementID id, int delayMS, int inCount):
myout(false), myout(false),
delay(delayMS) delay(delayMS)
{ {
if( inCount!=0 ) if( inCount != 0 )
{ {
// создаём заданное количество входов // создаём заданное количество входов
for( unsigned int i=1;i<=inCount;i++ ) for( unsigned int i = 1; i <= inCount; i++ )
ins.push_front(InputInfo(i,false)); // addInput(i,st); ins.push_front(InputInfo(i, false)); // addInput(i,st);
} }
} }
...@@ -25,18 +25,21 @@ TDelay::~TDelay() ...@@ -25,18 +25,21 @@ TDelay::~TDelay()
void TDelay::setIn( int num, bool state ) void TDelay::setIn( int num, bool state )
{ {
bool prev = myout; bool prev = myout;
// сбрасываем сразу // сбрасываем сразу
if( !state ) if( !state )
{ {
pt.setTiming(0); // reset timer pt.setTiming(0); // reset timer
myout = false; myout = false;
dinfo << this << ": set " << myout << endl; dinfo << this << ": set " << myout << endl;
if( prev != myout ) if( prev != myout )
Element::setChildOut(); Element::setChildOut();
return; return;
} }
// if( state ) // if( state )
// выставляем без задержки // выставляем без задержки
if( delay <= 0 ) if( delay <= 0 )
...@@ -44,8 +47,10 @@ void TDelay::setIn( int num, bool state ) ...@@ -44,8 +47,10 @@ void TDelay::setIn( int num, bool state )
pt.setTiming(0); // reset timer pt.setTiming(0); // reset timer
myout = true; myout = true;
dinfo << this << ": set " << myout << endl; dinfo << this << ": set " << myout << endl;
if( prev != myout ) if( prev != myout )
Element::setChildOut(); Element::setChildOut();
return; return;
} }
...@@ -59,7 +64,7 @@ void TDelay::setIn( int num, bool state ) ...@@ -59,7 +64,7 @@ void TDelay::setIn( int num, bool state )
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void TDelay::tick() void TDelay::tick()
{ {
if( pt.getInterval()!=0 && pt.checkTime() ) if( pt.getInterval() != 0 && pt.checkTime() )
{ {
myout = true; myout = true;
pt.setTiming(0); // reset timer pt.setTiming(0); // reset timer
......
...@@ -11,20 +11,26 @@ class TDelay: ...@@ -11,20 +11,26 @@ class TDelay:
{ {
public: public:
TDelay( Element::ElementID id, int delayMS=0, int inCount=0 ); TDelay( Element::ElementID id, int delayMS = 0, int inCount = 0 );
virtual ~TDelay(); virtual ~TDelay();
virtual void tick() override; virtual void tick() override;
virtual void setIn( int num, bool state ) override; virtual void setIn( int num, bool state ) override;
virtual bool getOut() override; virtual bool getOut() override;
virtual std::string getType() override { return "Delay"; } virtual std::string getType() override
{
return "Delay";
}
void setDelay( int timeMS ); void setDelay( int timeMS );
inline int getDelay(){ return delay; } inline int getDelay()
{
return delay;
}
protected: protected:
TDelay():myout(false),delay(0){}; TDelay(): myout(false), delay(0) {};
bool myout; bool myout;
PassiveTimer pt; PassiveTimer pt;
......
...@@ -10,7 +10,7 @@ TNOT::TNOT( ElementID id, bool out_default ): ...@@ -10,7 +10,7 @@ TNOT::TNOT( ElementID id, bool out_default ):
Element(id), Element(id),
myout(out_default) myout(out_default)
{ {
ins.push_front(InputInfo(1,!out_default)); ins.push_front(InputInfo(1, !out_default));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
TNOT::~TNOT() TNOT::~TNOT()
......
...@@ -10,12 +10,13 @@ TOR::TOR(ElementID id, int num, bool st): ...@@ -10,12 +10,13 @@ TOR::TOR(ElementID id, int num, bool st):
Element(id), Element(id),
myout(false) myout(false)
{ {
if( num!=0 ) if( num != 0 )
{ {
// создаём заданное количество входов // создаём заданное количество входов
for( unsigned int i=1;i<=num;i++ ) for( unsigned int i = 1; i <= num; i++ )
{ {
ins.push_front(InputInfo(i,st)); // addInput(i,st); ins.push_front(InputInfo(i, st)); // addInput(i,st);
if( st == true ) if( st == true )
myout = true; myout = true;
} }
...@@ -28,9 +29,9 @@ TOR::~TOR() ...@@ -28,9 +29,9 @@ TOR::~TOR()
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void TOR::setIn( int num, bool state ) void TOR::setIn( int num, bool state )
{ {
// cout << getType() << "(" << myid << "): input " << num << " set " << state << endl; // cout << getType() << "(" << myid << "): input " << num << " set " << state << endl;
for( auto &it: ins ) for( auto& it : ins )
{ {
if( it.num == num ) if( it.num == num )
{ {
...@@ -47,7 +48,7 @@ void TOR::setIn( int num, bool state ) ...@@ -47,7 +48,7 @@ void TOR::setIn( int num, bool state )
// проверяем изменился ли выход // проверяем изменился ли выход
// для тригера 'OR' проверка до первой единицы // для тригера 'OR' проверка до первой единицы
for( auto &it: ins ) for( auto& it : ins )
{ {
if( it.state ) if( it.state )
{ {
...@@ -61,6 +62,7 @@ void TOR::setIn( int num, bool state ) ...@@ -61,6 +62,7 @@ void TOR::setIn( int num, bool state )
myout = false; myout = false;
dinfo << this << ": myout " << myout << endl; dinfo << this << ": myout " << myout << endl;
if( prev != myout ) if( prev != myout )
Element::setChildOut(); Element::setChildOut();
} }
......
...@@ -7,14 +7,16 @@ using namespace std; ...@@ -7,14 +7,16 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
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);
try try
{ {
auto conf = uniset_init( argc, argv ); auto conf = uniset_init( argc, argv );
string logfilename(conf->getArgParam("--logicproc-logfile")); string logfilename(conf->getArgParam("--logicproc-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
logfilename = "logicproc.log"; logfilename = "logicproc.log";
...@@ -25,6 +27,7 @@ int main(int argc, const char **argv) ...@@ -25,6 +27,7 @@ int main(int argc, const char **argv)
dlog()->logFile( logname.str() ); dlog()->logFile( logname.str() );
string schema = conf->getArgParam("--schema"); string schema = conf->getArgParam("--schema");
if( schema.empty() ) if( schema.empty() )
{ {
dcrit << "schema-file not defined. Use --schema" << endl; dcrit << "schema-file not defined. Use --schema" << endl;
......
...@@ -9,14 +9,16 @@ using namespace std; ...@@ -9,14 +9,16 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
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);
try try
{ {
auto conf = uniset_init( argc, argv ); auto conf = uniset_init( argc, argv );
string logfilename(conf->getArgParam("--logicproc-logfile")); string logfilename(conf->getArgParam("--logicproc-logfile"));
if( logfilename.empty() ) if( logfilename.empty() )
logfilename = "logicproc.log"; logfilename = "logicproc.log";
...@@ -27,6 +29,7 @@ int main(int argc, const char **argv) ...@@ -27,6 +29,7 @@ int main(int argc, const char **argv)
dlog()->logFile( logname.str() ); dlog()->logFile( logname.str() );
string schema = conf->getArgParam("--schema"); string schema = conf->getArgParam("--schema");
if( schema.empty() ) if( schema.empty() )
{ {
cerr << "schema-file not defined. Use --schema" << endl; cerr << "schema-file not defined. Use --schema" << endl;
...@@ -35,6 +38,7 @@ int main(int argc, const char **argv) ...@@ -35,6 +38,7 @@ int main(int argc, const char **argv)
ObjectId shmID = DefaultObjectId; ObjectId shmID = DefaultObjectId;
string sID = conf->getArgParam("--smemory-id"); string sID = conf->getArgParam("--smemory-id");
if( !sID.empty() ) if( !sID.empty() )
shmID = conf->getControllerID(sID); shmID = conf->getControllerID(sID);
else else
...@@ -48,7 +52,8 @@ int main(int argc, const char **argv) ...@@ -48,7 +52,8 @@ int main(int argc, const char **argv)
cout << "init smemory: " << sID << " ID: " << shmID << endl; cout << "init smemory: " << sID << " ID: " << shmID << endl;
string name = conf->getArgParam("--name","LProcessor"); string name = conf->getArgParam("--name", "LProcessor");
if( name.empty() ) if( name.empty() )
{ {
cerr << "(plogicproc): Не задан name'" << endl; cerr << "(plogicproc): Не задан name'" << endl;
...@@ -56,6 +61,7 @@ int main(int argc, const char **argv) ...@@ -56,6 +61,7 @@ int main(int argc, const char **argv)
} }
ObjectId ID = conf->getObjectID(name); ObjectId ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(plogicproc): идентификатор '" << name cerr << "(plogicproc): идентификатор '" << name
...@@ -66,7 +72,7 @@ int main(int argc, const char **argv) ...@@ -66,7 +72,7 @@ int main(int argc, const char **argv)
cout << "init name: " << name << " ID: " << ID << endl; cout << "init name: " << name << " ID: " << ID << endl;
PassiveLProcessor plc(schema,ID,shmID); PassiveLProcessor plc(schema, ID, shmID);
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act->add(plc.get_ptr()); act->add(plc.get_ptr());
......
...@@ -24,4 +24,6 @@ clean-local: ...@@ -24,4 +24,6 @@ clean-local:
rm -rf $(CLEANFILES) rm -rf $(CLEANFILES)
rm -rf $(COVERAGE_REPORT_DIR) rm -rf $(COVERAGE_REPORT_DIR)
include $(top_builddir)/include.mk
endif endif
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
using namespace std; using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
TEST_CASE("Logic processor","[LogicProcessor]") TEST_CASE("Logic processor", "[LogicProcessor]")
{ {
#if 0 #if 0
SECTION( "ShemaXML" ) SECTION( "ShemaXML" )
...@@ -20,61 +20,61 @@ TEST_CASE("Logic processor","[LogicProcessor]") ...@@ -20,61 +20,61 @@ TEST_CASE("Logic processor","[LogicProcessor]")
#endif #endif
SECTION( "TOR" ) SECTION( "TOR" )
{ {
TOR e("1",2); // элемент на два входа.. TOR e("1", 2); // элемент на два входа..
REQUIRE( e.getOut() == 0 ); REQUIRE( e.getOut() == 0 );
e.setIn(1,true); e.setIn(1, true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(2,true); e.setIn(2, true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(1,false); e.setIn(1, false);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(2,false); e.setIn(2, false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(3,true); // несуществующий вход.. e.setIn(3, true); // несуществующий вход..
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
} }
SECTION( "TAND" ) SECTION( "TAND" )
{ {
TAND e("1",2); // элемент на два входа.. TAND e("1", 2); // элемент на два входа..
REQUIRE( e.getOut() == 0 ); REQUIRE( e.getOut() == 0 );
e.setIn(1,true); e.setIn(1, true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(2,true); e.setIn(2, true);
CHECK( e.getOut() ); CHECK( e.getOut() );
e.setIn(1,false); e.setIn(1, false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(2,false); e.setIn(2, false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(3,true); // несуществующий вход.. e.setIn(3, true); // несуществующий вход..
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
} }
SECTION( "TNOT" ) SECTION( "TNOT" )
{ {
TNOT e("1",false); TNOT e("1", false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(1,true); e.setIn(1, true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
e.setIn(1,false); e.setIn(1, false);
CHECK( e.getOut() ); CHECK( e.getOut() );
// other constructor // other constructor
TNOT e1("1",true); TNOT e1("1", true);
CHECK( e1.getOut() ); CHECK( e1.getOut() );
e1.setIn(1,true); e1.setIn(1, true);
CHECK_FALSE( e1.getOut() ); CHECK_FALSE( e1.getOut() );
e1.setIn(1,false); e1.setIn(1, false);
CHECK( e1.getOut() ); CHECK( e1.getOut() );
} }
SECTION( "TDelay" ) SECTION( "TDelay" )
{ {
TDelay e("1",50,1); TDelay e("1", 50, 1);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
// ON DELAY // ON DELAY
e.setIn(1,true); e.setIn(1, true);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
msleep(60); msleep(60);
e.tick(); e.tick();
...@@ -85,18 +85,18 @@ TEST_CASE("Logic processor","[LogicProcessor]") ...@@ -85,18 +85,18 @@ TEST_CASE("Logic processor","[LogicProcessor]")
CHECK( e.getOut() ); CHECK( e.getOut() );
// OFF DELAY // OFF DELAY
e.setIn(1,false); e.setIn(1, false);
CHECK_FALSE( e.getOut() ); CHECK_FALSE( e.getOut() );
// delay 0 msek.. // delay 0 msek..
e.setDelay(0); e.setDelay(0);
e.setIn(1,true); e.setIn(1, true);
CHECK( e.getOut() ); CHECK( e.getOut() );
// delay < 0 === 0 // delay < 0 === 0
e.setIn(1,false); e.setIn(1, false);
e.setDelay(-10); e.setDelay(-10);
e.setIn(1,true); e.setIn(1, true);
CHECK( e.getOut() ); CHECK( e.getOut() );
} }
} }
...@@ -28,23 +28,23 @@ class MBExchange: ...@@ -28,23 +28,23 @@ class MBExchange:
public UniSetObject_LT public UniSetObject_LT
{ {
public: public:
MBExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, MBExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="mb" ); const std::string& prefix = "mb" );
virtual ~MBExchange(); virtual ~MBExchange();
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
static const int NoSafetyState=-1; static const int NoSafetyState = -1;
/*! Режимы работы процесса обмена */ /*! Режимы работы процесса обмена */
enum ExchangeMode enum ExchangeMode
{ {
emNone=0, /*!< нормальная работа (по умолчанию) */ emNone = 0, /*!< нормальная работа (по умолчанию) */
emWriteOnly=1, /*!< "только посылка данных" (работают только write-функции) */ emWriteOnly = 1, /*!< "только посылка данных" (работают только write-функции) */
emReadOnly=2, /*!< "только чтение" (работают только read-функции) */ emReadOnly = 2, /*!< "только чтение" (работают только read-функции) */
emSkipSaveToSM=3, /*!< не писать данные в SM (при этом работают и read и write функции) */ emSkipSaveToSM = 3, /*!< не писать данные в SM (при этом работают и read и write функции) */
emSkipExchange=4 /*!< отключить обмен */ emSkipExchange = 4 /*!< отключить обмен */
}; };
friend std::ostream& operator<<( std::ostream& os, const ExchangeMode& em ); friend std::ostream& operator<<( std::ostream& os, const ExchangeMode& em );
...@@ -73,9 +73,9 @@ class MBExchange: ...@@ -73,9 +73,9 @@ class MBExchange:
short nbyte; /*!< byte number (1-2) */ short nbyte; /*!< byte number (1-2) */
RSProperty(): RSProperty():
nbit(-1),vType(VTypes::vtUnknown), nbit(-1), vType(VTypes::vtUnknown),
rnum(VTypes::wsize(VTypes::vtUnknown)), rnum(VTypes::wsize(VTypes::vtUnknown)),
nbyte(0),reg(0) nbyte(0), reg(0)
{} {}
// т.к. IOBase содержит rwmutex с запрещённым конструктором копирования // т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
...@@ -95,7 +95,7 @@ class MBExchange: ...@@ -95,7 +95,7 @@ class MBExchange:
typedef unsigned long RegID; typedef unsigned long RegID;
typedef std::map<RegID,RegInfo*> RegMap; typedef std::map<RegID, RegInfo*> RegMap;
struct RegInfo struct RegInfo
{ {
// т.к. RSProperty содержит rwmutex с запрещённым конструктором копирования // т.к. RSProperty содержит rwmutex с запрещённым конструктором копирования
...@@ -106,11 +106,11 @@ class MBExchange: ...@@ -106,11 +106,11 @@ class MBExchange:
RegInfo& operator=(RegInfo&& r) = default; RegInfo& operator=(RegInfo&& r) = default;
RegInfo(): RegInfo():
mbval(0),mbreg(0),mbfunc(ModbusRTU::fnUnknown), mbval(0), mbreg(0), mbfunc(ModbusRTU::fnUnknown),
id(0),dev(0), id(0), dev(0),
rtuJack(RTUStorage::nUnknown),rtuChan(0), rtuJack(RTUStorage::nUnknown), rtuChan(0),
mtrType(MTR::mtUnknown), mtrType(MTR::mtUnknown),
q_num(0),q_count(1),mb_initOK(false),sm_initOK(false) q_num(0), q_count(1), mb_initOK(false), sm_initOK(false)
{} {}
ModbusRTU::ModbusData mbval; ModbusRTU::ModbusData mbval;
...@@ -198,7 +198,7 @@ class MBExchange: ...@@ -198,7 +198,7 @@ class MBExchange:
friend std::ostream& operator<<( std::ostream& os, RTUDevice& d ); friend std::ostream& operator<<( std::ostream& os, RTUDevice& d );
typedef std::map<ModbusRTU::ModbusAddr,RTUDevice*> RTUDeviceMap; typedef std::map<ModbusRTU::ModbusAddr, RTUDevice*> RTUDeviceMap;
friend std::ostream& operator<<( std::ostream& os, RTUDeviceMap& d ); friend std::ostream& operator<<( std::ostream& os, RTUDeviceMap& d );
void printMap(RTUDeviceMap& d); void printMap(RTUDeviceMap& d);
...@@ -215,9 +215,9 @@ class MBExchange: ...@@ -215,9 +215,9 @@ class MBExchange:
protected: protected:
virtual void step(); virtual void step();
virtual void sysCommand( const UniSetTypes::SystemMessage *msg ) override; virtual void sysCommand( const UniSetTypes::SystemMessage* msg ) 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 askSensors( UniversalIO::UIOCommand cmd ); virtual void askSensors( UniversalIO::UIOCommand cmd );
virtual void initOutput(); virtual void initOutput();
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
...@@ -228,9 +228,9 @@ class MBExchange: ...@@ -228,9 +228,9 @@ class MBExchange:
struct InitRegInfo struct InitRegInfo
{ {
InitRegInfo(): InitRegInfo():
dev(0),mbreg(0), dev(0), mbreg(0),
mbfunc(ModbusRTU::fnUnknown), mbfunc(ModbusRTU::fnUnknown),
initOK(false),ri(0) initOK(false), ri(0)
{} {}
RSProperty p; RSProperty p;
RTUDevice* dev; RTUDevice* dev;
...@@ -250,7 +250,7 @@ class MBExchange: ...@@ -250,7 +250,7 @@ class MBExchange:
InitList initRegList; /*!< список регистров для инициализации */ InitList initRegList; /*!< список регистров для инициализации */
UniSetTypes::uniset_rwmutex pollMutex; UniSetTypes::uniset_rwmutex pollMutex;
virtual std::shared_ptr<ModbusClient> initMB( bool reopen=false )= 0; virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) = 0;
virtual bool poll(); virtual bool poll();
bool pollRTU( RTUDevice* dev, RegMap::iterator& it ); bool pollRTU( RTUDevice* dev, RegMap::iterator& it );
...@@ -259,7 +259,7 @@ class MBExchange: ...@@ -259,7 +259,7 @@ class MBExchange:
void updateRTU(RegMap::iterator& it); void updateRTU(RegMap::iterator& it);
void updateMTR(RegMap::iterator& it); void updateMTR(RegMap::iterator& it);
void updateRTU188(RegMap::iterator& it); void updateRTU188(RegMap::iterator& it);
void updateRSProperty( RSProperty* p, bool write_only=false ); void updateRSProperty( RSProperty* p, bool write_only = false );
virtual void updateRespondSensors(); virtual void updateRespondSensors();
bool checkUpdateSM( bool wrFunc, long devMode ); bool checkUpdateSM( bool wrFunc, long devMode );
...@@ -286,7 +286,7 @@ class MBExchange: ...@@ -286,7 +286,7 @@ class MBExchange:
bool initRTUDevice( RTUDevice* d, UniXML::iterator& it ); bool initRTUDevice( RTUDevice* d, UniXML::iterator& it );
virtual bool initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it ); virtual bool initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it );
std::string initPropPrefix( const std::string& def_prop_prefix="" ); std::string initPropPrefix( const std::string& def_prop_prefix = "" );
void rtuQueryOptimization( RTUDeviceMap& m ); void rtuQueryOptimization( RTUDeviceMap& m );
......
...@@ -12,10 +12,10 @@ using namespace UniSetExtensions; ...@@ -12,10 +12,10 @@ using namespace UniSetExtensions;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
MBTCPMaster::MBTCPMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId, MBTCPMaster::MBTCPMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId,
const std::shared_ptr<SharedMemory> ic, const std::string& prefix ): const std::shared_ptr<SharedMemory> ic, const std::string& prefix ):
MBExchange(objId,shmId,ic,prefix), MBExchange(objId, shmId, ic, prefix),
force_disconnect(true), force_disconnect(true),
mbtcp(nullptr), mbtcp(nullptr),
pollThread(0) pollThread(0)
{ {
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBTCPMaster): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBTCPMaster): objId=-1?!! Use --" + prefix + "-name" );
...@@ -30,18 +30,20 @@ pollThread(0) ...@@ -30,18 +30,20 @@ pollThread(0)
// ---------- init MBTCP ---------- // ---------- init MBTCP ----------
string pname("--" + prefix + "-gateway-iaddr"); string pname("--" + prefix + "-gateway-iaddr");
iaddr = conf->getArgParam(pname,it.getProp("gateway_iaddr")); iaddr = conf->getArgParam(pname, it.getProp("gateway_iaddr"));
if( iaddr.empty() ) if( iaddr.empty() )
throw UniSetTypes::SystemError(myname+"(MBMaster): Unknown inet addr...(Use: " + pname +")" ); throw UniSetTypes::SystemError(myname + "(MBMaster): Unknown inet addr...(Use: " + pname + ")" );
string tmp("--" + prefix + "-gateway-port"); string tmp("--" + prefix + "-gateway-port");
port = conf->getArgInt(tmp,it.getProp("gateway_port")); port = conf->getArgInt(tmp, it.getProp("gateway_port"));
if( port <= 0 ) if( port <= 0 )
throw UniSetTypes::SystemError(myname+"(MBMaster): Unknown inet port...(Use: " + tmp +")" ); throw UniSetTypes::SystemError(myname + "(MBMaster): Unknown inet port...(Use: " + tmp + ")" );
dinfo << myname << "(init): gateway " << iaddr << ":" << port << endl; dinfo << myname << "(init): gateway " << iaddr << ":" << port << endl;
force_disconnect = conf->getArgInt("--" + prefix + "-persistent-connection",it.getProp("persistent_connection")) ? false : true; force_disconnect = conf->getArgInt("--" + prefix + "-persistent-connection", it.getProp("persistent_connection")) ? false : true;
dinfo << myname << "(init): persisten-connection=" << (!force_disconnect) << endl; dinfo << myname << "(init): persisten-connection=" << (!force_disconnect) << endl;
if( shm->isLocalwork() ) if( shm->isLocalwork() )
...@@ -51,10 +53,10 @@ pollThread(0) ...@@ -51,10 +53,10 @@ pollThread(0)
initDeviceList(); initDeviceList();
} }
else else
ic->addReadItem( sigc::mem_fun(this,&MBTCPMaster::readItem) ); ic->addReadItem( sigc::mem_fun(this, &MBTCPMaster::readItem) );
pollThread = new ThreadCreator<MBTCPMaster>(this, &MBTCPMaster::poll_thread); pollThread = new ThreadCreator<MBTCPMaster>(this, &MBTCPMaster::poll_thread);
pollThread->setFinalAction(this,&MBTCPMaster::final_thread); pollThread->setFinalAction(this, &MBTCPMaster::final_thread);
if( dlog()->is_info() ) if( dlog()->is_info() )
printMap(rmap); printMap(rmap);
...@@ -65,9 +67,11 @@ MBTCPMaster::~MBTCPMaster() ...@@ -65,9 +67,11 @@ MBTCPMaster::~MBTCPMaster()
if( pollThread ) if( pollThread )
{ {
pollThread->stop(); pollThread->stop();
if( pollThread->isRunning() ) if( pollThread->isRunning() )
pollThread->join(); pollThread->join();
} }
delete pollThread; delete pollThread;
mbtcp.reset(); mbtcp.reset();
} }
...@@ -89,7 +93,7 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen ) ...@@ -89,7 +93,7 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen )
mbtcp = std::make_shared<ModbusTCPMaster>(); mbtcp = std::make_shared<ModbusTCPMaster>();
ost::InetAddress ia(iaddr.c_str()); ost::InetAddress ia(iaddr.c_str());
mbtcp->connect(ia,port); mbtcp->connect(ia, port);
mbtcp->setForceDisconnect(force_disconnect); mbtcp->setForceDisconnect(force_disconnect);
if( recv_timeout > 0 ) if( recv_timeout > 0 )
...@@ -125,9 +129,10 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen ) ...@@ -125,9 +129,10 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen )
return mbtcp; return mbtcp;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBTCPMaster::sysCommand( const UniSetTypes::SystemMessage *sm ) void MBTCPMaster::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
MBExchange::sysCommand(sm); MBExchange::sysCommand(sm);
if( sm->command == SystemMessage::StartUp ) if( sm->command == SystemMessage::StartUp )
pollThread->start(); pollThread->start();
} }
...@@ -149,7 +154,7 @@ void MBTCPMaster::poll_thread() ...@@ -149,7 +154,7 @@ void MBTCPMaster::poll_thread()
try try
{ {
if( sidExchangeMode != DefaultObjectId && force ) if( sidExchangeMode != DefaultObjectId && force )
exchangeMode = shm->localGetValue(itExchangeMode,sidExchangeMode); exchangeMode = shm->localGetValue(itExchangeMode, sidExchangeMode);
} }
catch(...) catch(...)
{ {
...@@ -162,7 +167,7 @@ void MBTCPMaster::poll_thread() ...@@ -162,7 +167,7 @@ void MBTCPMaster::poll_thread()
} }
catch(...) catch(...)
{ {
// if( !checkProcActive() ) // if( !checkProcActive() )
throw; throw;
} }
...@@ -180,6 +185,7 @@ void MBTCPMaster::sigterm( int signo ) ...@@ -180,6 +185,7 @@ void MBTCPMaster::sigterm( int signo )
if( pollThread ) if( pollThread )
{ {
pollThread->stop(); pollThread->stop();
if( pollThread->isRunning() ) if( pollThread->isRunning() )
pollThread->join(); pollThread->join();
...@@ -198,7 +204,7 @@ void MBTCPMaster::sigterm( int signo ) ...@@ -198,7 +204,7 @@ void MBTCPMaster::sigterm( int signo )
catch( ... ) catch( ... )
{ {
std::exception_ptr p = std::current_exception(); std::exception_ptr p = std::current_exception();
std::clog <<(p ? p.__cxa_exception_type()->name() : "null") << std::endl; std::clog << (p ? p.__cxa_exception_type()->name() : "null") << std::endl;
} }
} }
...@@ -206,7 +212,7 @@ void MBTCPMaster::sigterm( int signo ) ...@@ -206,7 +212,7 @@ void MBTCPMaster::sigterm( int signo )
void MBTCPMaster::help_print( int argc, const char* const* argv ) void MBTCPMaster::help_print( int argc, const char* const* argv )
{ {
cout << "Default: prefix='mbtcp'" << endl; cout << "Default: prefix='mbtcp'" << endl;
MBExchange::help_print(argc,argv); MBExchange::help_print(argc, argv);
cout << endl; cout << endl;
cout << " Настройки протокола TCP: " << endl; cout << " Настройки протокола TCP: " << endl;
cout << "--prefix-gateway-iaddr hostname,IP - IP опрашиваемого узла" << endl; cout << "--prefix-gateway-iaddr hostname,IP - IP опрашиваемого узла" << endl;
...@@ -219,7 +225,8 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c ...@@ -219,7 +225,8 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c
const std::string& prefix ) const std::string& prefix )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","MBTCPMaster1"); string name = conf->getArgParam("--" + prefix + "-name", "MBTCPMaster1");
if( name.empty() ) if( name.empty() )
{ {
dcrit << "(MBTCPMaster): Не задан name'" << endl; dcrit << "(MBTCPMaster): Не задан name'" << endl;
...@@ -227,6 +234,7 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c ...@@ -227,6 +234,7 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c
} }
ObjectId ID = conf->getObjectID(name); ObjectId ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
dcrit << "(MBTCPMaster): идентификатор '" << name dcrit << "(MBTCPMaster): идентификатор '" << name
...@@ -236,6 +244,6 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c ...@@ -236,6 +244,6 @@ std::shared_ptr<MBTCPMaster> MBTCPMaster::init_mbmaster( int argc, const char* c
} }
dinfo << "(MBTCPMaster): name = " << name << "(" << ID << ")" << endl; dinfo << "(MBTCPMaster): name = " << name << "(" << ID << ")" << endl;
return make_shared<MBTCPMaster>(ID,icID,ic,prefix); return make_shared<MBTCPMaster>(ID, icID, ic, prefix);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -193,21 +193,21 @@ class MBTCPMaster: ...@@ -193,21 +193,21 @@ class MBTCPMaster:
public MBExchange public MBExchange
{ {
public: public:
MBTCPMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, MBTCPMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="mbtcp" ); const std::string& prefix = "mbtcp" );
virtual ~MBTCPMaster(); virtual ~MBTCPMaster();
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<MBTCPMaster> init_mbmaster( int argc, const char* const* argv, static std::shared_ptr<MBTCPMaster> init_mbmaster( int argc, const char* const* argv,
UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="mbtcp" ); const std::string& prefix = "mbtcp" );
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
protected: protected:
virtual void sysCommand( const UniSetTypes::SystemMessage *sm ) override; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual std::shared_ptr<ModbusClient> initMB( bool reopen=false ) override; virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override;
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
UniSetTypes::uniset_rwmutex mbMutex; UniSetTypes::uniset_rwmutex mbMutex;
......
...@@ -214,22 +214,22 @@ class MBTCPMultiMaster: ...@@ -214,22 +214,22 @@ class MBTCPMultiMaster:
public MBExchange public MBExchange
{ {
public: public:
MBTCPMultiMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, MBTCPMultiMaster( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="mbtcp" ); const std::string& prefix = "mbtcp" );
virtual ~MBTCPMultiMaster(); virtual ~MBTCPMultiMaster();
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<MBTCPMultiMaster> init_mbmaster( int argc, const char* const* argv, static std::shared_ptr<MBTCPMultiMaster> init_mbmaster( int argc, const char* const* argv,
UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic=nullptr, UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory> ic = nullptr,
const std::string& prefix="mbtcp" ); const std::string& prefix = "mbtcp" );
/*! глобальная функция для вывода help-а */ /*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv ); static void help_print( int argc, const char* const* argv );
protected: protected:
virtual void sysCommand( const UniSetTypes::SystemMessage *sm ) override; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void initIterators() override; virtual void initIterators() override;
virtual std::shared_ptr<ModbusClient> initMB( bool reopen=false ) override; virtual std::shared_ptr<ModbusClient> initMB( bool reopen = false ) override;
void poll_thread(); void poll_thread();
void check_thread(); void check_thread();
void final_thread(); void final_thread();
...@@ -243,11 +243,11 @@ class MBTCPMultiMaster: ...@@ -243,11 +243,11 @@ class MBTCPMultiMaster:
struct MBSlaveInfo struct MBSlaveInfo
{ {
MBSlaveInfo():ip(""),port(0),mbtcp(0),priority(0), MBSlaveInfo(): ip(""), port(0), mbtcp(0), priority(0),
respond(false),respond_id(UniSetTypes::DefaultObjectId),respond_invert(false), respond(false), respond_id(UniSetTypes::DefaultObjectId), respond_invert(false),
recv_timeout(200),aftersend_pause(0),sleepPause_usec(100), recv_timeout(200), aftersend_pause(0), sleepPause_usec(100),
force_disconnect(true), force_disconnect(true),
myname(""),initOK(false),ignore(false){} myname(""), initOK(false), ignore(false) {}
std::string ip; std::string ip;
int port; int port;
......
...@@ -86,3 +86,4 @@ pkgconfig_DATA = libUniSet2MBTCPMaster.pc libUniSet2RTU.pc ...@@ -86,3 +86,4 @@ pkgconfig_DATA = libUniSet2MBTCPMaster.pc libUniSet2RTU.pc
all-local: all-local:
ln -sf ../ModbusMaster/$(devel_include_HEADERS) ../include ln -sf ../ModbusMaster/$(devel_include_HEADERS) ../include
include $(top_builddir)/include.mk
...@@ -10,12 +10,12 @@ using namespace UniSetExtensions; ...@@ -10,12 +10,12 @@ using namespace UniSetExtensions;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
RTUExchange::RTUExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId, const std::shared_ptr<SharedMemory> ic, RTUExchange::RTUExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId, const std::shared_ptr<SharedMemory> ic,
const std::string& prefix_ ): const std::string& prefix_ ):
MBExchange(objId,shmId,ic,prefix_), MBExchange(objId, shmId, ic, prefix_),
mbrtu(0), mbrtu(0),
defSpeed(ComPort::ComSpeed38400), defSpeed(ComPort::ComSpeed38400),
use485F(false), use485F(false),
transmitCtl(false), transmitCtl(false),
rs_pre_clean(false) rs_pre_clean(false)
{ {
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(RTUExchange): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(RTUExchange): objId=-1?!! Use --" + prefix + "-name" );
...@@ -24,19 +24,22 @@ rs_pre_clean(false) ...@@ -24,19 +24,22 @@ rs_pre_clean(false)
// префикс для "свойств" - по умолчанию // префикс для "свойств" - по умолчанию
prop_prefix = ""; prop_prefix = "";
// если задано поле для "фильтрации" // если задано поле для "фильтрации"
// то в качестве префикса используем его // то в качестве префикса используем его
if( !s_field.empty() ) if( !s_field.empty() )
prop_prefix = s_field + "_"; prop_prefix = s_field + "_";
// если "принудительно" задан префикс // если "принудительно" задан префикс
// используем его. // используем его.
{ {
string p("--" + prefix + "-set-prop-prefix"); string p("--" + prefix + "-set-prop-prefix");
string v = conf->getArgParam(p,""); string v = conf->getArgParam(p, "");
if( !v.empty() && v[0] != '-' ) if( !v.empty() && v[0] != '-' )
prop_prefix = v; prop_prefix = v;
// если параметр всё-таки указан, считаем, что это попытка задать "пустой" префикс // если параметр всё-таки указан, считаем, что это попытка задать "пустой" префикс
else if( findArgParam(p,conf->getArgc(),conf->getArgv()) != -1 ) else if( findArgParam(p, conf->getArgc(), conf->getArgv()) != -1 )
prop_prefix = ""; prop_prefix = "";
} }
...@@ -45,21 +48,24 @@ rs_pre_clean(false) ...@@ -45,21 +48,24 @@ rs_pre_clean(false)
UniXML::iterator it(cnode); UniXML::iterator it(cnode);
// ---------- init RS ---------- // ---------- init RS ----------
devname = conf->getArgParam("--"+prefix+"-dev",it.getProp("device")); devname = conf->getArgParam("--" + prefix + "-dev", it.getProp("device"));
if( devname.empty() ) if( devname.empty() )
throw UniSetTypes::SystemError(myname+"(RTUExchange): Unknown device..." ); throw UniSetTypes::SystemError(myname + "(RTUExchange): Unknown device..." );
string speed = conf->getArgParam("--" + prefix + "-speed", it.getProp("speed"));
string speed = conf->getArgParam("--"+prefix+"-speed",it.getProp("speed"));
if( speed.empty() ) if( speed.empty() )
speed = "38400"; speed = "38400";
use485F = conf->getArgInt("--"+prefix+"-use485F",it.getProp("use485F")); use485F = conf->getArgInt("--" + prefix + "-use485F", it.getProp("use485F"));
transmitCtl = conf->getArgInt("--"+prefix+"-transmit-ctl",it.getProp("transmitCtl")); transmitCtl = conf->getArgInt("--" + prefix + "-transmit-ctl", it.getProp("transmitCtl"));
defSpeed = ComPort::getSpeed(speed); defSpeed = ComPort::getSpeed(speed);
sleepPause_usec = conf->getArgPInt("--" + prefix + "-sleepPause-usec",it.getProp("slepePause"), 100); sleepPause_usec = conf->getArgPInt("--" + prefix + "-sleepPause-usec", it.getProp("slepePause"), 100);
rs_pre_clean = conf->getArgInt("--" + prefix + "-pre-clean", it.getProp("pre_clean"));
rs_pre_clean = conf->getArgInt("--"+prefix+"-pre-clean",it.getProp("pre_clean"));
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
readConfiguration(); readConfiguration();
...@@ -67,7 +73,7 @@ rs_pre_clean(false) ...@@ -67,7 +73,7 @@ rs_pre_clean(false)
initDeviceList(); initDeviceList();
} }
else else
ic->addReadItem( sigc::mem_fun(this,&RTUExchange::readItem) ); ic->addReadItem( sigc::mem_fun(this, &RTUExchange::readItem) );
initMB(false); initMB(false);
...@@ -78,8 +84,8 @@ rs_pre_clean(false) ...@@ -78,8 +84,8 @@ rs_pre_clean(false)
void RTUExchange::help_print( int argc, const char* const* argv ) void RTUExchange::help_print( int argc, const char* const* argv )
{ {
cout << "Default: prefix='rs'" << endl; cout << "Default: prefix='rs'" << endl;
MBExchange::help_print(argc,argv); MBExchange::help_print(argc, argv);
// cout << " Настройки протокола RS: " << endl; // cout << " Настройки протокола RS: " << endl;
cout << "--prefix-dev devname - файл устройства" << endl; cout << "--prefix-dev devname - файл устройства" << endl;
cout << "--prefix-speed - Скорость обмена (9600,19920,38400,57600,115200)." << endl; cout << "--prefix-speed - Скорость обмена (9600,19920,38400,57600,115200)." << endl;
cout << "--prefix-my-addr - адрес текущего узла" << endl; cout << "--prefix-my-addr - адрес текущего узла" << endl;
...@@ -90,7 +96,7 @@ void RTUExchange::help_print( int argc, const char* const* argv ) ...@@ -90,7 +96,7 @@ void RTUExchange::help_print( int argc, const char* const* argv )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
RTUExchange::~RTUExchange() RTUExchange::~RTUExchange()
{ {
// delete mbrtu; // delete mbrtu;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen ) std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen )
...@@ -99,10 +105,11 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen ) ...@@ -99,10 +105,11 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen )
{ {
if( mbrtu ) if( mbrtu )
{ {
// delete mbrtu; // delete mbrtu;
mb = 0; mb = 0;
mbrtu = 0; mbrtu = 0;
} }
return mbrtu; return mbrtu;
} }
...@@ -111,14 +118,14 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen ) ...@@ -111,14 +118,14 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen )
if( !reopen ) if( !reopen )
return mbrtu; return mbrtu;
// delete mbrtu; // delete mbrtu;
mbrtu = 0; mbrtu = 0;
mb = 0; mb = 0;
} }
try try
{ {
mbrtu = std::make_shared<ModbusRTUMaster>(devname,use485F,transmitCtl); mbrtu = std::make_shared<ModbusRTUMaster>(devname, use485F, transmitCtl);
if( defSpeed != ComPort::ComSpeed0 ) if( defSpeed != ComPort::ComSpeed0 )
mbrtu->setSpeed(defSpeed); mbrtu->setSpeed(defSpeed);
...@@ -144,8 +151,8 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen ) ...@@ -144,8 +151,8 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen )
} }
catch(...) catch(...)
{ {
// if( mbrtu ) // if( mbrtu )
// delete mbrtu; // delete mbrtu;
mbrtu = 0; mbrtu = 0;
dinfo << myname << "(init): catch...." << endl; dinfo << myname << "(init): catch...." << endl;
...@@ -160,9 +167,9 @@ void RTUExchange::step() ...@@ -160,9 +167,9 @@ void RTUExchange::step()
try try
{ {
if( sidExchangeMode != DefaultObjectId && force ) if( sidExchangeMode != DefaultObjectId && force )
exchangeMode = shm->localGetValue(itExchangeMode,sidExchangeMode); exchangeMode = shm->localGetValue(itExchangeMode, sidExchangeMode);
} }
catch(...){} catch(...) {}
poll(); poll();
...@@ -177,9 +184,10 @@ bool RTUExchange::poll() ...@@ -177,9 +184,10 @@ bool RTUExchange::poll()
uniset_rwmutex_wrlock l(pollMutex); uniset_rwmutex_wrlock l(pollMutex);
pollActivated = false; pollActivated = false;
mb = initMB(false); mb = initMB(false);
if( !mb ) if( !mb )
{ {
for( auto &it: rmap ) for( auto& it : rmap )
it.second->resp_real = false; it.second->resp_real = false;
} }
} }
...@@ -207,7 +215,7 @@ bool RTUExchange::poll() ...@@ -207,7 +215,7 @@ bool RTUExchange::poll()
bool allNotRespond = true; bool allNotRespond = true;
ComPort::Speed s = mbrtu->getSpeed(); ComPort::Speed s = mbrtu->getSpeed();
for( auto it1: rmap ) for( auto it1 : rmap )
{ {
RTUDevice* d(it1.second); RTUDevice* d(it1.second);
...@@ -253,32 +261,35 @@ bool RTUExchange::poll() ...@@ -253,32 +261,35 @@ bool RTUExchange::poll()
<< " regs=" << d->regmap.size() << endl; << " regs=" << d->regmap.size() << endl;
d->resp_real = false; d->resp_real = false;
for( auto it=d->regmap.begin(); it!=d->regmap.end(); ++it )
for( auto it = d->regmap.begin(); it != d->regmap.end(); ++it )
{ {
try try
{ {
if( d->dtype==RTUExchange::dtRTU || d->dtype==RTUExchange::dtMTR ) if( d->dtype == RTUExchange::dtRTU || d->dtype == RTUExchange::dtMTR )
{ {
if( rs_pre_clean ) if( rs_pre_clean )
mb->cleanupChannel(); mb->cleanupChannel();
if( pollRTU(d,it) )
if( pollRTU(d, it) )
d->resp_real = true; d->resp_real = true;
} }
} }
catch( ModbusRTU::mbException& ex ) catch( ModbusRTU::mbException& ex )
{ {
// if( d->resp_real ) // if( d->resp_real )
// { // {
dlog3 << myname << "(poll): FAILED ask addr=" << ModbusRTU::addr2str(d->mbaddr) dlog3 << myname << "(poll): FAILED ask addr=" << ModbusRTU::addr2str(d->mbaddr)
<< " reg=" << ModbusRTU::dat2str(it->second->mbreg) << " reg=" << ModbusRTU::dat2str(it->second->mbreg)
<< " for sensors: "; print_plist(dlog()->level3(), it->second->slst); << " for sensors: ";
print_plist(dlog()->level3(), it->second->slst);
dlog()->level3() << " err: " << ex << endl; dlog()->level3() << " err: " << ex << endl;
// d->resp_real = false; // d->resp_real = false;
// } // }
} }
if( it==d->regmap.end() ) if( it == d->regmap.end() )
break; break;
if( !checkProcActive() ) if( !checkProcActive() )
...@@ -294,12 +305,12 @@ bool RTUExchange::poll() ...@@ -294,12 +305,12 @@ bool RTUExchange::poll()
updateSM(); updateSM();
// check thresholds // check thresholds
for( auto &t: thrlist ) for( auto& t : thrlist )
{ {
if( !checkProcActive() ) if( !checkProcActive() )
return false; return false;
IOBase::processingThreshold(&t,shm,force); IOBase::processingThreshold(&t, shm, force);
} }
if( trReopen.hi(allNotRespond) ) if( trReopen.hi(allNotRespond) )
...@@ -313,7 +324,7 @@ bool RTUExchange::poll() ...@@ -313,7 +324,7 @@ bool RTUExchange::poll()
ptReopen.reset(); ptReopen.reset();
} }
// printMap(rmap); // printMap(rmap);
return !allNotRespond; return !allNotRespond;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -322,7 +333,8 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char ...@@ -322,7 +333,8 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
string name = conf->getArgParam("--" + prefix + "-name","RTUExchange1"); string name = conf->getArgParam("--" + prefix + "-name", "RTUExchange1");
if( name.empty() ) if( name.empty() )
{ {
cerr << "(rtuexchange): Unknown 'name'. Use --" << prefix << "-name" << endl; cerr << "(rtuexchange): Unknown 'name'. Use --" << prefix << "-name" << endl;
...@@ -330,6 +342,7 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char ...@@ -330,6 +342,7 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char
} }
ObjectId ID = conf->getObjectID(name); ObjectId ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(rtuexchange): Not found ID for '" << name cerr << "(rtuexchange): Not found ID for '" << name
...@@ -339,15 +352,16 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char ...@@ -339,15 +352,16 @@ std::shared_ptr<RTUExchange> RTUExchange::init_rtuexchange( int argc, const char
} }
dinfo << "(rtuexchange): name = " << name << "(" << ID << ")" << endl; dinfo << "(rtuexchange): name = " << name << "(" << ID << ")" << endl;
return make_shared<RTUExchange>(ID,icID,ic,prefix); return make_shared<RTUExchange>(ID, icID, ic, prefix);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool RTUExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it ) bool RTUExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniXML::iterator& it )
{ {
if( !MBExchange::initDeviceInfo(m,a,it) ) if( !MBExchange::initDeviceInfo(m, a, it) )
return false; return false;
auto d = m.find(a); auto d = m.find(a);
if( d == m.end() ) if( d == m.end() )
{ {
dwarn << myname << "(initDeviceInfo): not found device for addr=" << ModbusRTU::addr2str(a) << endl; dwarn << myname << "(initDeviceInfo): not found device for addr=" << ModbusRTU::addr2str(a) << endl;
...@@ -355,9 +369,11 @@ bool RTUExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniX ...@@ -355,9 +369,11 @@ bool RTUExchange::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniX
} }
string s = it.getProp("speed"); string s = it.getProp("speed");
if( !s.empty() ) if( !s.empty() )
{ {
d->second->speed = ComPort::getSpeed(s); d->second->speed = ComPort::getSpeed(s);
if( d->second->speed == ComPort::ComSpeed0 ) if( d->second->speed == ComPort::ComSpeed0 )
{ {
d->second->speed = defSpeed; d->second->speed = defSpeed;
......
This diff is collapsed. Click to expand it.
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