Commit b438c2e7 authored by Pavel Vainerman's avatar Pavel Vainerman

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

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