You need to sign in or sign up before continuing.
Commit a27da390 authored by Pavel Vainerman's avatar Pavel Vainerman

DBServer-MySQL переехал в extensions. Для него создан отдельный pc-файл.

parent 97348da6
...@@ -2,16 +2,10 @@ ...@@ -2,16 +2,10 @@
# This file is part of the UniSet library # # This file is part of the UniSet library #
############################################################################ ############################################################################
UTILS = scripts Admin NullController SViewer-text \ SUBDIRS = scripts Admin NullController SViewer-text \
InfoServer SMonit MBTester codegen SImitator InfoServer SMonit MBTester codegen SImitator
#MapSourceParser ClassGen #MapSourceParser ClassGen
if DISABLE_MYSQL
SUBDIRS = ${UTILS}
else
SUBDIRS = ${UTILS} DBServer-MySQL
endif
include $(top_builddir)/conf/common.mk include $(top_builddir)/conf/common.mk
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
Name: libuniset Name: libuniset
Version: 1.0 Version: 1.0
Release: alt30 Release: alt31
Summary: UniSet - library for building distributed industrial control systems Summary: UniSet - library for building distributed industrial control systems
License: GPL License: GPL
Group: Development/C++ Group: Development/C++
...@@ -43,6 +43,16 @@ Obsoletes: %oname-mysql-dbserver ...@@ -43,6 +43,16 @@ Obsoletes: %oname-mysql-dbserver
%description mysql-dbserver %description mysql-dbserver
MySQL dbserver for %name MySQL dbserver for %name
%package mysql-devel
Group: Development/Databases
Summary: Libraries needed to develop for uniset MySQL
Requires: %name = %version-%release
Provides: %oname-mysql-devel
Obsoletes: %oname-mysql-devel
%description mysql-devel
Libraries needed to develop for uniset MySQL
%package utils %package utils
Summary: UniSet utilities Summary: UniSet utilities
Group: Development/Tools Group: Development/Tools
...@@ -54,7 +64,7 @@ Obsoletes: %oname-utils ...@@ -54,7 +64,7 @@ Obsoletes: %oname-utils
UniSet utilities UniSet utilities
%package doc %package doc
Group: Development/C Group: Development/C++
Summary: Documentations for developing with UniSet Summary: Documentations for developing with UniSet
Requires: lib%name = %version-%release Requires: lib%name = %version-%release
...@@ -62,7 +72,7 @@ Requires: lib%name = %version-%release ...@@ -62,7 +72,7 @@ Requires: lib%name = %version-%release
Documentations for developing with UniSet Documentations for developing with UniSet
%package extensions %package extensions
Group: Development/Databases Group: Development/C++
Summary: libUniSet extensions Summary: libUniSet extensions
Requires: %name = %version-%release Requires: %name = %version-%release
Provides: %oname-extentions Provides: %oname-extentions
...@@ -74,7 +84,7 @@ Obsoletes: %name-extentions ...@@ -74,7 +84,7 @@ Obsoletes: %name-extentions
Extensions for libuniset Extensions for libuniset
%package extensions-devel %package extensions-devel
Group: Development/Databases Group: Development/C++
Summary: Libraries needed to develop for uniset extensions Summary: Libraries needed to develop for uniset extensions
Requires: %name-extensions = %version-%release Requires: %name-extensions = %version-%release
Provides: %name-extentions-devel Provides: %name-extentions-devel
...@@ -135,6 +145,9 @@ rm -f %buildroot%_libdir/*.la ...@@ -135,6 +145,9 @@ rm -f %buildroot%_libdir/*.la
%_bindir/%oname-mysql-*dbserver %_bindir/%oname-mysql-*dbserver
%_libdir/*-mysql.so* %_libdir/*-mysql.so*
%files mysql-devel
%_pkgconfigdir/libUniSetMySQL.pc
%if_enabled doc %if_enabled doc
%files doc %files doc
%_docdir/%name %_docdir/%name
...@@ -186,10 +199,13 @@ rm -f %buildroot%_libdir/*.la ...@@ -186,10 +199,13 @@ rm -f %buildroot%_libdir/*.la
%_pkgconfigdir/libUniSetShared*.pc %_pkgconfigdir/libUniSetShared*.pc
%_pkgconfigdir/libUniSetNetwork*.pc %_pkgconfigdir/libUniSetNetwork*.pc
%_pkgconfigdir/libUniSetUNet*.pc %_pkgconfigdir/libUniSetUNet*.pc
#%_pkgconfigdir/libUniSetSMDBServer.pc #%_pkgconfigdir/libUniSetSMDBServer.pc
#%_pkgconfigdir/libUniSet*.pc #%_pkgconfigdir/libUniSet*.pc
%exclude %_pkgconfigdir/libUniSet.pc %exclude %_pkgconfigdir/libUniSet.pc
%changelog %changelog
* Wed May 11 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt30 * Wed May 11 2011 Pavel Vainerman <pv@altlinux.ru> 1.0-alt30
- add new function to UniversalInterface - add new function to UniversalInterface
......
...@@ -167,7 +167,6 @@ AC_CONFIG_FILES([Makefile ...@@ -167,7 +167,6 @@ AC_CONFIG_FILES([Makefile
Utilities/SMonit/Makefile Utilities/SMonit/Makefile
Utilities/InfoServer/Makefile Utilities/InfoServer/Makefile
Utilities/MBTester/Makefile Utilities/MBTester/Makefile
Utilities/DBServer-MySQL/Makefile
Utilities/SImitator/Makefile Utilities/SImitator/Makefile
Utilities/codegen/Makefile Utilities/codegen/Makefile
Utilities/codegen/uniset-codegen Utilities/codegen/uniset-codegen
...@@ -176,6 +175,8 @@ AC_CONFIG_FILES([Makefile ...@@ -176,6 +175,8 @@ AC_CONFIG_FILES([Makefile
extensions/libUniSetExtensions.pc extensions/libUniSetExtensions.pc
extensions/lib/Makefile extensions/lib/Makefile
extensions/include/Makefile extensions/include/Makefile
extensions/DBServer-MySQL/Makefile
extensions/DBServer-MySQL/libUniSetMySQL.pc
extensions/IOControl/Makefile extensions/IOControl/Makefile
extensions/IOControl/libUniSetIOControl.pc extensions/IOControl/libUniSetIOControl.pc
extensions/RTUExchange/Makefile extensions/RTUExchange/Makefile
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <sstream> #include <sstream>
#include "DBInterface.h" #include "DBInterface.h"
using namespace std; using namespace std;
...@@ -31,12 +31,12 @@ DBInterface::DBInterface(): ...@@ -31,12 +31,12 @@ DBInterface::DBInterface():
result(0), result(0),
lastQ(""), lastQ(""),
queryok(false) queryok(false)
{ {
mysql = new MYSQL(); mysql = new MYSQL();
} }
DBInterface::~DBInterface() DBInterface::~DBInterface()
{ {
close(); close();
delete mysql; delete mysql;
} }
...@@ -54,7 +54,7 @@ bool DBInterface::connect( const string host, const string user, const string ps ...@@ -54,7 +54,7 @@ bool DBInterface::connect( const string host, const string user, const string ps
mysql_close(mysql); mysql_close(mysql);
return false; return false;
} }
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -63,7 +63,7 @@ bool DBInterface::close() ...@@ -63,7 +63,7 @@ bool DBInterface::close()
mysql_close(mysql); mysql_close(mysql);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::insert(const string q) bool DBInterface::insert(const string q)
{ {
if( !mysql ) if( !mysql )
...@@ -74,11 +74,11 @@ bool DBInterface::insert(const string q) ...@@ -74,11 +74,11 @@ bool DBInterface::insert(const string q)
queryok=false; queryok=false;
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::query(const string q) bool DBInterface::query(const string q)
{ {
if( !mysql ) if( !mysql )
...@@ -90,7 +90,7 @@ bool DBInterface::query(const string q) ...@@ -90,7 +90,7 @@ bool DBInterface::query(const string q)
return false; return false;
} }
lastQ = q; lastQ = q;
result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows result = mysql_store_result(mysql); // _use_result - некорректно работает с _num_rows
if( numRows()==0 ) if( numRows()==0 )
...@@ -99,7 +99,7 @@ bool DBInterface::query(const string q) ...@@ -99,7 +99,7 @@ bool DBInterface::query(const string q)
return false; return false;
} }
queryok=true; queryok=true;
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -149,25 +149,25 @@ unsigned int DBInterface::numCols() ...@@ -149,25 +149,25 @@ unsigned int DBInterface::numCols()
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
unsigned int DBInterface::numRows() unsigned int DBInterface::numRows()
{ {
if( result ) if( result )
return mysql_num_rows(result); return mysql_num_rows(result);
return 0; return 0;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const MYSQL_ROW DBInterface::getRow() const MYSQL_ROW DBInterface::getRow()
{ {
return Row; return Row;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
const char* DBInterface::gethostinfo() const char* DBInterface::gethostinfo()
{ {
return mysql_get_host_info(mysql); return mysql_get_host_info(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
/* /*
bool DBInterface::createDB(const string dbname) bool DBInterface::createDB(const string dbname)
{ {
...@@ -177,7 +177,7 @@ bool DBInterface::createDB(const string dbname) ...@@ -177,7 +177,7 @@ bool DBInterface::createDB(const string dbname)
return true; return true;
return false; return false;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::dropDB(const string dbname) bool DBInterface::dropDB(const string dbname)
{ {
...@@ -186,7 +186,7 @@ bool DBInterface::dropDB(const string dbname) ...@@ -186,7 +186,7 @@ bool DBInterface::dropDB(const string dbname)
return false; return false;
} }
*/ */
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
MYSQL_RES* DBInterface::listFields(const string table, const string wild ) MYSQL_RES* DBInterface::listFields(const string table, const string wild )
{ {
if( !mysql || !result ) if( !mysql || !result )
...@@ -199,37 +199,37 @@ MYSQL_RES* DBInterface::listFields(const string table, const string wild ) ...@@ -199,37 +199,37 @@ MYSQL_RES* DBInterface::listFields(const string table, const string wild )
// MYSQL_FIELD *field = mysql_fetch_fields(res); // MYSQL_FIELD *field = mysql_fetch_fields(res);
// cout << field << " | "; // cout << field << " | ";
for( unsigned int i = 0; i<cols; i++) for( unsigned int i = 0; i<cols; i++)
{ {
cout << row[i] << " | "; cout << row[i] << " | ";
} }
return res; // mysql_list_fields(mysql, table,wild); return res; // mysql_list_fields(mysql, table,wild);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::moveToRow(int ind) bool DBInterface::moveToRow(int ind)
{ {
if(!mysql || !result) if(!mysql || !result)
return false; return false;
mysql_data_seek(result, ind); mysql_data_seek(result, ind);
return true; return true;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::ping() bool DBInterface::ping()
{ {
if(!mysql) if(!mysql)
return false; return false;
// внимание mysql_ping возвращает 0 // внимание mysql_ping возвращает 0
// если всё хорошо.... (поэтому мы инвертируем) // если всё хорошо.... (поэтому мы инвертируем)
return !mysql_ping(mysql); return !mysql_ping(mysql);
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
bool DBInterface::isConnection() bool DBInterface::isConnection()
{ {
return ping(); //!mysql; return ping(); //!mysql;
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string DBInterface::addslashes(const string& str) string DBInterface::addslashes(const string& str)
{ {
ostringstream tmp; ostringstream tmp;
...@@ -240,6 +240,6 @@ string DBInterface::addslashes(const string& str) ...@@ -240,6 +240,6 @@ string DBInterface::addslashes(const string& str)
tmp << "\\"; tmp << "\\";
tmp << str[i]; tmp << str[i];
} }
return tmp.str(); return tmp.str();
} }
...@@ -34,7 +34,7 @@ using std::string; ...@@ -34,7 +34,7 @@ using std::string;
class DBInterface class DBInterface
{ {
public: public:
DBInterface(); DBInterface();
~DBInterface(); ~DBInterface();
...@@ -46,14 +46,14 @@ class DBInterface ...@@ -46,14 +46,14 @@ class DBInterface
bool connect( const string host, const string user, const string pswd, bool connect( const string host, const string user, const string pswd,
const string dbname); const string dbname);
bool close(); bool close();
bool query(const string q); bool query(const string q);
const string lastQuery(); const string lastQuery();
bool insert(const string q); bool insert(const string q);
string addslashes(const string& str); string addslashes(const string& str);
/*! /*!
проверка связи с БД. проверка связи с БД.
в случае отсутсвия попытка восстановить... в случае отсутсвия попытка восстановить...
*/ */
...@@ -61,7 +61,7 @@ class DBInterface ...@@ -61,7 +61,7 @@ class DBInterface
/*! связь с БД установлена (была) */ /*! связь с БД установлена (была) */
bool isConnection(); bool isConnection();
bool nextRecord(); bool nextRecord();
void freeResult(); void freeResult();
...@@ -69,20 +69,20 @@ class DBInterface ...@@ -69,20 +69,20 @@ class DBInterface
unsigned int numRows(); unsigned int numRows();
bool moveToRow(int ind); bool moveToRow(int ind);
int insert_id(); int insert_id();
const MYSQL_ROW getRow(); const MYSQL_ROW getRow();
const string error(); const string error();
MYSQL_ROW Row; MYSQL_ROW Row;
// ******************* // *******************
const char* gethostinfo(); const char* gethostinfo();
protected: protected:
private: private:
MYSQL_RES *result; MYSQL_RES *result;
MYSQL *mysql; MYSQL *mysql;
string lastQ; string lastQ;
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
* \brief файл реализации DB-сервера * \brief файл реализации DB-сервера
* \author Pavel Vainerman * \author Pavel Vainerman
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <sys/time.h> #include <sys/time.h>
#include <sstream> #include <sstream>
...@@ -38,7 +38,7 @@ using namespace std; ...@@ -38,7 +38,7 @@ using namespace std;
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
DBServer_MySQL::DBServer_MySQL(ObjectId id): DBServer_MySQL::DBServer_MySQL(ObjectId id):
DBServer(id), DBServer(id),
db(new DBInterface()), db(new DBInterface()),
PingTime(300000), PingTime(300000),
...@@ -55,7 +55,7 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id): ...@@ -55,7 +55,7 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id):
} }
} }
DBServer_MySQL::DBServer_MySQL(): DBServer_MySQL::DBServer_MySQL():
DBServer(conf->getDBServer()), DBServer(conf->getDBServer()),
db(new DBInterface()), db(new DBInterface()),
PingTime(300000), PingTime(300000),
...@@ -93,10 +93,10 @@ void DBServer_MySQL::processingMessage( UniSetTypes::VoidMessage *msg ) ...@@ -93,10 +93,10 @@ void DBServer_MySQL::processingMessage( UniSetTypes::VoidMessage *msg )
timerInfo(&tm); timerInfo(&tm);
break; break;
} }
default: default:
DBServer::processingMessage(msg); DBServer::processingMessage(msg);
break; break;
} }
} }
...@@ -134,7 +134,7 @@ void DBServer_MySQL::parse( UniSetTypes::DBMessage* dbm ) ...@@ -134,7 +134,7 @@ void DBServer_MySQL::parse( UniSetTypes::DBMessage* dbm )
unideb[Debug::CRIT] << myname << "(dbmessage): не задан tblId...\n"; unideb[Debug::CRIT] << myname << "(dbmessage): не задан tblId...\n";
return; return;
} }
ostringstream query; ostringstream query;
switch( dbm->qtype ) switch( dbm->qtype )
{ {
...@@ -184,9 +184,9 @@ void DBServer_MySQL::parse( UniSetTypes::InfoMessage* im ) ...@@ -184,9 +184,9 @@ void DBServer_MySQL::parse( UniSetTypes::InfoMessage* im )
if( !writeToBase(ostr.str()) ) if( !writeToBase(ostr.str()) )
{ {
unideb[Debug::CRIT] << myname << "(insert): info msg error: "<< db->error() << endl; unideb[Debug::CRIT] << myname << "(insert): info msg error: "<< db->error() << endl;
// db->freeResult(); // db->freeResult();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am ) void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am )
...@@ -203,7 +203,7 @@ void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am ) ...@@ -203,7 +203,7 @@ void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am )
ostr << "INSERT INTO " << tblName(am->type); ostr << "INSERT INTO " << tblName(am->type);
ostr << "(num,node,id,date,time,time_usec,code,text,haracter,type,confirm,causeid) VALUES("; ostr << "(num,node,id,date,time,time_usec,code,text,haracter,type,confirm,causeid) VALUES(";
ostr << "NULL,'"<< am->node << "','" << am->id; ostr << "NULL,'"<< am->node << "','" << am->id;
ostr << "','" << ui.dateToString(am->tm.tv_sec,"/") << "','" ostr << "','" << ui.dateToString(am->tm.tv_sec,"/") << "','"
<< ui.timeToString(am->tm.tv_sec,":")<< "','" << am->tm.tv_usec; << ui.timeToString(am->tm.tv_sec,":")<< "','" << am->tm.tv_usec;
ostr << "','" << am->alarmcode<< "','" << message; ostr << "','" << am->alarmcode<< "','" << message;
ostr << "','" << am->character << "','" << am->type << "',0,'" << am->causecode << "')"; ostr << "','" << am->character << "','" << am->type << "',0,'" << am->causecode << "')";
...@@ -211,7 +211,7 @@ void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am ) ...@@ -211,7 +211,7 @@ void DBServer_MySQL::parse( UniSetTypes::AlarmMessage* am )
if( !writeToBase(ostr.str()) ) if( !writeToBase(ostr.str()) )
{ {
unideb[Debug::CRIT] << myname << "(insert): alarm msg error: "<< db->error() << endl; unideb[Debug::CRIT] << myname << "(insert): alarm msg error: "<< db->error() << endl;
// db->freeResult(); // db->freeResult();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
...@@ -222,19 +222,19 @@ void DBServer_MySQL::parse( UniSetTypes::ConfirmMessage* am ) ...@@ -222,19 +222,19 @@ void DBServer_MySQL::parse( UniSetTypes::ConfirmMessage* am )
query << "UPDATE " << tblName(am->orig_type) << " SET "; query << "UPDATE " << tblName(am->orig_type) << " SET ";
query << "confirm='" << ui.timeToString(am->tm.tv_sec,":") << "'"; query << "confirm='" << ui.timeToString(am->tm.tv_sec,":") << "'";
query << " where "; query << " where ";
query << " id='" << am->orig_id << "'"; query << " id='" << am->orig_id << "'";
query << " AND type='" << am->orig_type << "'"; query << " AND type='" << am->orig_type << "'";
query << " AND node='" << am->orig_node << "'"; query << " AND node='" << am->orig_node << "'";
query << " AND code='" << am->code << "'"; query << " AND code='" << am->code << "'";
// query << " AND cause='" << am->cause << "'"; // query << " AND cause='" << am->cause << "'";
query << " AND date='" << ui.dateToString(am->orig_tm.tv_sec,"/") << "'"; query << " AND date='" << ui.dateToString(am->orig_tm.tv_sec,"/") << "'";
query << " AND time='" << ui.timeToString(am->orig_tm.tv_sec,":") << "'"; query << " AND time='" << ui.timeToString(am->orig_tm.tv_sec,":") << "'";
query << " AND time_usec='" << am->orig_tm.tv_usec << "'"; query << " AND time_usec='" << am->orig_tm.tv_usec << "'";
if( !writeToBase(query.str()) ) if( !writeToBase(query.str()) )
{ {
unideb[Debug::CRIT] << myname << "(insert): confirm msg error: "<< db->error() << endl; unideb[Debug::CRIT] << myname << "(insert): confirm msg error: "<< db->error() << endl;
// db->freeResult(); // db->freeResult();
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
...@@ -245,13 +245,13 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -245,13 +245,13 @@ bool DBServer_MySQL::writeToBase( const string& query )
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
unideb[Debug::CRIT] << myname << "(writeToBase): соединение с БД не установлено\n" unideb[Debug::CRIT] << myname << "(writeToBase): соединение с БД не установлено\n"
<< myname << "(writeToBase): lost query: " << myname << "(writeToBase): lost query: "
<< query << endl; << query << endl;
return false; return false;
} }
db->query( query ); db->query( query );
// Дело в том что на INSERT И UPDATE запросы // Дело в том что на INSERT И UPDATE запросы
// db->query() может возвращать false и надо самому // db->query() может возвращать false и надо самому
// отдельно проверять действительно ли произошла ошибка // отдельно проверять действительно ли произошла ошибка
// см. DBInterface::query. // см. DBInterface::query.
...@@ -261,7 +261,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -261,7 +261,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
db->freeResult(); db->freeResult();
return true; return true;
} }
return false; return false;
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
...@@ -275,8 +275,8 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si ) ...@@ -275,8 +275,8 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si )
struct timezone tz; struct timezone tz;
gettimeofday(&si->tm,&tz); gettimeofday(&si->tm,&tz);
} }
// см. DBTABLE AnalogSensors, DigitalSensors // см. DBTABLE AnalogSensors, DigitalSensors
ostringstream data; ostringstream data;
data << " VALUES( "; data << " VALUES( ";
// Поля таблицы // Поля таблицы
...@@ -299,7 +299,7 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si ) ...@@ -299,7 +299,7 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si )
table = "DigitalSensors(num,node,id,date,time,time_usec,state)"; table = "DigitalSensors(num,node,id,date,time,time_usec,state)";
data << si->state; // state data << si->state; // state
break; break;
case UniversalIO::AnalogInput: case UniversalIO::AnalogInput:
case UniversalIO::AnalogOutput: case UniversalIO::AnalogOutput:
table = "AnalogSensors(num,node,id,date,time,time_usec,value)"; table = "AnalogSensors(num,node,id,date,time,time_usec,value)";
...@@ -316,18 +316,18 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si ) ...@@ -316,18 +316,18 @@ void DBServer_MySQL::parse( UniSetTypes::SensorMessage *si )
if( !writeToBase("INSERT INTO "+table+data.str()) ) if( !writeToBase("INSERT INTO "+table+data.str()) )
{ {
unideb[Debug::CRIT] << myname << "(insert) sensor msg error: "<< db->error() << endl; unideb[Debug::CRIT] << myname << "(insert) sensor msg error: "<< db->error() << endl;
db->freeResult(); db->freeResult();
} }
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
unideb[Debug::CRIT] << myname << "(parse SensorMessage): " << ex << endl; unideb[Debug::CRIT] << myname << "(parse SensorMessage): " << ex << endl;
} }
catch( ... ) catch( ... )
{ {
unideb[Debug::CRIT] << myname << "(parse SensorMessage): неизвестное исключние..." << endl; unideb[Debug::CRIT] << myname << "(parse SensorMessage): неизвестное исключние..." << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::init_dbserver() void DBServer_MySQL::init_dbserver()
...@@ -337,7 +337,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -337,7 +337,7 @@ void DBServer_MySQL::init_dbserver()
if( connect_ok ) if( connect_ok )
{ {
initDBTableMap(tblMap); initDBTableMap(tblMap);
initDB(db); initDB(db);
return; return;
} }
...@@ -346,7 +346,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -346,7 +346,7 @@ void DBServer_MySQL::init_dbserver()
{ {
ostringstream msg; ostringstream msg;
msg << myname << "(init): на данном узле DBServer - отключён." msg << myname << "(init): на данном узле DBServer - отключён."
<< " В " << conf->getConfFileName() << " В " << conf->getConfFileName()
<< " для данного узла указан параметр dbserver=''"; << " для данного узла указан параметр dbserver=''";
throw NameNotFound(msg.str()); throw NameNotFound(msg.str());
} }
...@@ -364,22 +364,22 @@ void DBServer_MySQL::init_dbserver() ...@@ -364,22 +364,22 @@ void DBServer_MySQL::init_dbserver()
tblMap[UniSetTypes::Message::Info] = "Messages"; tblMap[UniSetTypes::Message::Info] = "Messages";
tblMap[UniSetTypes::Message::Alarm] = "Messages"; tblMap[UniSetTypes::Message::Alarm] = "Messages";
tblMap[UniSetTypes::Message::SensorInfo] = "AnalogSensors"; tblMap[UniSetTypes::Message::SensorInfo] = "AnalogSensors";
PingTime = conf->getIntProp(node,"pingTime"); PingTime = conf->getIntProp(node,"pingTime");
ReconnectTime = conf->getIntProp(node,"reconnectTime"); ReconnectTime = conf->getIntProp(node,"reconnectTime");
if( dbnode.empty() ) if( dbnode.empty() )
dbnode = "localhost"; dbnode = "localhost";
unideb[Debug::INFO] << myname << "(init): connect dbnode=" << dbnode unideb[Debug::INFO] << myname << "(init): connect dbnode=" << dbnode
<< "\tdbname=" << dbname << "\tdbname=" << dbname
<< " pingTime=" << PingTime << " pingTime=" << PingTime
<< " ReconnectTime=" << ReconnectTime << endl; << " ReconnectTime=" << ReconnectTime << endl;
if( !db->connect(dbnode, user, password, dbname) ) if( !db->connect(dbnode, user, password, dbname) )
{ {
// ostringstream err; // ostringstream err;
unideb[Debug::CRIT] << myname unideb[Debug::CRIT] << myname
<< "(init): не смог создать соединение с БД err:\n" << "(init): не смог создать соединение с БД err:\n"
<< db->error() << endl; << db->error() << endl;
// throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) ); // throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) );
...@@ -393,7 +393,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -393,7 +393,7 @@ void DBServer_MySQL::init_dbserver()
askTimer(DBServer_MySQL::PingTimer,PingTime); askTimer(DBServer_MySQL::PingTimer,PingTime);
// createTables(db); // createTables(db);
initDB(db); initDB(db);
initDBTableMap(tblMap); initDBTableMap(tblMap);
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
...@@ -416,7 +416,7 @@ void DBServer_MySQL::createTables( DBInterface *db ) ...@@ -416,7 +416,7 @@ void DBServer_MySQL::createTables( DBInterface *db )
if( !db->query(query.str()) ) if( !db->query(query.str()) )
unideb[Debug::CRIT] << myname << "(createTables): error: \t\t" << db->error() << endl; unideb[Debug::CRIT] << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::timerInfo( UniSetTypes::TimerMessage* tm ) void DBServer_MySQL::timerInfo( UniSetTypes::TimerMessage* tm )
...@@ -439,7 +439,7 @@ void DBServer_MySQL::timerInfo( UniSetTypes::TimerMessage* tm ) ...@@ -439,7 +439,7 @@ void DBServer_MySQL::timerInfo( UniSetTypes::TimerMessage* tm )
} }
} }
break; break;
case DBServer_MySQL::ReconnectTimer: case DBServer_MySQL::ReconnectTimer:
{ {
unideb[Debug::INFO] << myname << "(timerInfo): reconnect timer" << endl; unideb[Debug::INFO] << myname << "(timerInfo): reconnect timer" << endl;
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
/*! \file /*! \file
* \author Pavel Vainerman * \author Pavel Vainerman
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#ifndef DBServer_MySQL_H_ #ifndef DBServer_MySQL_H_
#define DBServer_MySQL_H_ #define DBServer_MySQL_H_
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
//------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------
/*! /*!
\page page_DBServer_MySQL (DBServer_MySQL) Реализация сервиса ведения БД на основе MySQL \page page_DBServer_MySQL (DBServer_MySQL) Реализация сервиса ведения БД на основе MySQL
- \ref sec_DBS_Comm - \ref sec_DBS_Comm
- \ref sec_DBS_Conf - \ref sec_DBS_Conf
- \ref sec_DBS_Tables - \ref sec_DBS_Tables
...@@ -40,14 +40,14 @@ ...@@ -40,14 +40,14 @@
\section sec_DBS_Comm Общее описание работы DBServer_MySQL \section sec_DBS_Comm Общее описание работы DBServer_MySQL
Сервис предназначен для работы с БД MySQL. В его задачи входит Сервис предназначен для работы с БД MySQL. В его задачи входит
сохранение всех событий происходищих в системе в БД. К этим сохранение всех событий происходищих в системе в БД. К этим
событиям относятся изменение состояния датчиков, различные логи событиям относятся изменение состояния датчиков, различные логи
работы процессов и т.п. работы процессов и т.п.
К моменту запуска, подразумевается, что неободимые таблицы уже К моменту запуска, подразумевается, что неободимые таблицы уже
созданы, все необходимые настройки mysql сделаны. созданы, все необходимые настройки mysql сделаны.
\par \par
При работе с БД, сервис в основном пишет в БД. Обработка накопленных данных При работе с БД, сервис в основном пишет в БД. Обработка накопленных данных
ведётся уже другими программами (web-интерфейс). ведётся уже другими программами (web-интерфейс).
\par \par
Для повышения надежности DBServer переодически ( DBServer_MySQL::PingTimer ) проверяет наличие связи с сервером БД. Для повышения надежности DBServer переодически ( DBServer_MySQL::PingTimer ) проверяет наличие связи с сервером БД.
В случае если связь пропала (или не была установлена при старте) DBServer пытается вновь переодически ( DBServer::ReconnectTimer ) В случае если связь пропала (или не была установлена при старте) DBServer пытается вновь переодически ( DBServer::ReconnectTimer )
...@@ -56,19 +56,19 @@ ...@@ -56,19 +56,19 @@
новые настройки. новые настройки.
\todo Может не сохранять текст, если задан код... (для экономии в БД) \todo Может не сохранять текст, если задан код... (для экономии в БД)
\section sec_DBS_Conf Настройка DBServer \section sec_DBS_Conf Настройка DBServer
Объект DBServer берёт настройки из конфигурационного файла из секции \b<LocalDBServer>. Объект DBServer берёт настройки из конфигурационного файла из секции \b<LocalDBServer>.
Возможно задать следующие параметры: Возможно задать следующие параметры:
- \b dbname - название БД - \b dbname - название БД
- \b dbnode - узел БД - \b dbnode - узел БД
- \b dbuser - пользователь - \b dbuser - пользователь
- \b dbpass - пароль для доступа к БД - \b dbpass - пароль для доступа к БД
- \b pingTime - период проверки связи с сервером MySQL - \b pingTime - период проверки связи с сервером MySQL
- \b reconnectTime - время повторной попытки соединения с БД - \b reconnectTime - время повторной попытки соединения с БД
\section sec_DBS_Tables Таблицы MySQL \section sec_DBS_Tables Таблицы MySQL
К основным таблицам относятся следующие: К основным таблицам относятся следующие:
\code \code
...@@ -128,9 +128,9 @@ CREATE TABLE SensorsThreshold ( ...@@ -128,9 +128,9 @@ CREATE TABLE SensorsThreshold (
) TYPE=MyISAM; ) TYPE=MyISAM;
\endcode \endcode
*/ */
class DBServer_MySQL: class DBServer_MySQL:
public DBServer public DBServer
{ {
public: public:
...@@ -158,7 +158,7 @@ class DBServer_MySQL: ...@@ -158,7 +158,7 @@ class DBServer_MySQL:
bool writeToBase( const string& query ); bool writeToBase( const string& query );
virtual void init_dbserver(); virtual void init_dbserver();
void createTables( DBInterface* db ); void createTables( DBInterface* db );
inline const char* tblName(int key) inline const char* tblName(int key)
{ {
return tblMap[key].c_str(); return tblMap[key].c_str();
......
if DISABLE_MYSQL
else
UMYSQL_VER=@LIBVER@ UMYSQL_VER=@LIBVER@
lib_LTLIBRARIES = libUniSet-mysql.la lib_LTLIBRARIES = libUniSet-mysql.la
libUniSet_mysql_la_LDFLAGS = -version-info $(UMYSQL_VER) libUniSet_mysql_la_LDFLAGS = -version-info $(UMYSQL_VER)
libUniSet_mysql_la_SOURCES = DBInterface.cc DBServer_MySQL.cc libUniSet_mysql_la_SOURCES = DBInterface.cc DBServer_MySQL.cc
libUniSet_mysql_la_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient libUniSet_mysql_la_LIBADD = $(top_builddir)/lib/libUniSet.la -lmysqlclient
...@@ -14,3 +18,5 @@ include $(top_builddir)/conf/setting.mk ...@@ -14,3 +18,5 @@ include $(top_builddir)/conf/setting.mk
# install # install
devel_include_HEADERS = *.h devel_include_HEADERS = *.h
devel_includedir = $(includedir)/@PACKAGE@/mysql devel_includedir = $(includedir)/@PACKAGE@/mysql
endif
\ No newline at end of file
...@@ -125,7 +125,7 @@ CREATE TABLE Network( ...@@ -125,7 +125,7 @@ CREATE TABLE Network(
num int(11) NOT NULL auto_increment, num int(11) NOT NULL auto_increment,
date date NOT NULL default '0000-00-00', date date NOT NULL default '0000-00-00',
time time NOT NULL default '00:00:00', time time NOT NULL default '00:00:00',
time_usec int(8) unsigned default 0, time_usec int(8) unsigned default 0,
master int(3) default NULL, master int(3) default NULL,
slave int(3) default NULL, slave int(3) default NULL,
connection int(2) default NULL, connection int(2) default NULL,
......
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: libUniSetMySQL
Description: Support library for libUniSetMySQL
Requires: libUniSet
Version: 1.0.0
Libs: -L${libdir} -lUniSet-mysql -lmysqlclient
Cflags: -I${includedir}/uniset -I${includedir}/mysql
...@@ -31,14 +31,14 @@ int main(int argc, char** argv) ...@@ -31,14 +31,14 @@ int main(int argc, char** argv)
{ {
if( ID != UniSetTypes::DefaultObjectId ) if( ID != UniSetTypes::DefaultObjectId )
{ {
unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в " unideb[Debug::WARN] << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl; << conf->getConfFileName() << endl;
} }
ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name); ID = conf->oind->getIdByName(conf->getServicesSection()+"/"+name);
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): идентификатор '" << name cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!" << "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl; << " в секции " << conf->getServicesSection() << endl;
return 1; return 1;
...@@ -46,7 +46,7 @@ int main(int argc, char** argv) ...@@ -46,7 +46,7 @@ int main(int argc, char** argv)
} }
else if( ID == UniSetTypes::DefaultObjectId ) else if( ID == UniSetTypes::DefaultObjectId )
{ {
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl; cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage(); short_usage();
return 1; return 1;
} }
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
if HAVE_EXTENTIONS if HAVE_EXTENTIONS
SUBDIRS = lib include SharedMemory IOControl RTUExchange LogicProcessor \ SUBDIRS = lib include SharedMemory IOControl RTUExchange LogicProcessor \
ModbusSlave MBTCPMaster SMViewer UniNetwork UNet2 ModbusSlave MBTCPMaster SMViewer UniNetwork UNet2 DBServer-MySQL
#SMDBServer #SMDBServer
#SharedMemoryPlus #SharedMemoryPlus
#UDPExchange #UDPExchange
......
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