Commit 5881c1e2 authored by Pavel Vainerman's avatar Pavel Vainerman

Убрал конструкор копирования и оператор присваивания для rwmutex-ов.

Разрешил "перемещение" и исправил везде по коду все места, где обнаружились ошибки (т.е. прямое или косвенное копирование rwmutex-а). Помимо этого где "заметил" попытался воспользоваться для оптимизации "перемещением" (std::move)
parent b605e8f7
......@@ -622,8 +622,8 @@ int logRotate( const string& arg, UInterface &ui )
return 1;
}
SystemMessage sm(SystemMessage::LogRotate);
TransportMessage tm(sm.transport_msg());
TransportMessage tm( std::move(SystemMessage(SystemMessage::LogRotate).transport_msg()) );
ui.send(id,tm);
cout << "\nSend 'LogRotate' to " << arg << " OK.\n";
}
......@@ -650,8 +650,8 @@ int configure( const string& arg, UInterface &ui )
cout << "(configure): name='" << arg << "' не найдено!!!\n";
return 1;
}
SystemMessage sm(SystemMessage::ReConfiguration);
TransportMessage tm(sm.transport_msg());
TransportMessage tm( std::move( SystemMessage(SystemMessage::ReConfiguration).transport_msg() ));
ui.send(id,tm);
cout << "\nSend 'ReConfigure' to " << arg << " OK.\n";
}
......
......@@ -8,7 +8,7 @@
Name: libuniset2
Version: 2.0
Release: alt2
Release: alt3
Summary: UniSet - library for building distributed industrial control systems
......@@ -333,6 +333,9 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%exclude %_pkgconfigdir/libUniSet2.pc
%changelog
* Sat Feb 22 2014 Pavel Vainerman <pv@altlinux.ru> 2.0-alt3
- use std::move
* Thu Feb 20 2014 Pavel Vainerman <pv@altlinux.ru> 2.0-alt2
- rename 'disactivate' --> 'deactivate'
......
......@@ -173,7 +173,7 @@
<iocards>
<item card="1" name="DI32"/>
<item card="2" name="DO32"/>
<item baddr="0x110" card="3" dev="/dev/comedi1" name="UNIO48" subdev1="TBI24_0" subdev2="TBI16_8"/>
<item baddr="0x110" card="3" dev="/dev/null" name="UNIO48" subdev1="TBI24_0" subdev2="TBI16_8"/>
</iocards>
</item>
<item id="3001" infserver="InfoServer" ip="127.0.0.1" name="LocalhostNode1" textname="Локальный узел" unet_ignore="0" unet_port="2049"/>
......
......@@ -696,7 +696,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
}
inf.subdev = it.getIntProp("subdev");
if( inf.subdev < 0 )
inf.subdev = DefaultSubdev;
......@@ -775,7 +775,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
<< " priority=" << prior << endl;
}
iomap[maxItem++] = inf;
iomap[maxItem++] = std::move(inf);
return true;
}
// ------------------------------------------------------------------------------------------
......
......@@ -211,6 +211,13 @@ class IOControl:
struct IOInfo:
public IOBase
{
// т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
IOInfo( const IOInfo& r ) = delete;
IOInfo& operator=(const IOInfo& r) = delete;
IOInfo( IOInfo&& r ) = default;
IOInfo& operator=(IOInfo&& r) = default;
IOInfo():
subdev(DefaultSubdev),channel(DefaultChannel),
ncard(-1),
......
......@@ -15,5 +15,5 @@ uniset2-start.sh -f ./uniset2-iocontrol --smemory-id SharedMemory \
--io-test-lamp Input1_S \
--io-heartbeat-id AI_AS \
--io-sm-ready-test-sid Input1_S \
--ulog-add-levels info,crit,warn,level9,system
--ulog-add-levels any --dlog-add-levels any
......@@ -593,7 +593,7 @@ bool MBExchange::preInitRead( InitList::iterator& p )
for( unsigned int i=0; i<ret.bcnt; i++ )
{
ModbusRTU::DataBits b(ret.data[i]);
for( unsigned int k=0;k<ModbusRTU::BitsPerByte && m<q_count; k++,m++ )
for( int k=0;k<ModbusRTU::BitsPerByte && m<q_count; k++,m++ )
dat[m] = b[k];
}
......@@ -610,7 +610,7 @@ bool MBExchange::preInitRead( InitList::iterator& p )
for( unsigned int i=0; i<ret.bcnt; i++ )
{
ModbusRTU::DataBits b(ret.data[i]);
for( unsigned int k=0;k<ModbusRTU::BitsPerByte && m<q_count; k++,m++ )
for( int k=0;k<ModbusRTU::BitsPerByte && m<q_count; k++,m++ )
dat[m] = b[k];
}
......@@ -830,7 +830,7 @@ bool MBExchange::pollRTU( RTUDevice* dev, RegMap::iterator& it )
for( unsigned int i=0; i<ret.bcnt; i++ )
{
ModbusRTU::DataBits b(ret.data[i]);
for( unsigned int k=0;k<ModbusRTU::BitsPerByte && m<p->q_count; k++,it++,m++ )
for( int k=0;k<ModbusRTU::BitsPerByte && m<p->q_count; k++,it++,m++ )
it->second->mbval = b[k];
}
it--;
......@@ -1722,8 +1722,7 @@ MBExchange::RTUDevice* MBExchange::addDev( RTUDeviceMap& mp, ModbusRTU::ModbusAd
}
// ------------------------------------------------------------------------------------------
MBExchange::RegInfo* MBExchange::addReg( RegMap& mp, RegID id, ModbusRTU::ModbusData r,
UniXML_iterator& xmlit, MBExchange::RTUDevice* dev,
MBExchange::RegInfo* rcopy )
UniXML_iterator& xmlit, MBExchange::RTUDevice* dev )
{
auto it = mp.find(id);
if( it != mp.end() )
......@@ -1751,24 +1750,14 @@ MBExchange::RegInfo* MBExchange::addReg( RegMap& mp, RegID id, ModbusRTU::Modbus
return it->second;
}
MBExchange::RegInfo* ri;
if( rcopy )
{
ri = new MBExchange::RegInfo(*rcopy);
ri->slst.clear();
ri->mbreg = r;
}
else
MBExchange::RegInfo* ri = new MBExchange::RegInfo();
if( !initRegInfo(ri,xmlit,dev) )
{
ri = new MBExchange::RegInfo();
if( !initRegInfo(ri,xmlit,dev) )
{
delete ri;
return 0;
}
ri->mbreg = r;
delete ri;
return 0;
}
ri->mbreg = r;
ri->id = id;
mp.insert(RegMap::value_type(id,ri));
......@@ -1777,7 +1766,7 @@ MBExchange::RegInfo* MBExchange::addReg( RegMap& mp, RegID id, ModbusRTU::Modbus
return ri;
}
// ------------------------------------------------------------------------------------------
MBExchange::RSProperty* MBExchange::addProp( PList& plist, RSProperty& p )
MBExchange::RSProperty* MBExchange::addProp( PList& plist, RSProperty&& p )
{
for( auto &it: plist )
{
......@@ -1785,7 +1774,7 @@ MBExchange::RSProperty* MBExchange::addProp( PList& plist, RSProperty& p )
return &it;
}
plist.push_back(p);
plist.push_back( std::move(p) );
auto it = plist.end();
--it;
return &(*it);
......@@ -1800,10 +1789,9 @@ bool MBExchange::initRSProperty( RSProperty& p, UniXML_iterator& it )
// тогда заносим его в отдельный список
if( p.t_ai != DefaultObjectId )
{
// испольуем конструктор копирования, чтобы сформировать IOBase
// через преобразование указателя к базовому классу
IOBase b( *(static_cast<IOBase*>(&p)) );
thrlist.push_back(b);
// испольуем конструктор копирования
// IOBase b( *(static_cast<IOBase*>(&p)));
thrlist.push_back( std::move(p) );
return true;
}
......@@ -2122,7 +2110,7 @@ bool MBExchange::initItem( UniXML_iterator& it )
}
RSProperty* p1 = addProp(ri->slst,p);
RSProperty* p1 = addProp(ri->slst, std::move(p) );
if( !p1 )
return false;
......@@ -2136,7 +2124,7 @@ bool MBExchange::initItem( UniXML_iterator& it )
for( unsigned int i=1; i<p1->rnum; i++ )
{
RegID id1 = genRegID(mbreg+i,ri->mbfunc);
RegInfo* r = addReg(dev->regmap,id1,mbreg+i,it,dev,ri);
RegInfo* r = addReg(dev->regmap,id1,mbreg+i,it,dev);
r->q_num=i+1;
r->q_count=1;
r->mbfunc = ri->mbfunc;
......@@ -2165,8 +2153,8 @@ bool MBExchange::initItem( UniXML_iterator& it )
bool need_init = it.getIntProp(prop_prefix + "preinit");
if( need_init && ModbusRTU::isWriteFunction(ri->mbfunc) )
{
InitRegInfo ii;
ii.p = p;
InitRegInfo ii;
ii.p = std::move(p);
ii.dev = dev;
ii.ri = ri;
......@@ -2208,12 +2196,12 @@ bool MBExchange::initItem( UniXML_iterator& it )
break;
default:
ii.mbfunc = ModbusRTU::fnReadOutputRegisters;
ii.mbfunc = ModbusRTU::fnReadOutputRegisters;
break;
}
}
initRegList.push_back(ii);
initRegList.push_back( std::move(ii) );
ri->mb_initOK = false;
ri->sm_initOK = false;
}
......
......@@ -78,6 +78,13 @@ class MBExchange:
nbyte(0),reg(0)
{}
// т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
RSProperty( const RSProperty& r ) = delete;
RSProperty& operator=(const RSProperty& r) = delete;
RSProperty( RSProperty&& r ) = default;
RSProperty& operator=(RSProperty&& r) = default;
RegInfo* reg;
};
......@@ -91,6 +98,13 @@ class MBExchange:
typedef std::map<RegID,RegInfo*> RegMap;
struct RegInfo
{
// т.к. RSProperty содержит rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
RegInfo( const RegInfo& r ) = default;
RegInfo& operator=(const RegInfo& r) = delete;
RegInfo( RegInfo&& r ) = delete;
RegInfo& operator=(RegInfo&& r) = default;
RegInfo():
mbval(0),mbreg(0),mbfunc(ModbusRTU::fnUnknown),
id(0),dev(0),
......@@ -261,9 +275,8 @@ class MBExchange:
void initOffsetList();
RTUDevice* addDev( RTUDeviceMap& dmap, ModbusRTU::ModbusAddr a, UniXML_iterator& it );
RegInfo* addReg( RegMap& rmap, RegID id, ModbusRTU::ModbusData r, UniXML_iterator& it,
RTUDevice* dev, RegInfo* rcopy=0 );
RSProperty* addProp( PList& plist, RSProperty& p );
RegInfo* addReg( RegMap& rmap, RegID id, ModbusRTU::ModbusData r, UniXML_iterator& it, RTUDevice* dev );
RSProperty* addProp( PList& plist, RSProperty&& p );
bool initMTRitem( UniXML_iterator& it, RegInfo* p );
bool initRTU188item( UniXML_iterator& it, RegInfo* p );
......
......@@ -847,8 +847,8 @@ bool MBSlave::initItem( UniXML_iterator& it )
{
p.vtype = VTypes::vtUnknown;
p.wnum = 0;
iomap[p.mbreg] = p;
dinfo << myname << "(initItem): add " << p << endl;
iomap[p.mbreg] = std::move(p);
}
else
{
......@@ -867,8 +867,8 @@ bool MBSlave::initItem( UniXML_iterator& it )
{
p.mbreg += i;
p.wnum+= i;
iomap[p.mbreg] = p;
dinfo << myname << "(initItem): add " << p << endl;
iomap[p.mbreg] = std::move(p);
}
}
......
......@@ -126,7 +126,7 @@ SharedMemory::~SharedMemory()
delete restorer;
restorer = NULL;
}
delete wdt;
}
......@@ -164,13 +164,13 @@ void SharedMemory::sysCommand( const SystemMessage *sm )
case SystemMessage::StartUp:
{
PassiveTimer ptAct(activateTimeout);
while( !isActivated() && !ptAct.checkTime() )
while( !activated && !ptAct.checkTime() )
{
cout << myname << "(sysCommand): wait activate..." << endl;
msleep(100);
}
if( !isActivated() )
if( !activated )
dcrit << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
// подождать пока пройдёт инициализация
......@@ -472,16 +472,16 @@ void SharedMemory::readEventList( const std::string& oname )
// -----------------------------------------------------------------------------
void SharedMemory::sendEvent( UniSetTypes::SystemMessage& sm )
{
TransportMessage tm(sm.transport_msg());
for( auto &it: elst )
{
bool ok = false;
sm.consumer = it;
for( unsigned int i=0; i<2; i++ )
{
try
{
ui.send(it,tm);
ui.send(it, std::move(sm.transport_msg()) );
ok = true;
break;
}
......@@ -625,25 +625,20 @@ void SharedMemory::saveHistory()
{
if( hist.empty() )
return;
// if( dlog.is_info() )
// dlog.info() << myname << "(saveHistory): ..." << endl;
for( auto &it: hist )
{
for( auto &hit: it.hlst )
{
if( hit.ioit != myioEnd() )
hit.add( localGetValue( hit.ioit, hit.ioit->second.si.id ), it.size );
else
try
{
try
{
hit.add( localGetValue( hit.ioit, hit.id ), it.size );
continue;
}
catch(...){}
hit.add( localGetValue( hit.ioit, hit.id ), it.size );
}
catch( IOController_i::Undefined& ex )
{
hit.add( numeric_limits<long>::max(), it.size );
}
catch(...){}
}
}
}
......@@ -747,8 +742,3 @@ std::ostream& operator<<( std::ostream& os, const SharedMemory::HistoryInfo& h )
return os;
}
// ------------------------------------------------------------------------------------------
bool SharedMemory::isActivated()
{
return activated;
}
// ------------------------------------------------------------------------------------------
......@@ -430,7 +430,6 @@ class SharedMemory:
void buildHistoryList( xmlNode* cnode );
void checkHistoryFilter( UniXML_iterator& it );
bool isActivated();
IOStateList::iterator itPulsar;
UniSetTypes::ObjectId sidPulsar;
......
......@@ -64,7 +64,7 @@ smReadyTimeout(15000)
for( ; it.getCurrent(); it.goNext() )
{
UniSetTypes::ObjectId id;
string n(it.getProp("id"));
if( !n.empty() )
id = it.getIntProp("id");
......@@ -73,7 +73,7 @@ smReadyTimeout(15000)
id = conf->getControllerID( it.getProp("name") );
n = it.getProp("name");
}
if( id == DefaultObjectId )
throw SystemError("(UniExchange): Uknown ID for " + n );
......@@ -90,7 +90,7 @@ smReadyTimeout(15000)
if( id == DefaultObjectId )
throw SystemError("(UniExchange): Uknown ID for node=" + n1 );
NetNodeInfo ni;
ni.oref = CORBA::Object::_nil();
ni.id = id;
......@@ -98,10 +98,10 @@ smReadyTimeout(15000)
ni.sidConnection = conf->getSensorID(it.getProp("sid_connection"));
dinfo << myname << ": add point " << n << ":" << n1 << endl;
nlst.push_back(ni);
nlst.push_back( std::move(ni) );
}
}
if( shm->isLocalwork() )
{
readConfiguration();
......@@ -204,9 +204,9 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI
// init new map...
smap.resize(map->length());
}
int size = map->length();
for( unsigned int i=0; i<size; i++ )
size_t size = map->length();
for( size_t i=0; i<size; i++ )
{
SInfo* s = &(smap[i]);
IOController_i::ShortMap* m = &(map[i]);
......@@ -218,7 +218,7 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI
}
s->val = m->value;
try
{
/*
......@@ -408,7 +408,7 @@ bool UniExchange::initItem( UniXML_iterator& it )
i.val = 0;
mymap[maxIndex++] = i;
mymap[maxIndex++] = std::move(i);
if( maxIndex >= mymap.size() )
mymap.resize(maxIndex+10);
......
......@@ -61,9 +61,16 @@ class UniExchange:
std::string s_field;
std::string s_fvalue;
SMInterface* shm;
struct SInfo
{
// т.к. содержится rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
SInfo( const SInfo& r ) = delete;
SInfo& operator=(const SInfo& r) = delete;
SInfo( SInfo&& r ) = default;
SInfo& operator=(SInfo&& r) = default;
SInfo():
val(0),
id(UniSetTypes::DefaultObjectId),
......@@ -76,13 +83,20 @@ class UniExchange:
UniversalIO::IOType type;
UniSetTypes::uniset_rwmutex val_lock;
};
typedef std::vector<SInfo> SList;
struct NetNodeInfo
{
// т.к. содержится SList в котором rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
NetNodeInfo( const NetNodeInfo& r ) = delete;
NetNodeInfo& operator=(const NetNodeInfo& r) = delete;
NetNodeInfo( NetNodeInfo&& r ) = default;
NetNodeInfo& operator=(NetNodeInfo&& r) = default;
NetNodeInfo();
CORBA::Object_var oref;
IOController_i_var shm;
UniSetTypes::ObjectId id;
......
......@@ -18,6 +18,13 @@ static const int NoSafety = -1;
/*! Информация о входе/выходе */
struct IOBase
{
// т.к. IOBase содержит rwmutex с запрещённым конструктором копирования
// приходится здесь тоже объявлять разрешенными только операции "перемещения"
IOBase( const IOBase& r ) = delete;
IOBase& operator=(const IOBase& r) = delete;
IOBase( IOBase&& r ) = default;
IOBase& operator=(IOBase&& r) = default;
IOBase():
cdiagram(0),
breaklim(0),
......
......@@ -124,6 +124,11 @@ class IOController:
struct USensorInfo:
public IOController_i::SensorIOInfo
{
USensorInfo( const USensorInfo& ) = delete;
const USensorInfo& operator=(const USensorInfo& ) = delete;
USensorInfo( USensorInfo&& ) = default;
USensorInfo& operator=(USensorInfo&& ) = default;
USensorInfo():any(0),d_value(0),d_off_value(0)
{
d_si.id = UniSetTypes::DefaultObjectId;
......@@ -207,7 +212,7 @@ class IOController:
/*! регистрация датчика
force=true - не проверять на дублирование (оптимизация)
*/
void ioRegistration( const USensorInfo&, bool force=false );
void ioRegistration( USensorInfo&&, bool force=false );
/*! разрегистрация датчика */
void ioUnRegistration( const UniSetTypes::ObjectId sid );
......
......@@ -171,15 +171,25 @@ class IONotifyController:
UniSetObject_i_var ref;
int attempt;
ConsumerInfoExt( const ConsumerInfoExt& ) = default;
ConsumerInfoExt& operator=( const ConsumerInfoExt& ) = default;
ConsumerInfoExt( ConsumerInfoExt&& ) = default;
ConsumerInfoExt& operator=(ConsumerInfoExt&& ) = default;
};
typedef std::list<ConsumerInfoExt> ConsumerList;
struct ConsumerListInfo
{
ConsumerListInfo():mut("ConsumerInfoMutex"){}
ConsumerList clst;
UniSetTypes::uniset_rwmutex mut;
ConsumerListInfo():mut("ConsumerInfoMutex"){}
ConsumerList clst;
UniSetTypes::uniset_rwmutex mut;
ConsumerListInfo( const ConsumerListInfo& ) = delete;
ConsumerListInfo& operator=( const ConsumerListInfo& ) = delete;
ConsumerListInfo( ConsumerListInfo&& ) = default;
ConsumerListInfo& operator=(ConsumerListInfo&& ) = default;
};
/*! словарь: датчик -> список потребителей */
......@@ -232,6 +242,11 @@ class IONotifyController:
r.state = state;
return r;
}
ThresholdInfoExt( const ThresholdInfoExt& ) = delete;
ThresholdInfoExt& operator=( const ThresholdInfoExt& ) = delete;
ThresholdInfoExt( ThresholdInfoExt&& ) = default;
ThresholdInfoExt& operator=(ThresholdInfoExt&& ) = default;
};
/*! список порогов (информация по каждому порогу) */
......@@ -240,9 +255,9 @@ class IONotifyController:
struct ThresholdsListInfo
{
ThresholdsListInfo(){}
ThresholdsListInfo( IOController_i::SensorInfo& si, ThresholdExtList& list,
ThresholdsListInfo( IOController_i::SensorInfo& si, ThresholdExtList&& list,
UniversalIO::IOType t=UniversalIO::AI ):
si(si),type(t),list(list){}
si(si),type(t),list( std::move(list) ){}
UniSetTypes::uniset_rwmutex mut;
IOController_i::SensorInfo si; /*!< аналоговый датчик */
......@@ -303,7 +318,7 @@ class IONotifyController:
const UniSetTypes::ConsumerInfo& ci, UniversalIO::UIOCommand cmd);
/*! добавить новый порог для датчика */
bool addThreshold(ThresholdExtList& lst, ThresholdInfoExt& ti, const UniSetTypes::ConsumerInfo& cons);
bool addThreshold(ThresholdExtList& lst, ThresholdInfoExt&& ti, const UniSetTypes::ConsumerInfo& ci);
/*! удалить порог для датчика */
bool removeThreshold(ThresholdExtList& lst, ThresholdInfoExt& ti, const UniSetTypes::ConsumerInfo& ci);
......@@ -312,7 +327,7 @@ class IONotifyController:
/*! замок для блокирования совместного доступа к cписку потребителей датчиков */
UniSetTypes::uniset_rwmutex askIOMutex;
/*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */
/*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */
UniSetTypes::uniset_rwmutex trshMutex;
int maxAttemtps; /*! timeout for consumer */
......
......@@ -72,8 +72,8 @@ namespace UniSetTypes
{
TransportMessage tmsg;
assert(sizeof(UniSetTypes::RawDataOfTransportMessage)>=sizeof(msg));
memcpy(&tmsg.data,&msg,sizeof(msg));
return tmsg;
std::memcpy(&tmsg.data,&msg,sizeof(msg));
return std::move(tmsg);
}
};
......@@ -91,7 +91,7 @@ namespace UniSetTypes
{
if( priority != msg.priority )
return priority < msg.priority;
if( tm.tv_sec != msg.tm.tv_sec )
return tm.tv_sec >= msg.tm.tv_sec;
......@@ -121,7 +121,7 @@ namespace UniSetTypes
UniversalIO::IOType sensor_type;
IOController_i::CalibrateInfo ci;
// для пороговых датчиков
bool threshold; /*!< TRUE - сработал порог, FALSE - порог отключился */
UniSetTypes::ThresholdId tid;
......
......@@ -50,8 +50,8 @@ namespace UniSetTypes
private:
friend class uniset_mutex_lock;
uniset_mutex(const uniset_mutex& r)=delete;
const uniset_mutex &operator=(const uniset_mutex& r) = delete;
uniset_mutex(const uniset_mutex& r) = delete;
uniset_mutex &operator=(const uniset_mutex& r) = delete;
std::string nm;
std::timed_mutex m_lock;
};
......@@ -99,8 +99,11 @@ namespace UniSetTypes
bool tryrlock();
bool trywrlock();
uniset_rwmutex( const uniset_rwmutex& r );
const uniset_rwmutex &operator=(const uniset_rwmutex& r);
uniset_rwmutex( const uniset_rwmutex& r ) = delete;
uniset_rwmutex& operator=(const uniset_rwmutex& r)=delete;
uniset_rwmutex( uniset_rwmutex&& r ) = default;
uniset_rwmutex& operator=(uniset_rwmutex&& r)=default;
inline std::string name(){ return nm; }
inline void setName( const std::string& name ){ nm = name; }
......@@ -109,7 +112,6 @@ namespace UniSetTypes
std::string nm;
friend class uniset_rwmutex_lock;
ost::ThreadLock m;
static std::atomic<int> num;
};
std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m );
......
......@@ -48,6 +48,11 @@ class NCRestorer
struct SInfo:
public IOController::USensorInfo
{
SInfo( const SInfo& ) = delete;
const SInfo& operator=(const SInfo& ) = delete;
SInfo( SInfo&& ) = default;
SInfo& operator=(SInfo&& ) = default;
SInfo( IOController_i::SensorInfo& si, UniversalIO::IOType& t,
UniSetTypes::Message::Message::Priority& p, long& def )
{
......@@ -74,14 +79,14 @@ class NCRestorer
protected:
// добавление списка заказчиков
static void addlist( IONotifyController* ic, SInfo& inf, IONotifyController::ConsumerListInfo& lst, bool force=false );
static void addlist( IONotifyController* ic, SInfo&& inf, IONotifyController::ConsumerListInfo&& lst, bool force=false );
// добавление списка порогов и заказчиков
static void addthresholdlist( IONotifyController* ic, SInfo& inf, IONotifyController::ThresholdExtList& lst, bool force=false );
static void addthresholdlist( IONotifyController* ic, SInfo&& inf, IONotifyController::ThresholdExtList&& lst, bool force=false );
static inline void ioRegistration( IONotifyController* ic, IOController::USensorInfo& inf, bool force=false )
static inline void ioRegistration( IONotifyController* ic, IOController::USensorInfo&& inf, bool force=false )
{
ic->ioRegistration(inf,force);
ic->ioRegistration( std::move(inf),force);
}
static inline IOController::IOStateList::iterator ioFind( IONotifyController* ic, UniSetTypes::KeyType k )
......@@ -121,7 +126,7 @@ class NCRestorer_XML:
\param fname - файл. (формата uniset-project)
\param sensor_filterField - читать из списка только те узлы, у которых filterField="filterValue"
\param sensor_filterValue - значение для фильтрования списка
*/
*/
NCRestorer_XML( const std::string& fname, const std::string& sensor_filterField, const std::string& sensor_filterValue="" );
virtual ~NCRestorer_XML();
......@@ -157,7 +162,7 @@ class NCRestorer_XML:
protected:
bool check_thresholds_item( UniXML_iterator& it );
void read_consumers(const UniXML& xml, xmlNode* node, NCRestorer_XML::SInfo& inf, IONotifyController* ic );
void read_consumers(const UniXML& xml, xmlNode* node, NCRestorer_XML::SInfo&& inf, IONotifyController* ic );
void read_list(const UniXML& xml, xmlNode* node, IONotifyController* ic);
void read_thresholds(const UniXML& xml, xmlNode* node, IONotifyController* ic);
void init( const std::string& fname );
......
......@@ -1907,7 +1907,6 @@ bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const Obje
}
return ready;
}
// -----------------------------------------------------------------------------
UniversalIO::IOType UInterface::getConfIOType( const UniSetTypes::ObjectId id ) const
......
......@@ -44,7 +44,7 @@ string IORFile::getIOR( const ObjectId id ) const
string sior;
ior_file >> sior;
return sior;
return std::move(sior);
}
// -----------------------------------------------------------------------------------------
void IORFile::setIOR( const ObjectId id, const string& sior ) const
......@@ -72,6 +72,6 @@ string IORFile::genFName( const ObjectId id ) const
{
ostringstream fname;
fname << conf->getLockDir() << id;
return fname.str();
return std::move( fname.str() );
}
// -----------------------------------------------------------------------------------------
......@@ -142,52 +142,52 @@ namespace ORepHelpers
CosNaming::NamingContext_ptr getRootNamingContext(const CORBA::ORB_ptr orb, const string& nsName, int timeoutSec)
{
CosNaming::NamingContext_var rootContext;
try
{
// cout << "ORepHelpers(getRootNamingContext): nsName->" << nsName << endl;
CORBA::Object_var initServ = orb->resolve_initial_references(nsName.c_str());
ulogrep << "OREPHELP: get rootcontext...(nsName = "<< nsName << ")" <<endl;
try
{
// cout << "ORepHelpers(getRootNamingContext): nsName->" << nsName << endl;
CORBA::Object_var initServ = orb->resolve_initial_references(nsName.c_str());
ulogrep << "OREPHELP: get rootcontext...(nsName = "<< nsName << ")" <<endl;
rootContext = CosNaming::NamingContext::_narrow(initServ);
if (CORBA::is_nil(rootContext))
{
string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу.");
throw ORepFailed(err.c_str());
}
rootContext = CosNaming::NamingContext::_narrow(initServ);
if (CORBA::is_nil(rootContext))
ulogrep << "OREPHELP: init NameService ok"<< endl;
}
catch(CORBA::ORB::InvalidName& ex)
{
string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу.");
throw ORepFailed(err.c_str());
ostringstream err;
err << "ORepHelpers(getRootNamingContext): InvalidName=" << nsName;
uwarn << err.str() << endl;
throw ORepFailed(err.str());
}
catch (CORBA::COMM_FAILURE& ex)
{
ostringstream err;
err << "ORepHelpers(getRootNamingContext): Не смог получить ссылку на контекст ->" << nsName;
throw ORepFailed(err.str());
}
catch(omniORB::fatalException& ex)
{
string err("ORepHelpers(getRootNamingContext): Caught Fatal Exception");
throw ORepFailed(err);
}
catch (...)
{
string err("ORepHelpers(getRootNamingContext): Caught a system exception while resolving the naming service.");
throw ORepFailed(err);
}
ulogrep << "OREPHELP: init NameService ok"<< endl;
}
catch(CORBA::ORB::InvalidName& ex)
{
ostringstream err;
err << "ORepHelpers(getRootNamingContext): InvalidName=" << nsName;
uwarn << err.str() << endl;
throw ORepFailed(err.str());
}
catch (CORBA::COMM_FAILURE& ex)
{
ostringstream err;
err << "ORepHelpers(getRootNamingContext): Не смог получить ссылку на контекст ->" << nsName;
throw ORepFailed(err.str());
}
catch(omniORB::fatalException& ex)
{
string err("ORepHelpers(getRootNamingContext): Caught Fatal Exception");
throw ORepFailed(err);
}
catch (...)
{
string err("ORepHelpers(getRootNamingContext): Caught a system exception while resolving the naming service.");
throw ORepFailed(err);
}
ulogrep << "OREPHELP: get root context ok"<< endl;
ulogrep << "OREPHELP: get root context ok"<< endl;
// // Если создан как _ptr
// return rootContext;
// // Если создан как _ptr
// return rootContext;
// Если создан как _var
return rootContext._retn();
// Если создан как _var
return rootContext._retn();
}
// ---------------------------------------------------------------------------------------------------------------
/*!
......@@ -196,7 +196,6 @@ namespace ORepHelpers
*/
const string getShortName( const string& fname, const std::string& brk )
{
string::size_type pos = fname.rfind(brk);
if( pos == string::npos )
return fname;
......@@ -251,7 +250,7 @@ namespace ORepHelpers
}
string err("Имя не должно содержать символы: "+ bad);
return err;
return std::move(err);
}
// ---------------------------------------------------------------------------------------------------------------
}
......@@ -74,6 +74,7 @@ string ObjectIndex_Array::getTextName( const ObjectId id )
{
if( id!=UniSetTypes::DefaultObjectId && id>=0 && id<maxId )
return objectInfo[id].textName;
return "";
// throw OutOfRange("ObjectIndex_Array::getTextName OutOfRange");
}
......@@ -107,14 +108,6 @@ const ObjectInfo* ObjectIndex_Array::getObjectInfo( const ObjectId id )
return &(objectInfo[id]);
return NULL;
/*
ObjectInfo ret;
ret.id = DefaultObjectId;
ret.repName = "";
ret.textName = "";
return ret;
*/
}
// -----------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_Array::getObjectInfo( const std::string& name )
......
......@@ -228,7 +228,7 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi
ctx->list(how_many,bl,bi);
if(how_many>bl->length())
if( how_many>bl->length() )
how_many = bl->length();
bool rem = true; // удалять или нет
......@@ -266,7 +266,7 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi
// Удаляем контекст, если он уже пустой
if (rem)
if( rem )
{
// Получаем имя контекста содержащего удаляемый
string in_sec(ORepHelpers::getSectionName(fullName));
......
......@@ -443,7 +443,7 @@ void UniSetObject::setThreadPriority( int p )
thr->setPriority(p);
}
// ------------------------------------------------------------------------------------------
void UniSetObject::push(const TransportMessage& tm)
void UniSetObject::push( const TransportMessage& tm )
{
{ // lock
uniset_rwmutex_wrlock mlk(qmutex);
......
......@@ -31,344 +31,344 @@ using namespace std;
using namespace UniSetTypes;
// -----------------------------------------------------------------------------
float UniSetTypes::fcalibrate( float raw, float rawMin, float rawMax,
float calMin, float calMax, bool limit )
{
if( rawMax == rawMin ) return 0; // деление на 0!!!
float ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin;
if( !limit )
return ret;
// Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) {
if( ret < calMin )
return calMin;
if( ret > calMax )
return calMax;
} else {
if( ret > calMin )
return calMin;
if( ret < calMax )
return calMax;
}
float UniSetTypes::fcalibrate( float raw, float rawMin, float rawMax,
float calMin, float calMax, bool limit )
{
if( rawMax == rawMin ) return 0; // деление на 0!!!
float ret = (raw - rawMin) * (calMax - calMin) / ( rawMax - rawMin ) + calMin;
if( !limit )
return ret;
}
// -------------------------------------------------------------------------
// Пересчитываем из исходных пределов в заданные
long UniSetTypes::lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit )
{
if( rawMax == rawMin ) return 0; // деление на 0!!!
long ret = lroundf( (float)(raw - rawMin) * (float)(calMax - calMin) /
(float)( rawMax - rawMin ) + calMin );
if( !limit )
return ret;
return setinregion(ret, calMin, calMax);
// Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) {
if( ret < calMin )
return calMin;
if( ret > calMax )
return calMax;
} else {
if( ret > calMin )
return calMin;
if( ret < calMax )
return calMax;
}
// -------------------------------------------------------------------------
// Приводим указанное значение в заданные пределы
long UniSetTypes::setinregion(long ret, long calMin, long calMax)
{
// Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) {
if( ret < calMin )
return calMin;
if( ret > calMax )
return calMax;
} else {
if( ret > calMin )
return calMin;
if( ret < calMax )
return calMax;
}
return ret;
}
// -------------------------------------------------------------------------
// Пересчитываем из исходных пределов в заданные
long UniSetTypes::lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit )
{
if( rawMax == rawMin ) return 0; // деление на 0!!!
long ret = lroundf( (float)(raw - rawMin) * (float)(calMax - calMin) /
(float)( rawMax - rawMin ) + calMin );
if( !limit )
return ret;
return setinregion(ret, calMin, calMax);
}
// -------------------------------------------------------------------------
// Приводим указанное значение в заданные пределы
long UniSetTypes::setinregion(long ret, long calMin, long calMax)
{
// Переворачиваем calMin и calMax для проверки, если calMin > calMax
if (calMin < calMax) {
if( ret < calMin )
return calMin;
if( ret > calMax )
return calMax;
} else {
if( ret > calMin )
return calMin;
if( ret < calMax )
return calMax;
}
// Выводим указанное значение из заданных пределов (на границы)
long UniSetTypes::setoutregion(long ret, long calMin, long calMax)
return ret;
}
// Выводим указанное значение из заданных пределов (на границы)
long UniSetTypes::setoutregion(long ret, long calMin, long calMax)
{
if ((ret > calMin) && (ret < calMax))
{
if ((ret > calMin) && (ret < calMax))
{
if ((ret*10) >= ((calMax + calMin)*5))
ret = calMax;
else
ret = calMin;
}
return ret;
if ((ret*10) >= ((calMax + calMin)*5))
ret = calMax;
else
ret = calMin;
}
return ret;
}
// -------------------------------------------------------------------------
UniSetTypes::IDList::IDList():
node(UniSetTypes::conf->getLocalNode())
{
// -------------------------------------------------------------------------
UniSetTypes::IDList::IDList():
node(UniSetTypes::conf->getLocalNode())
{
}
}
UniSetTypes::IDList::~IDList()
UniSetTypes::IDList::~IDList()
{
}
void UniSetTypes::IDList::add( ObjectId id )
{
for( auto it=lst.begin(); it!=lst.end(); ++it )
{
if( (*it) == id )
return;
}
void UniSetTypes::IDList::add( ObjectId id )
lst.push_back(id);
}
void UniSetTypes::IDList::del( ObjectId id )
{
for( auto it=lst.begin(); it!=lst.end(); ++it )
{
for( auto it=lst.begin(); it!=lst.end(); ++it )
if( (*it) == id )
{
if( (*it) == id )
return;
lst.erase(it);
return;
}
lst.push_back(id);
}
void UniSetTypes::IDList::del( ObjectId id )
}
std::list<UniSetTypes::ObjectId> UniSetTypes::IDList::getList()
{
return lst;
}
UniSetTypes::ObjectId UniSetTypes::IDList::getFirst()
{
if( lst.empty() )
return UniSetTypes::DefaultObjectId;
return (*lst.begin());
}
// за освобождение выделеной памяти
// отвечает вызывающий!
IDSeq* UniSetTypes::IDList::getIDSeq()
{
IDSeq* seq = new IDSeq();
seq->length(lst.size());
int i=0;
for( auto it=lst.begin(); it!=lst.end(); ++it,i++ )
(*seq)[i] = (*it);
return seq;
}
// -------------------------------------------------------------------------
bool UniSetTypes::file_exist( const std::string& filename )
{
std::ifstream file;
#ifdef HAVE_IOS_NOCREATE
file.open( filename.c_str(), std::ios::in | std::ios::nocreate );
#else
file.open( filename.c_str(), std::ios::in );
#endif
bool result = false;
if( file )
result = true;
file.close();
return result;
}
// -------------------------------------------------------------------------
UniSetTypes::IDList UniSetTypes::explode( const string& str, char sep )
{
UniSetTypes::IDList l;
string::size_type prev = 0;
string::size_type pos = 0;
do
{
for( auto it=lst.begin(); it!=lst.end(); ++it )
pos = str.find(sep,prev);
string s(str.substr(prev,pos-prev));
if( !s.empty() )
{
if( (*it) == id )
{
lst.erase(it);
return;
}
l.add( uni_atoi(s) );
prev=pos+1;
}
}
std::list<UniSetTypes::ObjectId> UniSetTypes::IDList::getList()
while( pos!=string::npos );
return l;
}
// -------------------------------------------------------------------------
std::list<std::string> UniSetTypes::explode_str( const string& str, char sep )
{
std::list<std::string> l;
string::size_type prev = 0;
string::size_type pos = 0;
do
{
return lst;
pos = str.find(sep,prev);
string s(str.substr(prev,pos-prev));
if( !s.empty() )
{
l.push_back(s);
prev=pos+1;
}
}
UniSetTypes::ObjectId UniSetTypes::IDList::getFirst()
while( pos!=string::npos );
return l;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s )
{
for( auto c: s )
{
if( lst.empty() )
return UniSetTypes::DefaultObjectId;
return (*lst.begin());
if( !isdigit(c) )
return false;
}
// за освобождение выделеной памяти
// отвечает вызывающий!
IDSeq* UniSetTypes::IDList::getIDSeq()
{
IDSeq* seq = new IDSeq();
seq->length(lst.size());
int i=0;
for( auto it=lst.begin(); it!=lst.end(); ++it,i++ )
(*seq)[i] = (*it);
return true;
//return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false;
}
// --------------------------------------------------------------------------------------
std::list<UniSetTypes::ParamSInfo> UniSetTypes::getSInfoList( const string& str, Configuration* conf )
{
std::list<UniSetTypes::ParamSInfo> res;
return seq;
}
// -------------------------------------------------------------------------
bool UniSetTypes::file_exist( const std::string& filename )
{
std::ifstream file;
#ifdef HAVE_IOS_NOCREATE
file.open( filename.c_str(), std::ios::in | std::ios::nocreate );
#else
file.open( filename.c_str(), std::ios::in );
#endif
bool result = false;
if( file )
result = true;
file.close();
return result;
}
// -------------------------------------------------------------------------
UniSetTypes::IDList UniSetTypes::explode( const string& str, char sep )
auto lst = UniSetTypes::explode_str(str,',');
for( auto it: lst )
{
UniSetTypes::IDList l;
UniSetTypes::ParamSInfo item;
string::size_type prev = 0;
string::size_type pos = 0;
do
auto p = UniSetTypes::explode_str(it,'=');
std::string s = "";
if( p.size() == 1 )
{
pos = str.find(sep,prev);
string s(str.substr(prev,pos-prev));
if( !s.empty() )
{
l.add( uni_atoi(s) );
prev=pos+1;
}
s = *(p.begin());
item.val = 0;
}
while( pos!=string::npos );
return l;
}
// -------------------------------------------------------------------------
std::list<std::string> UniSetTypes::explode_str( const string& str, char sep )
{
std::list<std::string> l;
string::size_type prev = 0;
string::size_type pos = 0;
do
else if( p.size() == 2 )
{
pos = str.find(sep,prev);
string s(str.substr(prev,pos-prev));
if( !s.empty() )
{
l.push_back(s);
prev=pos+1;
}
s = *(p.begin());
item.val = uni_atoi(*(++p.begin()));
}
while( pos!=string::npos );
return l;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s )
{
for( auto c: s )
else
{
if( !isdigit(c) )
return false;
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue;
}
return true;
//return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false;
}
// --------------------------------------------------------------------------------------
std::list<UniSetTypes::ParamSInfo> UniSetTypes::getSInfoList( const string& str, Configuration* conf )
{
std::list<UniSetTypes::ParamSInfo> res;
auto lst = UniSetTypes::explode_str(str,',');
for( auto it: lst )
item.fname = s;
auto t = UniSetTypes::explode_str(s,'@');
if( t.size() == 1 )
{
UniSetTypes::ParamSInfo item;
auto p = UniSetTypes::explode_str(it,'=');
std::string s = "";
if( p.size() == 1 )
{
s = *(p.begin());
item.val = 0;
}
else if( p.size() == 2 )
{
s = *(p.begin());
item.val = uni_atoi(*(++p.begin()));
}
std::string s_id = *(t.begin());
if( is_digit(s_id) )
item.si.id = uni_atoi(s_id);
else
{
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
continue;
}
item.fname = s;
auto t = UniSetTypes::explode_str(s,'@');
if( t.size() == 1 )
{
std::string s_id = *(t.begin());
if( is_digit(s_id) )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
item.si.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
std::string s_id = *(t.begin());
std::string s_node = *(++t.begin());
if( is_digit(s_id) )
item.si.id = uni_atoi(s_id);
else
item.si.id = conf->getSensorID(s_id);
if( is_digit(s_node.c_str()) )
item.si.node = uni_atoi(s_node);
else
item.si.node= conf->getNodeID(s_node);
}
item.si.id = conf->getSensorID(s_id);
item.si.node = DefaultObjectId;
}
else if( t.size() == 2 )
{
std::string s_id = *(t.begin());
std::string s_node = *(++t.begin());
if( is_digit(s_id) )
item.si.id = uni_atoi(s_id);
else
{
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue;
}
item.si.id = conf->getSensorID(s_id);
res.push_back(item);
if( is_digit(s_node.c_str()) )
item.si.node = uni_atoi(s_node);
else
item.si.node= conf->getNodeID(s_node);
}
else
{
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue;
}
return res;
res.push_back(item);
}
// --------------------------------------------------------------------------------------
UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype )
{
if ( stype == "DI" || stype == "di" )
return UniversalIO::DI;
if( stype == "AI" || stype == "ai" )
return UniversalIO::AI;
if ( stype == "DO" || stype == "do" )
return UniversalIO::DO;
if ( stype == "AO" || stype == "ao" )
return UniversalIO::AO;
return UniversalIO::UnknownIOType;
}
// ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOType t )
{
if( t == UniversalIO::AI )
return os << "AI";
if( t == UniversalIO::DI )
return os << "DI";
if( t == UniversalIO::AO )
return os << "AO";
if( t == UniversalIO::DO )
return os << "DO";
return os << "UnknownIOType";
}
// ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const IOController_i::CalibrateInfo c )
{
return os << " rmin=" << c.minRaw << " rmax=" << c.maxRaw
<< " cmin=" << c.minCal << " cmax=" << c.maxCal
<< " precision=" << c.precision;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::check_filter( UniXML_iterator& it, const std::string& f_prop, const std::string& f_val )
{
if( f_prop.empty() )
return true;
// просто проверка на не пустой field
if( f_val.empty() && it.getProp(f_prop).empty() )
return false;
// просто проверка что field = value
if( !f_val.empty() && it.getProp(f_prop)!=f_val )
return false;
return res;
}
// --------------------------------------------------------------------------------------
UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype )
{
if ( stype == "DI" || stype == "di" )
return UniversalIO::DI;
if( stype == "AI" || stype == "ai" )
return UniversalIO::AI;
if ( stype == "DO" || stype == "do" )
return UniversalIO::DO;
if ( stype == "AO" || stype == "ao" )
return UniversalIO::AO;
return UniversalIO::UnknownIOType;
}
// ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOType t )
{
if( t == UniversalIO::AI )
return os << "AI";
if( t == UniversalIO::DI )
return os << "DI";
if( t == UniversalIO::AO )
return os << "AO";
if( t == UniversalIO::DO )
return os << "DO";
return os << "UnknownIOType";
}
// ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const IOController_i::CalibrateInfo c )
{
return os << " rmin=" << c.minRaw << " rmax=" << c.maxRaw
<< " cmin=" << c.minCal << " cmax=" << c.maxCal
<< " precision=" << c.precision;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::check_filter( UniXML_iterator& it, const std::string& f_prop, const std::string& f_val )
{
if( f_prop.empty() )
return true;
}
// ------------------------------------------------------------------------------------------
string UniSetTypes::timeToString(time_t tm, const std::string& brk )
{
struct tm *tms = localtime(&tm);
ostringstream time;
time << std::setw(2) << std::setfill('0') << tms->tm_hour << brk;
time << std::setw(2) << std::setfill('0') << tms->tm_min << brk;
time << std::setw(2) << std::setfill('0') << tms->tm_sec;
return time.str();
}
string UniSetTypes::dateToString(time_t tm, const std::string& brk )
{
struct tm *tms = localtime(&tm);
ostringstream date;
date << std::setw(4) << std::setfill('0') << tms->tm_year+1900 << brk;
date << std::setw(2) << std::setfill('0') << tms->tm_mon+1 << brk;
date << std::setw(2) << std::setfill('0') << tms->tm_mday;
return date.str();
}
//--------------------------------------------------------------------------------------------
// просто проверка на не пустой field
if( f_val.empty() && it.getProp(f_prop).empty() )
return false;
// просто проверка что field = value
if( !f_val.empty() && it.getProp(f_prop)!=f_val )
return false;
return true;
}
// ------------------------------------------------------------------------------------------
string UniSetTypes::timeToString(time_t tm, const std::string& brk )
{
struct tm *tms = localtime(&tm);
ostringstream time;
time << std::setw(2) << std::setfill('0') << tms->tm_hour << brk;
time << std::setw(2) << std::setfill('0') << tms->tm_min << brk;
time << std::setw(2) << std::setfill('0') << tms->tm_sec;
return time.str();
}
string UniSetTypes::dateToString(time_t tm, const std::string& brk )
{
struct tm *tms = localtime(&tm);
ostringstream date;
date << std::setw(4) << std::setfill('0') << tms->tm_year+1900 << brk;
date << std::setw(2) << std::setfill('0') << tms->tm_mon+1 << brk;
date << std::setw(2) << std::setfill('0') << tms->tm_mday;
return date.str();
}
//--------------------------------------------------------------------------------------------
......@@ -134,10 +134,11 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const
if( li!=ioList.end() )
{
uniset_rwmutex_rlock lock(li->second.val_lock);
if( li->second.undefined )
throw IOController_i::Undefined();
uniset_rwmutex_rlock lock(li->second.val_lock);
return li->second.value;
}
......@@ -150,7 +151,7 @@ long IOController::localGetValue( IOController::IOStateList::iterator& li, const
throw IOController_i::NameNotFound(err.str().c_str());
}
// ------------------------------------------------------------------------------------------
void IOController::setUndefinedState(UniSetTypes::ObjectId sid, CORBA::Boolean undefined, UniSetTypes::ObjectId sup_id )
void IOController::setUndefinedState( UniSetTypes::ObjectId sid, CORBA::Boolean undefined, UniSetTypes::ObjectId sup_id )
{
auto li = ioList.end();
localSetUndefinedState( li,undefined, sid );
......@@ -267,7 +268,7 @@ void IOController::localSetValue( IOController::IOStateList::iterator& li,
// поэтому передаём (и затем сохраняем) напрямую(ссылку) value (а не const value)
bool blocked = ( li->second.blocked || li->second.undefined );
if( checkIOFilters(&li->second,value,sup_id) || blocked )
if( checkIOFilters(li->second,value,sup_id) || blocked )
{
uinfo << myname << ": save sensor value (" << sid << ")"
<< " name: " << conf->oind->getNameById(sid)
......@@ -331,7 +332,7 @@ IOType IOController::getIOType( UniSetTypes::ObjectId sid )
throw IOController_i::NameNotFound(err.str().c_str());
}
// ---------------------------------------------------------------------------
void IOController::ioRegistration( const USensorInfo& ainf, bool force )
void IOController::ioRegistration( USensorInfo&& ainf, bool force )
{
// проверка задан ли контроллеру идентификатор
if( getId() == DefaultObjectId )
......@@ -356,7 +357,7 @@ void IOController::ioRegistration( const USensorInfo& ainf, bool force )
}
}
IOStateList::mapped_type ai(ainf);
IOStateList::mapped_type ai( std::move(ainf) );
// запоминаем начальное время
struct timeval tm;
struct timezone tz;
......@@ -368,7 +369,7 @@ void IOController::ioRegistration( const USensorInfo& ainf, bool force )
ai.value = ai.default_val;
// более оптимальный способ(при условии вставки первый раз)
ioList.insert(IOStateList::value_type(ainf.si.id,ai));
ioList.insert( IOStateList::value_type(ainf.si.id, std::move(ai) ));
}
try
......@@ -420,7 +421,7 @@ void IOController::logging( UniSetTypes::SensorMessage& sm )
sm.consumer = dbID;
TransportMessage tm(sm.transport_msg());
ui.send(sm.consumer, tm);
ui.send( sm.consumer, std::move(tm) );
isPingDBServer = true;
}
catch(...)
......@@ -676,7 +677,7 @@ IOController_i::SensorInfoSeq* IOController::getSensorSeq( const IDSeq& lst )
// -----------------------------------------------------------------------------
IDSeq* IOController::setOutputSeq(const IOController_i::OutSeq& lst, ObjectId sup_id )
{
UniSetTypes::IDList badlist; // писок не найденных идентификаторов
UniSetTypes::IDList badlist; // список не найденных идентификаторов
int size = lst.length();
......
......@@ -77,24 +77,8 @@ IONotifyController::~IONotifyController()
}
// ------------------------------------------------------------------------------------------
// функция-объект для поиска
// !!!! для ассоциативных контейнеров должна возвращать false
// в случае равенства!!!!!!!!!!! (проверка эквивалетности. а не равенства)
/*
struct FindCons_eq: public unary_function<UniSetTypes::ConsumerInfo, bool>
{
FindCons_eq(const UniSetTypes::ConsumerInfo& ci):ci(ci){}
inline bool operator()(const UniSetTypes::ConsumerInfo& c) const
{
return !( ci.id==c.id && ci.node==c.node );
}
UniSetTypes::ConsumerInfo ci;
}
*/
// ------------------------------------------------------------------------------------------
/*!
* \param lst - указатель на список в который необходимо внести потребителя
* \param lst - список в который необходимо внести потребителя
* \param name - имя вносимого потребителя
* \note Добавление произойдет только если такого потребителя не существует в списке
*/
......@@ -117,7 +101,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
}
catch(...){}
lst.clst.push_front(cinf);
lst.clst.push_front( std::move(cinf) );
return true;
}
// ------------------------------------------------------------------------------------------
......@@ -155,7 +139,11 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
// если такого аналогового датчика нет, здесь сработает исключение...
auto li = myioEnd();
localGetValue(li,sid);
try
{
localGetValue(li,sid);
}
catch( IOController_i::Undefined& ex ){}
{ // lock
uniset_rwmutex_wrlock lock(askIOMutex);
......@@ -184,10 +172,9 @@ void IONotifyController::askSensor(const UniSetTypes::ObjectId sid,
smsg.sm_tv_usec = li->second.tv_usec;
}
TransportMessage tm(smsg.transport_msg());
try
{
ui.send(ci.id, tm, ci.node);
ui.send(ci.id, std::move(smsg.transport_msg()), ci.node);
}
catch( Exception& ex )
{
......@@ -225,7 +212,7 @@ void IONotifyController::ask( AskMap& askLst, const UniSetTypes::ObjectId sid,
ConsumerListInfo lst; // создаем новый список
addConsumer(lst,cons);
// более оптимальный способ(при условии вставки первый раз)
askLst.insert(AskMap::value_type(sid,lst));
askLst.insert(AskMap::value_type(sid,std::move(lst)));
try
{
......@@ -412,7 +399,7 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage
// а формируем TransportMessage самостоятельно..
assert(sizeof(UniSetTypes::RawDataOfTransportMessage)>=sizeof(sm));
memcpy(&tmsg.data,&sm,sizeof(sm));
std::memcpy(&tmsg.data,&sm,sizeof(sm));
li->ref->push( tmsg );
li->attempt = maxAttemtps; // reinit attempts
......@@ -436,7 +423,7 @@ void IONotifyController::send( ConsumerListInfo& lst, UniSetTypes::SensorMessage
<< " catch..." << endl;
}
if( maxAttemtps>0 && ( (li->attempt)-- <= 0 ) )
if( maxAttemtps>0 && --(li->attempt) <= 0 )
{
li = lst.clst.erase(li);
if( li == lst.clst.end() ) --li;
......@@ -483,7 +470,7 @@ void IONotifyController::initItem( IOStateList::iterator& li, IOController* ic )
}
// ------------------------------------------------------------------------------------------
void IONotifyController::dumpOrdersList( const UniSetTypes::ObjectId sid,
const IONotifyController::ConsumerListInfo& lst)
const IONotifyController::ConsumerListInfo& lst )
{
if( restorer == NULL )
return;
......@@ -502,7 +489,7 @@ void IONotifyController::dumpOrdersList( const UniSetTypes::ObjectId sid,
}
// --------------------------------------------------------------------------------------------------------------
void IONotifyController::dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst)
void IONotifyController::dumpThresholdList( const UniSetTypes::ObjectId sid, const IONotifyController::ThresholdExtList& lst )
{
if( restorer == NULL )
return;
......@@ -531,7 +518,13 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
// если такого дискретного датчика нет сдесь сработает исключение...
auto li = myioEnd();
CORBA::Long val = localGetValue(li,sid);
long val = 0;
try
{
val = localGetValue(li,sid);
}
catch( IOController_i::Undefined& ex ){}
{ // lock
uniset_rwmutex_wrlock lock(trshMutex);
......@@ -547,20 +540,21 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
case UniversalIO::UIONotify: // заказ
case UniversalIO::UIONotifyChange:
{
if( it==askTMap.end() )
if( it==askTMap.end() )
{
ThresholdExtList lst; // создаем новый список
ThresholdsListInfo tli;
tli.si.id = sid;
tli.si.node = conf->getLocalNode();
tli.list = lst;
tli.list = std::move(lst);
tli.type = li->second.type;
tli.ait = myioEnd();
addThreshold(lst,ti,ci);
askTMap.insert(AskThresholdMap::value_type(sid,tli));
// после этого вызова ti использовать нельзя
addThreshold(tli.list,std::move(ti),ci);
try
{
dumpThresholdList(sid,lst);
dumpThresholdList(sid,tli.list);
}
catch(Exception& ex)
{
......@@ -570,10 +564,13 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
{
uwarn << myname << " не смогли сделать dump" << endl;
}
// т.к. делаем move... то надо гарантировать, что дальше уже tli не используется..
askTMap.insert(AskThresholdMap::value_type(sid,std::move(tli)));
}
else
{
if( addThreshold(it->second.list,ti,ci) )
if( addThreshold(it->second.list,std::move(ti),ci) )
{
try
{
......@@ -605,8 +602,6 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
sm.priority = (Message::Priority)li->second.priority;
sm.consumer = ci.id;
sm.tid = tid;
sm.sm_tv_sec = ti.tv_sec;
sm.sm_tv_usec = ti.tv_usec;
sm.ci = li->second.ci;
// Проверка нижнего предела
......@@ -616,7 +611,7 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
CORBA::Object_var op = ui.resolve(ci.id, ci.node);
UniSetObject_i_var ref = UniSetObject_i::_narrow(op);
if(!CORBA::is_nil(ref))
ref->push(sm.transport_msg());
ref->push( std::move(sm.transport_msg()) );
}
// Проверка верхнего предела
else if( val >= hiLimit )
......@@ -625,10 +620,10 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
CORBA::Object_var op = ui.resolve(ci.id, ci.node);
UniSetObject_i_var ref = UniSetObject_i::_narrow(op);
if(!CORBA::is_nil(ref))
ref->push(sm.transport_msg());
ref->push( std::move(sm.transport_msg()) );
}
}
catch(Exception& ex)
catch( Exception& ex )
{
uwarn << myname << "(askThreshod): " << ex << endl;
}
......@@ -673,17 +668,15 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
} // unlock
}
// --------------------------------------------------------------------------------------------------------------
bool IONotifyController::addThreshold( ThresholdExtList& lst, ThresholdInfoExt& ti, const UniSetTypes::ConsumerInfo& ci )
bool IONotifyController::addThreshold( ThresholdExtList& lst, ThresholdInfoExt&& ti, const UniSetTypes::ConsumerInfo& ci )
{
for( auto it=lst.begin(); it!=lst.end(); ++it)
{
if( ti==(*it) )
{
if( addConsumer(it->clst, ci) )
{
ti.clst = it->clst;
return true;
}
return false;
}
}
......@@ -699,7 +692,7 @@ bool IONotifyController::addThreshold( ThresholdExtList& lst, ThresholdInfoExt&
ti.tv_sec = tm.tv_sec;
ti.tv_usec = tm.tv_usec;
lst.push_front(ti);
lst.push_back( std::move(ti) );
return true;
}
// --------------------------------------------------------------------------------------------------------------
......@@ -711,10 +704,9 @@ bool IONotifyController::removeThreshold( ThresholdExtList& lst, ThresholdInfoEx
{
if( removeConsumer(it->clst, ci) )
{
/* Не удаляем датчик из списка, чтобы не поломать итераторы
которые могут использоваться в этот момент в других потоках*/
/* Даже если список заказчиков по данному датчику стал пуст.
Не удаляем датчик из списка, чтобы не поломать итераторы
которые могут использоваться в этот момент в других потоках */
// uniset_rwmutex_wrlock lock(it->clst.mut);
// if( it->clst.clst.empty() )
// lst.erase(it);
......@@ -773,8 +765,8 @@ void IONotifyController::checkThreshold( IOStateList::iterator& li,
uniset_rwmutex_rlock l(lst->second.mut);
for( auto it=lst->second.list.begin(); it!=lst->second.list.end(); ++it )
{
// Используем здесь sm.value чтобы не делать ещё раз lock на li->second.value
// Используем здесь значение скопированное в sm.value
// чтобы не делать ещё раз lock на li->second.value
IONotifyController_i::ThresholdState state = it->state;
if( !it->invert )
......@@ -942,9 +934,9 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
{
try
{
(*res)[i].si = it->second.si;
(*res)[i].value = IOController::localGetValue(it->second.ait,it->second.si.id);
(*res)[i].type = it->second.type;
(*res)[i].si = it->second.si;
(*res)[i].value = IOController::localGetValue(it->second.ait,it->second.si.id);
(*res)[i].type = it->second.type;
}
catch(Exception& ex)
{
......@@ -959,12 +951,12 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
unsigned int k=0;
for( auto it2=it->second.list.begin(); it2!=it->second.list.end(); ++it2 )
{
(*res)[i].tlist[k].id = it2->id;
(*res)[i].tlist[k].hilimit = it2->hilimit;
(*res)[i].tlist[k].lowlimit = it2->lowlimit;
(*res)[i].tlist[k].state = it2->state;
(*res)[i].tlist[k].tv_sec = it2->tv_sec;
(*res)[i].tlist[k].tv_usec = it2->tv_usec;
(*res)[i].tlist[k].id = it2->id;
(*res)[i].tlist[k].hilimit = it2->hilimit;
(*res)[i].tlist[k].lowlimit = it2->lowlimit;
(*res)[i].tlist[k].state = it2->state;
(*res)[i].tlist[k].tv_sec = it2->tv_sec;
(*res)[i].tlist[k].tv_usec = it2->tv_usec;
k++;
}
i++;
......
......@@ -40,7 +40,7 @@ NCRestorer::~NCRestorer()
{
}
// ------------------------------------------------------------------------------------------
void NCRestorer::addlist( IONotifyController* ic, SInfo& inf, IONotifyController::ConsumerListInfo& lst, bool force )
void NCRestorer::addlist( IONotifyController* ic, SInfo&& inf, IONotifyController::ConsumerListInfo&& lst, bool force )
{
// Проверка зарегистрирован-ли данный датчик
// если такого дискретного датчика нет, то здесь сработает исключение...
......@@ -59,7 +59,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo& inf, IONotifyController
case UniversalIO::DO:
case UniversalIO::AI:
case UniversalIO::AO:
ic->ioRegistration(inf);
ic->ioRegistration( std::move(inf) );
break;
default:
......@@ -78,7 +78,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo& inf, IONotifyController
case UniversalIO::AI:
case UniversalIO::DO:
case UniversalIO::AO:
ic->askIOList[inf.si.id]=lst;
ic->askIOList[inf.si.id]=std::move(lst);
break;
default:
......@@ -88,7 +88,7 @@ void NCRestorer::addlist( IONotifyController* ic, SInfo& inf, IONotifyController
}
}
// ------------------------------------------------------------------------------------------
void NCRestorer::addthresholdlist( IONotifyController* ic, SInfo& inf, IONotifyController::ThresholdExtList& lst, bool force )
void NCRestorer::addthresholdlist( IONotifyController* ic, SInfo&& inf, IONotifyController::ThresholdExtList&& lst, bool force )
{
// Проверка зарегистрирован-ли данный датчик
// если такого дискретного датчика нет сдесь сработает исключение...
......@@ -107,7 +107,7 @@ void NCRestorer::addthresholdlist( IONotifyController* ic, SInfo& inf, IONotifyC
case UniversalIO::DO:
case UniversalIO::AI:
case UniversalIO::AO:
ic->ioRegistration(inf);
ic->ioRegistration( std::move(inf) );
break;
default:
......@@ -122,7 +122,7 @@ void NCRestorer::addthresholdlist( IONotifyController* ic, SInfo& inf, IONotifyC
ic->askTMap[inf.si.id].si = inf.si;
ic->askTMap[inf.si.id].type = inf.type;
ic->askTMap[inf.si.id].list = lst;
ic->askTMap[inf.si.id].list = std::move(lst);
ic->askTMap[inf.si.id].ait = ic->myioEnd();
}
// ------------------------------------------------------------------------------------------
......
......@@ -143,7 +143,7 @@ void NCRestorer_XML::read_list( const UniXML& xml, xmlNode* node, IONotifyContro
{
try
{
ioRegistration(ic, inf, true);
ioRegistration(ic, std::move(inf), true);
}
catch(Exception& ex)
{
......@@ -157,7 +157,7 @@ void NCRestorer_XML::read_list( const UniXML& xml, xmlNode* node, IONotifyContro
}
rslot(xml,it,node);
read_consumers(xml,it,inf,ic);
read_consumers(xml, it, std::move(inf), ic);
}
}
// ------------------------------------------------------------------------------------------
......@@ -348,7 +348,7 @@ void NCRestorer_XML::read_thresholds(const UniXML& xml, xmlNode* node, IONotifyC
continue;
}
uinfo << ic->getName() << "(read_thresholds): " << it.getProp("name") << endl;
uinfo << ic->getName() << "(read_thresholds): " << it.getProp("name") << endl;
UniXML_iterator tit(it);
if( !tit.goChildren() )
......@@ -390,17 +390,17 @@ void NCRestorer_XML::read_thresholds(const UniXML& xml, xmlNode* node, IONotifyC
}
// порог добавляем в любом случае, даже если список заказчиков пуст...
tlst.push_back(ti);
tlst.push_back( std::move(ti) );
rtslot(xml,tit,it);
}
addthresholdlist(ic,inf,tlst);
addthresholdlist(ic, std::move(inf), std::move(tlst) );
}
}
// ------------------------------------------------------------------------------------------
void NCRestorer_XML::read_consumers( const UniXML& xml, xmlNode* it,
NCRestorer_XML::SInfo& inf, IONotifyController* ic )
NCRestorer_XML::SInfo&& inf, IONotifyController* ic )
{
// в новых ask-файлах список выделен <consumers>...</consumers>,
xmlNode* cnode = find_node(xml,it,"consumers","");
......@@ -411,7 +411,7 @@ void NCRestorer_XML::read_consumers( const UniXML& xml, xmlNode* it,
{
IONotifyController::ConsumerListInfo lst;
if( getConsumerList(xml,cit,lst) )
addlist(ic,inf,lst,true);
addlist(ic,std::move(inf),std::move(lst),true);
}
}
}
......
......@@ -79,7 +79,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
if( li->tmr.checkTime() )
{
// помещаем себе в очередь сообщение
TransportMessage tm = TimerMessage(li->id, li->priority, obj->getId()).transport_msg();
TransportMessage tm( std::move(TimerMessage(li->id, li->priority, obj->getId()).transport_msg()) );
obj->push(tm);
// Проверка на количество заданных тактов
......@@ -151,9 +151,8 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c
}
}
TimerInfo newti(timerid, timeMS, ticks, p);
tlst.push_back(newti);
newti.reset();
// TimerInfo newti(timerid, timeMS, ticks, p);
tlst.push_back( std::move(TimerInfo(timerid, timeMS, ticks, p)) );
} // unlock
uinfo << "(LT_askTimer): поступил заказ на таймер(id="<< timerid << ") " << timeMS << " [мс]\n";
......
......@@ -79,8 +79,8 @@ threshold(false),
tid(UniSetTypes::DefaultThresholdId)
{
type = Message::SensorInfo;
sm_tv_sec = tm.tv_sec;
sm_tv_usec = tm.tv_usec;
sm_tv_sec = tm.tv_sec;
sm_tv_usec = tm.tv_usec;
ci.minRaw = 0;
ci.maxRaw = 0;
......
......@@ -104,7 +104,7 @@ bool uniset_mutex_lock::lock_ok()
// -----------------------------------------------------------------------------
uniset_mutex_lock::~uniset_mutex_lock()
{
if( locked)
if( locked )
{
mutex->unlock();
locked = false;
......@@ -130,36 +130,6 @@ std::ostream& UniSetTypes::operator<<(std::ostream& os, uniset_rwmutex& m )
return os << m.name();
}
std::atomic<int> uniset_rwmutex::num(0);
const uniset_rwmutex &uniset_rwmutex::operator=( const uniset_rwmutex& r )
{
if( this != &r )
{
lock();
MUTEX_DEBUG(cerr << "...copy mutex...(" << r.nm << " --> " << nm << ")" << endl;)
ostringstream s;
s << r.nm << "." << (++num);
nm = s.str();
unlock();
}
return *this;
}
uniset_rwmutex::uniset_rwmutex( const uniset_rwmutex& r )
{
if( this != &r )
{
lock();
MUTEX_DEBUG(cerr << "...copy constr mutex...(" << r.nm << " --> " << nm << ")" << endl;)
ostringstream s;
s << r.nm << "." << (++num);
nm = s.str();
unlock();
}
}
void uniset_rwmutex::lock()
{
MUTEX_DEBUG(cerr << nm << " prepare Locked.." << endl;)
......
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