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"/>
......
...@@ -696,7 +696,7 @@ bool IOControl::initIOItem( UniXML_iterator& it ) ...@@ -696,7 +696,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
} }
inf.subdev = it.getIntProp("subdev"); inf.subdev = it.getIntProp("subdev");
if( inf.subdev < 0 ) if( inf.subdev < 0 )
inf.subdev = DefaultSubdev; inf.subdev = DefaultSubdev;
...@@ -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 ) if( !initRegInfo(ri,xmlit,dev) )
{
ri = new MBExchange::RegInfo(*rcopy);
ri->slst.clear();
ri->mbreg = r;
}
else
{ {
ri = new MBExchange::RegInfo(); delete ri;
if( !initRegInfo(ri,xmlit,dev) ) return 0;
{
delete ri;
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;
...@@ -2165,8 +2153,8 @@ bool MBExchange::initItem( UniXML_iterator& it ) ...@@ -2165,8 +2153,8 @@ bool MBExchange::initItem( UniXML_iterator& it )
bool need_init = it.getIntProp(prop_prefix + "preinit"); bool need_init = it.getIntProp(prop_prefix + "preinit");
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;
...@@ -2208,12 +2196,12 @@ bool MBExchange::initItem( UniXML_iterator& it ) ...@@ -2208,12 +2196,12 @@ bool MBExchange::initItem( UniXML_iterator& it )
break; break;
default: default:
ii.mbfunc = ModbusRTU::fnReadOutputRegisters; ii.mbfunc = ModbusRTU::fnReadOutputRegisters;
break; break;
} }
} }
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);
} }
} }
......
...@@ -126,7 +126,7 @@ SharedMemory::~SharedMemory() ...@@ -126,7 +126,7 @@ SharedMemory::~SharedMemory()
delete restorer; delete restorer;
restorer = NULL; restorer = NULL;
} }
delete wdt; delete wdt;
} }
...@@ -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() ) try
hit.add( localGetValue( hit.ioit, hit.ioit->second.si.id ), it.size );
else
{ {
try hit.add( localGetValue( hit.ioit, hit.id ), it.size );
{ }
catch( IOController_i::Undefined& ex )
hit.add( localGetValue( hit.ioit, hit.id ), it.size ); {
continue; hit.add( numeric_limits<long>::max(), it.size );
}
catch(...){}
} }
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;
......
...@@ -64,7 +64,7 @@ smReadyTimeout(15000) ...@@ -64,7 +64,7 @@ smReadyTimeout(15000)
for( ; it.getCurrent(); it.goNext() ) for( ; it.getCurrent(); it.goNext() )
{ {
UniSetTypes::ObjectId id; UniSetTypes::ObjectId id;
string n(it.getProp("id")); string n(it.getProp("id"));
if( !n.empty() ) if( !n.empty() )
id = it.getIntProp("id"); id = it.getIntProp("id");
...@@ -73,7 +73,7 @@ smReadyTimeout(15000) ...@@ -73,7 +73,7 @@ smReadyTimeout(15000)
id = conf->getControllerID( it.getProp("name") ); id = conf->getControllerID( it.getProp("name") );
n = it.getProp("name"); n = it.getProp("name");
} }
if( id == DefaultObjectId ) if( id == DefaultObjectId )
throw SystemError("(UniExchange): Uknown ID for " + n ); throw SystemError("(UniExchange): Uknown ID for " + n );
...@@ -90,7 +90,7 @@ smReadyTimeout(15000) ...@@ -90,7 +90,7 @@ smReadyTimeout(15000)
if( id == DefaultObjectId ) if( id == DefaultObjectId )
throw SystemError("(UniExchange): Uknown ID for node=" + n1 ); throw SystemError("(UniExchange): Uknown ID for node=" + n1 );
NetNodeInfo ni; NetNodeInfo ni;
ni.oref = CORBA::Object::_nil(); ni.oref = CORBA::Object::_nil();
ni.id = id; ni.id = id;
...@@ -98,10 +98,10 @@ smReadyTimeout(15000) ...@@ -98,10 +98,10 @@ 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) );
} }
} }
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
readConfiguration(); readConfiguration();
...@@ -204,9 +204,9 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI ...@@ -204,9 +204,9 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI
// init new map... // init new map...
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]);
...@@ -218,7 +218,7 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI ...@@ -218,7 +218,7 @@ void UniExchange::NetNodeInfo::update( IOController_i::ShortMapSeq_var& map, SMI
} }
s->val = m->value; s->val = m->value;
try try
{ {
/* /*
...@@ -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);
......
...@@ -61,9 +61,16 @@ class UniExchange: ...@@ -61,9 +61,16 @@ class UniExchange:
std::string s_field; std::string s_field;
std::string s_fvalue; std::string s_fvalue;
SMInterface* shm; SMInterface* shm;
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),
...@@ -76,13 +83,20 @@ class UniExchange: ...@@ -76,13 +83,20 @@ class UniExchange:
UniversalIO::IOType type; UniversalIO::IOType type;
UniSetTypes::uniset_rwmutex val_lock; UniSetTypes::uniset_rwmutex val_lock;
}; };
typedef std::vector<SInfo> SList; typedef std::vector<SInfo> SList;
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;
IOController_i_var shm; IOController_i_var shm;
UniSetTypes::ObjectId id; UniSetTypes::ObjectId id;
......
...@@ -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,15 +171,25 @@ class IONotifyController: ...@@ -171,15 +171,25 @@ 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;
struct ConsumerListInfo struct ConsumerListInfo
{ {
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);
...@@ -312,7 +327,7 @@ class IONotifyController: ...@@ -312,7 +327,7 @@ class IONotifyController:
/*! замок для блокирования совместного доступа к cписку потребителей датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей датчиков */
UniSetTypes::uniset_rwmutex askIOMutex; UniSetTypes::uniset_rwmutex askIOMutex;
/*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */
UniSetTypes::uniset_rwmutex trshMutex; UniSetTypes::uniset_rwmutex trshMutex;
int maxAttemtps; /*! timeout for consumer */ int maxAttemtps; /*! timeout for consumer */
......
...@@ -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);
} }
}; };
...@@ -91,7 +91,7 @@ namespace UniSetTypes ...@@ -91,7 +91,7 @@ namespace UniSetTypes
{ {
if( priority != msg.priority ) if( priority != msg.priority )
return priority < msg.priority; return priority < msg.priority;
if( tm.tv_sec != msg.tm.tv_sec ) if( tm.tv_sec != msg.tm.tv_sec )
return tm.tv_sec >= msg.tm.tv_sec; return tm.tv_sec >= msg.tm.tv_sec;
...@@ -121,7 +121,7 @@ namespace UniSetTypes ...@@ -121,7 +121,7 @@ namespace UniSetTypes
UniversalIO::IOType sensor_type; UniversalIO::IOType sensor_type;
IOController_i::CalibrateInfo ci; IOController_i::CalibrateInfo ci;
// для пороговых датчиков // для пороговых датчиков
bool threshold; /*!< TRUE - сработал порог, FALSE - порог отключился */ bool threshold; /*!< TRUE - сработал порог, FALSE - порог отключился */
UniSetTypes::ThresholdId tid; UniSetTypes::ThresholdId tid;
......
...@@ -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 )
...@@ -121,7 +126,7 @@ class NCRestorer_XML: ...@@ -121,7 +126,7 @@ class NCRestorer_XML:
\param fname - файл. (формата uniset-project) \param fname - файл. (формата uniset-project)
\param sensor_filterField - читать из списка только те узлы, у которых filterField="filterValue" \param sensor_filterField - читать из списка только те узлы, у которых filterField="filterValue"
\param sensor_filterValue - значение для фильтрования списка \param sensor_filterValue - значение для фильтрования списка
*/ */
NCRestorer_XML( const std::string& fname, const std::string& sensor_filterField, const std::string& sensor_filterValue="" ); NCRestorer_XML( const std::string& fname, const std::string& sensor_filterField, const std::string& sensor_filterValue="" );
virtual ~NCRestorer_XML(); virtual ~NCRestorer_XML();
...@@ -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() );
} }
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
...@@ -142,52 +142,52 @@ namespace ORepHelpers ...@@ -142,52 +142,52 @@ namespace ORepHelpers
CosNaming::NamingContext_ptr getRootNamingContext(const CORBA::ORB_ptr orb, const string& nsName, int timeoutSec) CosNaming::NamingContext_ptr getRootNamingContext(const CORBA::ORB_ptr orb, const string& nsName, int timeoutSec)
{ {
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;
rootContext = CosNaming::NamingContext::_narrow(initServ);
if (CORBA::is_nil(rootContext))
{
string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу.");
throw ORepFailed(err.c_str());
}
rootContext = CosNaming::NamingContext::_narrow(initServ); ulogrep << "OREPHELP: init NameService ok"<< endl;
if (CORBA::is_nil(rootContext)) }
catch(CORBA::ORB::InvalidName& ex)
{ {
string err("ORepHelpers: Не удалось преобразовать ссылку к нужному типу."); ostringstream err;
throw ORepFailed(err.c_str()); 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; ulogrep << "OREPHELP: get root context 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;
// // Если создан как _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,344 +31,344 @@ using namespace std; ...@@ -31,344 +31,344 @@ 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;
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;
}
if( !limit )
return ret; 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 ) // Переворачиваем calMin и calMax для проверки, если calMin > calMax
return ret; if (calMin < calMax) {
return setinregion(ret, 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::setinregion(long ret, long calMin, long calMax) // -------------------------------------------------------------------------
{ // Пересчитываем из исходных пределов в заданные
// Переворачиваем calMin и calMax для проверки, если calMin > calMax long UniSetTypes::lcalibrate(long raw, long rawMin, long rawMax, long calMin, long calMax, bool limit )
if (calMin < calMax) { {
if( ret < calMin ) if( rawMax == rawMin ) return 0; // деление на 0!!!
return calMin;
if( ret > calMax )
return calMax;
} else {
if( ret > calMin )
return calMin;
if( ret < calMax )
return calMax;
}
long ret = lroundf( (float)(raw - rawMin) * (float)(calMax - calMin) /
(float)( rawMax - rawMin ) + calMin );
if( !limit )
return ret; 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;
} }
// Выводим указанное значение из заданных пределов (на границы) 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))
{ ret = calMax;
if ((ret*10) >= ((calMax + calMin)*5)) else
ret = calMax; ret = calMin;
else
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 )
{
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 ) lst.erase(it);
return; 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 ) l.add( uni_atoi(s) );
{ prev=pos+1;
lst.erase(it);
return;
}
} }
} }
while( pos!=string::npos );
std::list<UniSetTypes::ObjectId> UniSetTypes::IDList::getList()
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;
}
} }
while( pos!=string::npos );
UniSetTypes::ObjectId UniSetTypes::IDList::getFirst()
return l;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s )
{
for( auto c: s )
{ {
if( lst.empty() ) if( !isdigit(c) )
return UniSetTypes::DefaultObjectId; return false;
return (*lst.begin());
} }
// за освобождение выделеной памяти return true;
// отвечает вызывающий! //return (std::count_if(s.begin(),s.end(),std::isdigit) == s.size()) ? true : false;
IDSeq* UniSetTypes::IDList::getIDSeq() }
{ // --------------------------------------------------------------------------------------
IDSeq* seq = new IDSeq(); std::list<UniSetTypes::ParamSInfo> UniSetTypes::getSInfoList( const string& str, Configuration* conf )
seq->length(lst.size()); {
int i=0; std::list<UniSetTypes::ParamSInfo> res;
for( auto it=lst.begin(); it!=lst.end(); ++it,i++ )
(*seq)[i] = (*it);
return seq; auto lst = UniSetTypes::explode_str(str,',');
} for( auto it: lst )
// -------------------------------------------------------------------------
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; UniSetTypes::ParamSInfo item;
string::size_type prev = 0; auto p = UniSetTypes::explode_str(it,'=');
string::size_type pos = 0; std::string s = "";
do if( p.size() == 1 )
{ {
pos = str.find(sep,prev); s = *(p.begin());
string s(str.substr(prev,pos-prev)); item.val = 0;
if( !s.empty() )
{
l.add( uni_atoi(s) );
prev=pos+1;
}
} }
while( pos!=string::npos ); else if( p.size() == 2 )
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
{ {
pos = str.find(sep,prev); s = *(p.begin());
string s(str.substr(prev,pos-prev)); item.val = uni_atoi(*(++p.begin()));
if( !s.empty() )
{
l.push_back(s);
prev=pos+1;
}
} }
while( pos!=string::npos ); else
return l;
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s )
{
for( auto c: s )
{ {
if( !isdigit(c) ) cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl;
return false; 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,','); item.fname = s;
for( auto it: lst ) auto t = UniSetTypes::explode_str(s,'@');
if( t.size() == 1 )
{ {
UniSetTypes::ParamSInfo item; std::string s_id = *(t.begin());
if( is_digit(s_id) )
auto p = UniSetTypes::explode_str(it,'='); item.si.id = uni_atoi(s_id);
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()));
}
else else
{ item.si.id = conf->getSensorID(s_id);
cerr << "WARNING: parse error for '" << it << "'. IGNORE..." << endl; item.si.node = DefaultObjectId;
continue; }
} else if( t.size() == 2 )
{
item.fname = s; std::string s_id = *(t.begin());
auto t = UniSetTypes::explode_str(s,'@'); std::string s_node = *(++t.begin());
if( t.size() == 1 ) if( is_digit(s_id) )
{ item.si.id = uni_atoi(s_id);
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);
}
else else
{ item.si.id = conf->getSensorID(s_id);
cerr << "WARNING: parse error for '" << s << "'. IGNORE..." << endl;
continue;
}
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 ) return res;
{ }
if ( stype == "DI" || stype == "di" ) // --------------------------------------------------------------------------------------
return UniversalIO::DI;
if( stype == "AI" || stype == "ai" ) UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype )
return UniversalIO::AI; {
if ( stype == "DO" || stype == "do" ) if ( stype == "DI" || stype == "di" )
return UniversalIO::DO; return UniversalIO::DI;
if ( stype == "AO" || stype == "ao" ) if( stype == "AI" || stype == "ai" )
return UniversalIO::AO; return UniversalIO::AI;
if ( stype == "DO" || stype == "do" )
return UniversalIO::UnknownIOType; return UniversalIO::DO;
} if ( stype == "AO" || stype == "ao" )
// ------------------------------------------------------------------------------------------ return UniversalIO::AO;
std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOType t )
{ return UniversalIO::UnknownIOType;
if( t == UniversalIO::AI ) }
return os << "AI"; // ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOType t )
if( t == UniversalIO::DI ) {
return os << "DI"; if( t == UniversalIO::AI )
return os << "AI";
if( t == UniversalIO::AO )
return os << "AO"; if( t == UniversalIO::DI )
return os << "DI";
if( t == UniversalIO::DO )
return os << "DO"; if( t == UniversalIO::AO )
return os << "AO";
return os << "UnknownIOType";
} if( t == UniversalIO::DO )
// ------------------------------------------------------------------------------------------ return os << "DO";
std::ostream& UniSetTypes::operator<<( std::ostream& os, const IOController_i::CalibrateInfo c )
{ return os << "UnknownIOType";
return os << " rmin=" << c.minRaw << " rmax=" << c.maxRaw }
<< " cmin=" << c.minCal << " cmax=" << c.maxCal // ------------------------------------------------------------------------------------------
<< " precision=" << c.precision; std::ostream& UniSetTypes::operator<<( std::ostream& os, const IOController_i::CalibrateInfo c )
} {
// ------------------------------------------------------------------------------------------ return os << " rmin=" << c.minRaw << " rmax=" << c.maxRaw
bool UniSetTypes::check_filter( UniXML_iterator& it, const std::string& f_prop, const std::string& f_val ) << " cmin=" << c.minCal << " cmax=" << c.maxCal
{ << " precision=" << c.precision;
if( f_prop.empty() ) }
return true; // ------------------------------------------------------------------------------------------
bool UniSetTypes::check_filter( UniXML_iterator& it, const std::string& f_prop, const std::string& f_val )
// просто проверка на не пустой field {
if( f_val.empty() && it.getProp(f_prop).empty() ) if( f_prop.empty() )
return false;
// просто проверка что field = value
if( !f_val.empty() && it.getProp(f_prop)!=f_val )
return false;
return true; 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 ...@@ -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();
localGetValue(li,sid); try
{
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);
...@@ -547,20 +540,21 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp ...@@ -547,20 +540,21 @@ void IONotifyController::askThreshold(UniSetTypes::ObjectId sid, const UniSetTyp
case UniversalIO::UIONotify: // заказ case UniversalIO::UIONotify: // заказ
case UniversalIO::UIONotifyChange: case UniversalIO::UIONotifyChange:
{ {
if( it==askTMap.end() ) if( it==askTMap.end() )
{ {
ThresholdExtList lst; // создаем новый список ThresholdExtList lst; // создаем новый список
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 )
...@@ -942,9 +934,9 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList() ...@@ -942,9 +934,9 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
{ {
try try
{ {
(*res)[i].si = it->second.si; (*res)[i].si = it->second.si;
(*res)[i].value = IOController::localGetValue(it->second.ait,it->second.si.id); (*res)[i].value = IOController::localGetValue(it->second.ait,it->second.si.id);
(*res)[i].type = it->second.type; (*res)[i].type = it->second.type;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
...@@ -959,12 +951,12 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList() ...@@ -959,12 +951,12 @@ IONotifyController_i::ThresholdsListSeq* IONotifyController::getThresholdsList()
unsigned int k=0; unsigned int k=0;
for( auto it2=it->second.list.begin(); it2!=it->second.list.end(); ++it2 ) for( auto it2=it->second.list.begin(); it2!=it->second.list.end(); ++it2 )
{ {
(*res)[i].tlist[k].id = it2->id; (*res)[i].tlist[k].id = it2->id;
(*res)[i].tlist[k].hilimit = it2->hilimit; (*res)[i].tlist[k].hilimit = it2->hilimit;
(*res)[i].tlist[k].lowlimit = it2->lowlimit; (*res)[i].tlist[k].lowlimit = it2->lowlimit;
(*res)[i].tlist[k].state = it2->state; (*res)[i].tlist[k].state = it2->state;
(*res)[i].tlist[k].tv_sec = it2->tv_sec; (*res)[i].tlist[k].tv_sec = it2->tv_sec;
(*res)[i].tlist[k].tv_usec = it2->tv_usec; (*res)[i].tlist[k].tv_usec = it2->tv_usec;
k++; k++;
} }
i++; i++;
......
...@@ -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);
} }
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -348,7 +348,7 @@ void NCRestorer_XML::read_thresholds(const UniXML& xml, xmlNode* node, IONotifyC ...@@ -348,7 +348,7 @@ void NCRestorer_XML::read_thresholds(const UniXML& xml, xmlNode* node, IONotifyC
continue; continue;
} }
uinfo << ic->getName() << "(read_thresholds): " << it.getProp("name") << endl; uinfo << ic->getName() << "(read_thresholds): " << it.getProp("name") << endl;
UniXML_iterator tit(it); UniXML_iterator tit(it);
if( !tit.goChildren() ) if( !tit.goChildren() )
...@@ -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";
......
...@@ -79,8 +79,8 @@ threshold(false), ...@@ -79,8 +79,8 @@ threshold(false),
tid(UniSetTypes::DefaultThresholdId) tid(UniSetTypes::DefaultThresholdId)
{ {
type = Message::SensorInfo; type = Message::SensorInfo;
sm_tv_sec = tm.tv_sec; sm_tv_sec = tm.tv_sec;
sm_tv_usec = tm.tv_usec; sm_tv_usec = tm.tv_usec;
ci.minRaw = 0; ci.minRaw = 0;
ci.maxRaw = 0; ci.maxRaw = 0;
......
...@@ -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