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