Commit ae323107 authored by Pavel Vainerman's avatar Pavel Vainerman

(Optimization): начал вписывать noexcept где возможно.

Для начала в самых используемых классах.
parent 87abb2e8
......@@ -32,7 +32,7 @@
// --------------------------------------------------------------------------
<xsl:call-template name="COMMON-CC-FILE"/>
// --------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::callback()
void <xsl:value-of select="$CLASSNAME"/>_SK::callback() noexcept
{
if( !active )
return;
......
......@@ -30,7 +30,7 @@
<xsl:call-template name="COMMON-CC-ALONE-FUNCS"/>
<xsl:call-template name="COMMON-CC-FILE"/>
// --------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::callback()
void <xsl:value-of select="$CLASSNAME"/>_SK::callback() noexept
{
if( !active )
return;
......
......@@ -33,7 +33,7 @@
// --------------------------------------------------------------------------
<xsl:call-template name="COMMON-CC-FILE"/>
// --------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::callback()
void <xsl:value-of select="$CLASSNAME"/>_SK::callback() noexcept
{
if( !active )
return;
......
......@@ -31,7 +31,7 @@
// --------------------------------------------------------------------------
<xsl:call-template name="COMMON-CC-FUNCS"/>
// --------------------------------------------------------------------------
void <xsl:value-of select="$CLASSNAME"/>_SK::callback()
void <xsl:value-of select="$CLASSNAME"/>_SK::callback() noexept
{
if( !active )
return;
......
......@@ -14,7 +14,7 @@
Name: libuniset2
Version: 2.5
Release: alt14
Release: alt13.1
Summary: UniSet - library for building distributed industrial control systems
License: LGPL
......@@ -486,8 +486,9 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
# ..
%changelog
* Sun Sep 11 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt14
* Sun Sep 11 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt13.1
- (ModbusTCPMster): refactoring
- (optimization): added the use of the qualifier 'noexcept'
* Fri Sep 09 2016 Pavel Vainerman <pv@altlinux.ru> 2.5-alt13
- minor fixes in millisecToPoco() and microsecToPoco() functions
......
......@@ -3,7 +3,7 @@
# See doc: http://www.gnu.org/software/hello/manual/autoconf/Generic-Programs.html
# AC_PREREQ(2.59)
AC_INIT([uniset2], [2.5.0], pv@etersoft.ru)
AC_INIT([uniset2], [2.5.1], pv@etersoft.ru)
AM_INIT_AUTOMAKE(AC_PACKAGE_NAME,AC_PACKAGE_VERSION)
LIBVER=2:5:0
......
......@@ -61,7 +61,7 @@ static unsigned short crc_16_tab[] =
// -------------------------------------------------------------------------
/* CRC-16 is based on the polynomial x^16 + x^15 + x^2 + 1. Bits are */
/* sent LSB to MSB. */
static int get_crc_16( uint16_t crc, unsigned char* buf, int size )
static int get_crc_16( uint16_t crc, unsigned char* buf, int size ) noexcept
{
while( size-- )
......@@ -89,7 +89,7 @@ static int get_crc_16( uint16_t crc, unsigned char* buf, int size )
return crc;
}
// -------------------------------------------------------------------------
uint16_t UniSetUDP::makeCRC( unsigned char* buf, size_t len )
uint16_t UniSetUDP::makeCRC( unsigned char* buf, size_t len ) noexcept
{
uint16_t crc = 0xffff;
crc = get_crc_16(crc, (unsigned char*)(buf), len);
......@@ -133,11 +133,11 @@ std::ostream& UniSetUDP::operator<<( std::ostream& os, UniSetUDP::UDPMessage& p
return os;
}
// -----------------------------------------------------------------------------
UDPMessage::UDPMessage()
UDPMessage::UDPMessage() noexcept
{
}
// -----------------------------------------------------------------------------
size_t UDPMessage::addAData( const UniSetUDP::UDPAData& dat )
size_t UDPMessage::addAData( const UniSetUDP::UDPAData& dat ) noexcept
{
if( acount >= MaxACount )
return MaxACount;
......@@ -147,13 +147,13 @@ size_t UDPMessage::addAData( const UniSetUDP::UDPAData& dat )
return acount - 1;
}
// -----------------------------------------------------------------------------
size_t UDPMessage::addAData( long id, long val)
size_t UDPMessage::addAData( long id, long val) noexcept
{
UDPAData d(id, val);
return addAData(d);
}
// -----------------------------------------------------------------------------
bool UDPMessage::setAData( size_t index, long val )
bool UDPMessage::setAData( size_t index, long val ) noexcept
{
if( index < MaxACount )
{
......@@ -164,7 +164,7 @@ bool UDPMessage::setAData( size_t index, long val )
return false;
}
// -----------------------------------------------------------------------------
size_t UDPMessage::addDData( long id, bool val )
size_t UDPMessage::addDData( long id, bool val ) noexcept
{
if( dcount >= MaxDCount )
return MaxDCount;
......@@ -183,7 +183,7 @@ size_t UDPMessage::addDData( long id, bool val )
return MaxDCount;
}
// -----------------------------------------------------------------------------
bool UDPMessage::setDData( size_t index, bool val )
bool UDPMessage::setDData( size_t index, bool val ) noexcept
{
if( index >= MaxDCount )
return false;
......@@ -203,7 +203,7 @@ bool UDPMessage::setDData( size_t index, bool val )
return true;
}
// -----------------------------------------------------------------------------
long UDPMessage::dID( size_t index ) const
long UDPMessage::dID( size_t index ) const noexcept
{
if( index >= MaxDCount )
return UniSetTypes::DefaultObjectId;
......@@ -211,7 +211,7 @@ long UDPMessage::dID( size_t index ) const
return d_id[index];
}
// -----------------------------------------------------------------------------
bool UDPMessage::dValue( size_t index ) const
bool UDPMessage::dValue( size_t index ) const noexcept
{
if( index >= MaxDCount )
return UniSetTypes::DefaultObjectId;
......@@ -222,7 +222,7 @@ bool UDPMessage::dValue( size_t index ) const
return ( d_dat[nbyte] & (1 << nbit) );
}
// -----------------------------------------------------------------------------
size_t UDPMessage::transport_msg( UDPPacket& p )
size_t UDPMessage::transport_msg( UDPPacket& p ) const noexcept
{
memset(&p, 0, sizeof(UDPPacket));
......@@ -251,7 +251,7 @@ size_t UDPMessage::transport_msg( UDPPacket& p )
return i;
}
// -----------------------------------------------------------------------------
long UDPMessage::getDataID() const
long UDPMessage::getDataID() const noexcept
{
// в качестве идентификатора берётся ID первого датчика в данных
// приоритет имеет аналоговые датчики
......@@ -266,7 +266,7 @@ long UDPMessage::getDataID() const
return num;
}
size_t UniSetUDP::UDPMessage::sizeOf() const
size_t UniSetUDP::UDPMessage::sizeOf() const noexcept
{
// биты которые не уместились в очередной байт, добавляют ещё один байт
size_t nbit = dcount % 8 * sizeof(unsigned char);
......@@ -275,12 +275,12 @@ size_t UniSetUDP::UDPMessage::sizeOf() const
return sizeof(UDPHeader) + acount * sizeof(UDPAData) + dcount * sizeof(long) + (dcount / 8 * sizeof(unsigned char) + add);
}
// -----------------------------------------------------------------------------
UDPMessage::UDPMessage( UDPPacket& p )
UDPMessage::UDPMessage( UDPPacket& p ) noexcept
{
getMessage(*this, p);
}
// -----------------------------------------------------------------------------
size_t UDPMessage::getMessage( UDPMessage& m, UDPPacket& p )
size_t UDPMessage::getMessage( UDPMessage& m, UDPPacket& p ) noexcept
{
memset(&m, 0, sizeof(m));
......@@ -326,7 +326,7 @@ size_t UDPMessage::getMessage( UDPMessage& m, UDPPacket& p )
return i + sz;
}
// -----------------------------------------------------------------------------
uint16_t UDPMessage::getDataCRC() const
uint16_t UDPMessage::getDataCRC() const noexcept
{
uint16_t crc[3];
crc[0] = makeCRC( (unsigned char*)(a_dat), sizeof(a_dat) );
......
......@@ -41,7 +41,7 @@ namespace UniSetUDP
struct UDPHeader
{
UDPHeader(): magic(UNETUDP_MAGICNUM), num(0), nodeID(0), procID(0), dcount(0), acount(0) {}
UDPHeader() noexcept: magic(UNETUDP_MAGICNUM), num(0), nodeID(0), procID(0), dcount(0), acount(0) {}
uint32_t magic;
size_t num;
long nodeID;
......@@ -58,8 +58,8 @@ namespace UniSetUDP
struct UDPAData
{
UDPAData(): id(UniSetTypes::DefaultObjectId), val(0) {}
UDPAData(long id, long val): id(id), val(val) {}
UDPAData() noexcept: id(UniSetTypes::DefaultObjectId), val(0) {}
UDPAData(long id, long val) noexcept: id(id), val(val) {}
long id;
long val;
......@@ -79,7 +79,7 @@ namespace UniSetUDP
struct UDPPacket
{
UDPPacket(): len(0) {}
UDPPacket() noexcept: len(0) {}
size_t len;
uint8_t data[ sizeof(UDPHeader) + MaxDCount * sizeof(long) + MaxDDataCount + MaxACount * sizeof(UDPAData) ];
......@@ -90,58 +90,72 @@ namespace UniSetUDP
struct UDPMessage:
public UDPHeader
{
UDPMessage();
UDPMessage() noexcept;
UDPMessage(UDPMessage&& m) = default;
UDPMessage& operator=(UDPMessage&&) = default;
UDPMessage(UDPMessage&& m) noexcept = default;
UDPMessage& operator=(UDPMessage&&) noexcept = default;
UDPMessage( const UDPMessage& m ) = default;
UDPMessage& operator=(const UDPMessage&) = default;
UDPMessage( const UDPMessage& m ) noexcept = default;
UDPMessage& operator=(const UDPMessage&) noexcept = default;
explicit UDPMessage( UDPPacket& p );
size_t transport_msg( UDPPacket& p );
static size_t getMessage( UDPMessage& m, UDPPacket& p );
explicit UDPMessage( UDPPacket& p ) noexcept;
size_t transport_msg( UDPPacket& p ) const noexcept;
size_t addDData( long id, bool val );
bool setDData( size_t index, bool val );
long dID( size_t index ) const;
bool dValue( size_t index ) const;
static size_t getMessage( UDPMessage& m, UDPPacket& p ) noexcept;
// \warning в случае переполнения возвращается MaxDCount
size_t addDData( long id, bool val ) noexcept;
//!\return true - successful
bool setDData( size_t index, bool val ) noexcept;
//! \return UniSetTypes::DefaultObjectId if not found
long dID( size_t index ) const noexcept;
//! \return UniSetTypes::DefaultObjectId if not found
bool dValue( size_t index ) const noexcept;
// функции addAData возвращают индекс, по которому потом можно напрямую писать при помощи setAData(index)
size_t addAData( const UDPAData& dat );
size_t addAData( long id, long val );
bool setAData( size_t index, long val );
// \warning в случае переполнения возвращается MaxACount
size_t addAData( const UDPAData& dat ) noexcept;
size_t addAData( long id, long val ) noexcept;
long getDataID( ) const; /*!< получение "уникального" идентификатора данных этого пакета */
inline bool isAFull() const
//!\return true - successful
bool setAData( size_t index, long val ) noexcept;
long getDataID( ) const noexcept; /*!< получение "уникального" идентификатора данных этого пакета */
inline bool isAFull() const noexcept
{
return (acount >= MaxACount);
}
inline bool isDFull() const
inline bool isDFull() const noexcept
{
return (dcount >= MaxDCount);
}
inline bool isFull() const
inline bool isFull() const noexcept
{
return !((dcount < MaxDCount) && (acount < MaxACount));
}
inline size_t dsize() const
inline size_t dsize() const noexcept
{
return dcount;
}
inline size_t asize() const
inline size_t asize() const noexcept
{
return acount;
}
// размер итогового пакета в байтах
size_t sizeOf() const;
size_t sizeOf() const noexcept;
uint16_t getDataCRC() const;
uint16_t getDataCRC() const noexcept;
// количество байт в пакете с булевыми переменными...
size_t d_byte() const
size_t d_byte() const noexcept
{
return dcount * sizeof(long) + dcount;
}
......@@ -153,7 +167,7 @@ namespace UniSetUDP
friend std::ostream& operator<<( std::ostream& os, UDPMessage& p );
};
uint16_t makeCRC( unsigned char* buf, size_t len );
uint16_t makeCRC( unsigned char* buf, size_t len ) noexcept;
}
// -----------------------------------------------------------------------------
#endif // UDPPacket_H_
......
......@@ -444,7 +444,7 @@ UNetExchange::~UNetExchange()
{
}
// -----------------------------------------------------------------------------
bool UNetExchange::checkExistUNetHost(const std::string& addr, int port )
bool UNetExchange::checkExistUNetHost(const std::string& addr, int port ) noexcept
{
for( const auto& it : recvlist )
{
......@@ -497,7 +497,7 @@ void UNetExchange::timerInfo( const TimerMessage* tm )
step();
}
// -----------------------------------------------------------------------------
void UNetExchange::step()
void UNetExchange::step() noexcept
{
if( !activated )
return;
......@@ -509,9 +509,9 @@ void UNetExchange::step()
shm->localSetValue(itHeartBeat, sidHeartBeat, maxHeartBeat, getId());
ptHeartBeat.reset();
}
catch( const Exception& ex )
catch( const std::exception& ex )
{
unetcrit << myname << "(step): (hb) " << ex << std::endl;
unetcrit << myname << "(step): (hb) " << ex.what() << std::endl;
}
}
......@@ -520,7 +520,7 @@ void UNetExchange::step()
}
// -----------------------------------------------------------------------------
void UNetExchange::ReceiverInfo::step( const std::shared_ptr<SMInterface>& shm, const std::string& myname, std::shared_ptr<DebugStream>& unetlog )
void UNetExchange::ReceiverInfo::step( const std::shared_ptr<SMInterface>& shm, const std::string& myname, std::shared_ptr<DebugStream>& unetlog ) noexcept
{
try
{
......@@ -534,9 +534,9 @@ void UNetExchange::ReceiverInfo::step( const std::shared_ptr<SMInterface>& shm,
shm->localSetValue(itRespond, sidRespond, resp, shm->ID());
}
}
catch( const Exception& ex )
catch( const std::exception& ex )
{
unetcrit << myname << "(ReceiverInfo::step): (respond): " << ex << std::endl;
unetcrit << myname << "(ReceiverInfo::step): (respond): " << ex.what() << std::endl;
}
try
......@@ -554,9 +554,9 @@ void UNetExchange::ReceiverInfo::step( const std::shared_ptr<SMInterface>& shm,
shm->localSetValue(itLostPackets, sidLostPackets, l, shm->ID());
}
}
catch( const Exception& ex )
catch( const std::exception& ex )
{
unetcrit << myname << "(ReceiverInfo::step): (lostpackets): " << ex << std::endl;
unetcrit << myname << "(ReceiverInfo::step): (lostpackets): " << ex.what() << std::endl;
}
try
......@@ -574,9 +574,9 @@ void UNetExchange::ReceiverInfo::step( const std::shared_ptr<SMInterface>& shm,
shm->localSetValue(itChannelNum, sidChannelNum, c, shm->ID());
}
}
catch( const Exception& ex )
catch( const std::exception& ex )
{
unetcrit << myname << "(ReceiverInfo::step): (channelnum): " << ex << std::endl;
unetcrit << myname << "(ReceiverInfo::step): (channelnum): " << ex.what() << std::endl;
}
}
// -----------------------------------------------------------------------------
......@@ -775,7 +775,7 @@ void UNetExchange::sigterm( int signo )
UniSetObject::sigterm(signo);
}
// ------------------------------------------------------------------------------------------
void UNetExchange::initIterators()
void UNetExchange::initIterators() noexcept
{
shm->initIterator(itHeartBeat);
......@@ -789,7 +789,7 @@ void UNetExchange::initIterators()
it.initIterators(shm);
}
// -----------------------------------------------------------------------------
void UNetExchange::help_print( int argc, const char* argv[] )
void UNetExchange::help_print( int argc, const char* argv[] ) noexcept
{
cout << "Default prefix='unet'" << endl;
cout << "--prefix-name NameID - Идентификтора процесса." << endl;
......@@ -858,7 +858,7 @@ std::shared_ptr<UNetExchange> UNetExchange::init_unetexchange(int argc, const ch
return make_shared<UNetExchange>(ID, icID, ic, prefix);
}
// -----------------------------------------------------------------------------
void UNetExchange::receiverEvent( const shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev )
void UNetExchange::receiverEvent( const shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev ) noexcept
{
for( auto && it : recvlist )
{
......
......@@ -131,15 +131,15 @@ class UNetExchange:
UniSetTypes::ObjectId shmID, const std::shared_ptr<SharedMemory>& ic = 0, const std::string& prefix = "unet" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* argv[] );
static void help_print( int argc, const char* argv[] ) noexcept;
bool checkExistUNetHost( const std::string& host, int port );
bool checkExistUNetHost( const std::string& host, int port ) noexcept;
inline std::shared_ptr<LogAgregator> getLogAggregator()
inline std::shared_ptr<LogAgregator> getLogAggregator() noexcept
{
return loga;
}
inline std::shared_ptr<DebugStream> log()
inline std::shared_ptr<DebugStream> log() noexcept
{
return unetlog;
}
......@@ -153,14 +153,14 @@ class UNetExchange:
std::string s_fvalue;
std::shared_ptr<SMInterface> shm;
void step();
void step() noexcept;
void sysCommand( const UniSetTypes::SystemMessage* msg ) override;
void sensorInfo( const UniSetTypes::SensorMessage* sm ) override;
void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
void askSensors( UniversalIO::UIOCommand cmd );
void waitSMReady();
void receiverEvent( const std::shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev );
void receiverEvent( const std::shared_ptr<UNetReceiver>& r, UNetReceiver::Event ev ) noexcept;
virtual bool activateObject() override;
virtual bool deactivateObject() override;
......@@ -170,7 +170,7 @@ class UNetExchange:
void termSenders();
void termReceivers();
void initIterators();
void initIterators() noexcept;
void startReceivers();
enum Timer
......@@ -196,14 +196,14 @@ class UNetExchange:
struct ReceiverInfo
{
ReceiverInfo(): r1(nullptr), r2(nullptr),
ReceiverInfo() noexcept: r1(nullptr), r2(nullptr),
sidRespond(UniSetTypes::DefaultObjectId),
respondInvert(false),
sidLostPackets(UniSetTypes::DefaultObjectId),
sidChannelNum(UniSetTypes::DefaultObjectId)
{}
ReceiverInfo( const std::shared_ptr<UNetReceiver>& _r1, const std::shared_ptr<UNetReceiver>& _r2 ):
ReceiverInfo( const std::shared_ptr<UNetReceiver>& _r1, const std::shared_ptr<UNetReceiver>& _r2 ) noexcept:
r1(_r1), r2(_r2),
sidRespond(UniSetTypes::DefaultObjectId),
respondInvert(false),
......@@ -214,23 +214,23 @@ class UNetExchange:
std::shared_ptr<UNetReceiver> r1; /*!< приём по первому каналу */
std::shared_ptr<UNetReceiver> r2; /*!< приём по второму каналу */
void step(const std::shared_ptr<SMInterface>& shm, const std::string& myname, std::shared_ptr<DebugStream>& log );
void step(const std::shared_ptr<SMInterface>& shm, const std::string& myname, std::shared_ptr<DebugStream>& log ) noexcept;
inline void setRespondID( UniSetTypes::ObjectId id, bool invert = false )
inline void setRespondID( UniSetTypes::ObjectId id, bool invert = false ) noexcept
{
sidRespond = id;
respondInvert = invert;
}
inline void setLostPacketsID( UniSetTypes::ObjectId id )
inline void setLostPacketsID( UniSetTypes::ObjectId id ) noexcept
{
sidLostPackets = id;
}
inline void setChannelNumID( UniSetTypes::ObjectId id )
inline void setChannelNumID( UniSetTypes::ObjectId id ) noexcept
{
sidChannelNum = id;
}
inline void initIterators( const std::shared_ptr<SMInterface>& shm )
inline void initIterators( const std::shared_ptr<SMInterface>& shm ) noexcept
{
shm->initIterator(itLostPackets);
shm->initIterator(itRespond);
......
......@@ -85,24 +85,24 @@ UNetReceiver::UNetReceiver(const std::string& s_host, int _port, const std::shar
evUpdate.set<UNetReceiver, &UNetReceiver::updateEvent>(this);
}
// -----------------------------------------------------------------------------
UNetReceiver::~UNetReceiver()
UNetReceiver::~UNetReceiver() noexcept
{
}
// -----------------------------------------------------------------------------
void UNetReceiver::setReceiveTimeout( timeout_t msec )
void UNetReceiver::setReceiveTimeout( timeout_t msec ) noexcept
{
std::lock_guard<std::mutex> l(tmMutex);
recvTimeout = msec;
ptRecvTimeout.setTiming(msec);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setPrepareTime( timeout_t msec )
void UNetReceiver::setPrepareTime( timeout_t msec ) noexcept
{
prepareTime = msec;
ptPrepare.setTiming(msec);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setCheckConnectionPause( timeout_t msec )
void UNetReceiver::setCheckConnectionPause( timeout_t msec ) noexcept
{
checkConnectionTime = (double)msec / 1000.0;
......@@ -110,18 +110,18 @@ void UNetReceiver::setCheckConnectionPause( timeout_t msec )
evCheckConnection.start(0, checkConnectionTime);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setLostTimeout( timeout_t msec )
void UNetReceiver::setLostTimeout( timeout_t msec ) noexcept
{
lostTimeout = msec;
ptLostTimeout.setTiming(msec);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setReceivePause( timeout_t msec )
void UNetReceiver::setReceivePause( timeout_t msec ) noexcept
{
recvpause = msec;
}
// -----------------------------------------------------------------------------
void UNetReceiver::setUpdatePause( timeout_t msec )
void UNetReceiver::setUpdatePause( timeout_t msec ) noexcept
{
updatepause = msec;
......@@ -129,30 +129,30 @@ void UNetReceiver::setUpdatePause( timeout_t msec )
evUpdate.start(0, (float)updatepause/1000.);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setMaxProcessingCount( int set )
void UNetReceiver::setMaxProcessingCount( int set ) noexcept
{
maxProcessingCount = set;
}
// -----------------------------------------------------------------------------
void UNetReceiver::setMaxDifferens( unsigned long set )
void UNetReceiver::setMaxDifferens( unsigned long set ) noexcept
{
maxDifferens = set;
}
// -----------------------------------------------------------------------------
void UNetReceiver::setRespondID( UniSetTypes::ObjectId id, bool invert )
void UNetReceiver::setRespondID( UniSetTypes::ObjectId id, bool invert ) noexcept
{
sidRespond = id;
respondInvert = invert;
shm->initIterator(itRespond);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setLostPacketsID( UniSetTypes::ObjectId id )
void UNetReceiver::setLostPacketsID( UniSetTypes::ObjectId id ) noexcept
{
sidLostPackets = id;
shm->initIterator(itLostPackets);
}
// -----------------------------------------------------------------------------
void UNetReceiver::setLockUpdate( bool st )
void UNetReceiver::setLockUpdate( bool st ) noexcept
{
lockUpdate = st;
......@@ -161,7 +161,7 @@ void UNetReceiver::setLockUpdate( bool st )
ptPrepare.reset();
}
// -----------------------------------------------------------------------------
void UNetReceiver::resetTimeout()
void UNetReceiver::resetTimeout() noexcept
{
std::lock_guard<std::mutex> l(tmMutex);
ptRecvTimeout.reset();
......@@ -232,7 +232,7 @@ void UNetReceiver::start()
forceUpdate();
}
// -----------------------------------------------------------------------------
void UNetReceiver::evprepare( const ev::loop_ref& eloop )
void UNetReceiver::evprepare( const ev::loop_ref& eloop ) noexcept
{
evStatistic.set(eloop);
evStatistic.start(0, 1.0); // раз в сек
......@@ -256,7 +256,7 @@ void UNetReceiver::evprepare( const ev::loop_ref& eloop )
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::evfinish( const ev::loop_ref& eloop )
void UNetReceiver::evfinish( const ev::loop_ref& eloop ) noexcept
{
activated = false;
......@@ -280,14 +280,14 @@ void UNetReceiver::evfinish( const ev::loop_ref& eloop )
udp = nullptr;
}
// -----------------------------------------------------------------------------
void UNetReceiver::forceUpdate()
void UNetReceiver::forceUpdate() noexcept
{
pack_guard l(packMutex,upStrategy);
pnum = 0; // сбрасываем запомненый номер последнего обработанного пакета
// и тем самым заставляем обновить данные в SM (см. update)
}
// -----------------------------------------------------------------------------
void UNetReceiver::statisticsEvent(ev::periodic& tm, int revents)
void UNetReceiver::statisticsEvent(ev::periodic& tm, int revents) noexcept
{
if( EV_ERROR & revents )
{
......@@ -308,7 +308,7 @@ void UNetReceiver::statisticsEvent(ev::periodic& tm, int revents)
tm.again();
}
// -----------------------------------------------------------------------------
void UNetReceiver::update()
void UNetReceiver::update() noexcept
{
UniSetUDP::UDPMessage p;
// обрабатываем, пока очередь либо не опустеет,
......@@ -465,7 +465,7 @@ void UNetReceiver::update()
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::updateThread()
void UNetReceiver::updateThread() noexcept
{
while( activated )
{
......@@ -507,7 +507,7 @@ void UNetReceiver::updateThread()
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::callback( ev::io& watcher, int revents )
void UNetReceiver::callback( ev::io& watcher, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -519,7 +519,7 @@ void UNetReceiver::callback( ev::io& watcher, int revents )
readEvent(watcher);
}
// -----------------------------------------------------------------------------
void UNetReceiver::readEvent( ev::io& watcher )
void UNetReceiver::readEvent( ev::io& watcher ) noexcept
{
if( !activated )
return;
......@@ -565,7 +565,7 @@ void UNetReceiver::readEvent( ev::io& watcher )
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::updateEvent( ev::periodic& tm, int revents )
void UNetReceiver::updateEvent( ev::periodic& tm, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -615,7 +615,7 @@ void UNetReceiver::updateEvent( ev::periodic& tm, int revents )
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::checkConnectionEvent( ev::periodic& tm, int revents )
void UNetReceiver::checkConnectionEvent( ev::periodic& tm, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -642,7 +642,7 @@ void UNetReceiver::stop()
loop.evstop(this);
}
// -----------------------------------------------------------------------------
bool UNetReceiver::receive()
bool UNetReceiver::receive() noexcept
{
try
{
......@@ -751,7 +751,7 @@ bool UNetReceiver::receive()
return true;
}
// -----------------------------------------------------------------------------
void UNetReceiver::initIterators()
void UNetReceiver::initIterators() noexcept
{
for( auto mit = d_icache_map.begin(); mit != d_icache_map.end(); ++mit )
{
......@@ -770,7 +770,7 @@ void UNetReceiver::initIterators()
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force )
void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force ) noexcept
{
CacheInfo& d_info(d_icache_map[pack.getDataID()]);
......@@ -814,7 +814,7 @@ void UNetReceiver::initDCache( UniSetUDP::UDPMessage& pack, bool force )
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::initACache( UniSetUDP::UDPMessage& pack, bool force )
void UNetReceiver::initACache( UniSetUDP::UDPMessage& pack, bool force ) noexcept
{
CacheInfo& a_info(a_icache_map[pack.getDataID()]);
......@@ -858,12 +858,12 @@ void UNetReceiver::initACache( UniSetUDP::UDPMessage& pack, bool force )
}
}
// -----------------------------------------------------------------------------
void UNetReceiver::connectEvent( UNetReceiver::EventSlot sl )
void UNetReceiver::connectEvent( UNetReceiver::EventSlot sl ) noexcept
{
slEvent = sl;
}
UNetReceiver::UpdateStrategy UNetReceiver::strToUpdateStrategy(const string& s)
// -----------------------------------------------------------------------------
UNetReceiver::UpdateStrategy UNetReceiver::strToUpdateStrategy( const string& s ) noexcept
{
if( s == "thread" || s == "THREAD" )
return useUpdateThread;
......@@ -874,7 +874,7 @@ UNetReceiver::UpdateStrategy UNetReceiver::strToUpdateStrategy(const string& s)
return useUpdateUnknown;
}
// -----------------------------------------------------------------------------
string UNetReceiver::to_string(UNetReceiver::UpdateStrategy s)
string UNetReceiver::to_string( UNetReceiver::UpdateStrategy s ) noexcept
{
if( s == useUpdateThread )
return "thread";
......@@ -905,7 +905,7 @@ void UNetReceiver::setUpdateStrategy( UNetReceiver::UpdateStrategy set )
upStrategy = set;
}
// -----------------------------------------------------------------------------
const std::string UNetReceiver::getShortInfo() const
const std::string UNetReceiver::getShortInfo() const noexcept
{
// warning: будет вызываться из другого потока
// (считаем что чтение безопасно)
......
......@@ -110,43 +110,43 @@ class UNetReceiver:
}
// блокировать сохранение данных в SM
void setLockUpdate( bool st );
inline bool isLockUpdate() const
void setLockUpdate( bool st ) noexcept;
inline bool isLockUpdate() const noexcept
{
return lockUpdate;
}
void resetTimeout();
void resetTimeout() noexcept;
inline bool isRecvOK() const
inline bool isRecvOK() const noexcept
{
return !ptRecvTimeout.checkTime();
}
inline size_t getLostPacketsNum() const
inline size_t getLostPacketsNum() const noexcept
{
return lostPackets;
}
void setReceiveTimeout( timeout_t msec );
void setReceivePause( timeout_t msec );
void setUpdatePause( timeout_t msec );
void setLostTimeout( timeout_t msec );
void setPrepareTime( timeout_t msec );
void setCheckConnectionPause( timeout_t msec );
void setMaxDifferens( unsigned long set );
void setReceiveTimeout( timeout_t msec ) noexcept;
void setReceivePause( timeout_t msec ) noexcept;
void setUpdatePause( timeout_t msec ) noexcept;
void setLostTimeout( timeout_t msec ) noexcept;
void setPrepareTime( timeout_t msec ) noexcept;
void setCheckConnectionPause( timeout_t msec ) noexcept;
void setMaxDifferens( unsigned long set ) noexcept;
void setRespondID( UniSetTypes::ObjectId id, bool invert = false );
void setLostPacketsID( UniSetTypes::ObjectId id );
void setRespondID( UniSetTypes::ObjectId id, bool invert = false ) noexcept;
void setLostPacketsID( UniSetTypes::ObjectId id ) noexcept;
void setMaxProcessingCount( int set );
void setMaxProcessingCount( int set ) noexcept;
void forceUpdate(); // пересохранить очередной пакет в SM даже если данные не менялись
void forceUpdate() noexcept; // пересохранить очередной пакет в SM даже если данные не менялись
inline std::string getAddress() const
inline std::string getAddress() const noexcept
{
return addr;
}
inline int getPort() const
inline int getPort() const noexcept
{
return port;
}
......@@ -159,7 +159,7 @@ class UNetReceiver:
};
typedef sigc::slot<void, const std::shared_ptr<UNetReceiver>&, Event> EventSlot;
void connectEvent( EventSlot sl );
void connectEvent( EventSlot sl ) noexcept;
// --------------------------------------------------------------------
/*! Стратегия обработки сообщений */
......@@ -170,8 +170,8 @@ class UNetReceiver:
useUpdateEventLoop /*!< использовать event loop (т.е. совместно с receive) */
};
static UpdateStrategy strToUpdateStrategy( const std::string& s );
static std::string to_string( UpdateStrategy s);
static UpdateStrategy strToUpdateStrategy( const std::string& s ) noexcept;
static std::string to_string( UpdateStrategy s) noexcept;
//! функция должна вызываться до первого вызова start()
void setUpdateStrategy( UpdateStrategy set );
......@@ -196,30 +196,30 @@ class UNetReceiver:
return unetlog;
}
virtual const std::string getShortInfo() const;
virtual const std::string getShortInfo() const noexcept;
protected:
const std::shared_ptr<SMInterface> shm;
std::shared_ptr<DebugStream> unetlog;
bool receive();
void step();
void update();
void updateThread();
void callback( ev::io& watcher, int revents );
void readEvent( ev::io& watcher );
void updateEvent( ev::periodic& watcher, int revents );
void checkConnectionEvent( ev::periodic& watcher, int revents );
void statisticsEvent( ev::periodic& watcher, int revents );
virtual void evprepare( const ev::loop_ref& eloop ) override;
virtual void evfinish(const ev::loop_ref& eloop ) override;
virtual std::string wname() override
bool receive() noexcept;
void step() noexcept;
void update() noexcept;
void updateThread() noexcept;
void callback( ev::io& watcher, int revents ) noexcept;
void readEvent( ev::io& watcher ) noexcept;
void updateEvent( ev::periodic& watcher, int revents ) noexcept;
void checkConnectionEvent( ev::periodic& watcher, int revents ) noexcept;
void statisticsEvent( ev::periodic& watcher, int revents ) noexcept;
virtual void evprepare( const ev::loop_ref& eloop ) noexcept override;
virtual void evfinish(const ev::loop_ref& eloop ) noexcept override;
virtual std::string wname() const noexcept override
{
return myname;
}
void initIterators();
void initIterators() noexcept;
bool createConnection( bool throwEx = false );
public:
......@@ -337,8 +337,8 @@ class UNetReceiver:
bool d_cache_init_ok = { false };
bool a_cache_init_ok = { false };
void initDCache( UniSetUDP::UDPMessage& pack, bool force = false );
void initACache( UniSetUDP::UDPMessage& pack, bool force = false );
void initDCache( UniSetUDP::UDPMessage& pack, bool force = false ) noexcept;
void initACache( UniSetUDP::UDPMessage& pack, bool force = false ) noexcept;
};
// -----------------------------------------------------------------------------
#endif // UNetReceiver_H_
......
......@@ -182,7 +182,7 @@ void UNetSender::setCheckConnectionPause( int msec )
ptCheckConnection.setTiming(msec);
}
// -----------------------------------------------------------------------------
void UNetSender::send()
void UNetSender::send() noexcept
{
unetinfo << myname << "(send): dlist size = " << items.size() << endl;
ncycle = 0;
......@@ -223,9 +223,9 @@ void UNetSender::send()
break;
auto& pk = it.second;
int size = pk.size();
size_t size = pk.size();
for(int i = 0; i < size; ++i)
for(size_t i = 0; i < size; ++i)
{
if( !activated )
break;
......@@ -265,34 +265,34 @@ void UNetSender::send()
// -----------------------------------------------------------------------------
// #define UNETUDP_DISABLE_OPTIMIZATION_N1
void UNetSender::real_send( PackMessage& mypack )
void UNetSender::real_send( PackMessage& mypack ) noexcept
{
UniSetTypes::uniset_rwmutex_rlock l(mypack.mut);
#ifdef UNETUDP_DISABLE_OPTIMIZATION_N1
mypack.msg.num = packetnum++;
#else
uint16_t crc = mypack.msg.getDataCRC();
if( crc != lastcrc )
try
{
UniSetTypes::uniset_rwmutex_rlock l(mypack.mut);
#ifdef UNETUDP_DISABLE_OPTIMIZATION_N1
mypack.msg.num = packetnum++;
lastcrc = crc;
}
#else
uint16_t crc = mypack.msg.getDataCRC();
if( crc != lastcrc )
{
mypack.msg.num = packetnum++;
lastcrc = crc;
}
#endif
// при переходе через ноль (когда счётчик перевалит через UniSetUDP::MaxPacketNum..
// делаем номер пакета "1"
if( packetnum == 0 )
packetnum = 1;
// при переходе через ноль (когда счётчик перевалит через UniSetUDP::MaxPacketNum..
// делаем номер пакета "1"
if( packetnum == 0 )
packetnum = 1;
if( !udp || !udp->poll( UniSetTimer::millisecToPoco(writeTimeout), Poco::Net::Socket::SELECT_WRITE) )
return;
mypack.msg.transport_msg(s_msg);
if( !udp || !udp->poll( UniSetTimer::millisecToPoco(writeTimeout), Poco::Net::Socket::SELECT_WRITE) )
return;
mypack.msg.transport_msg(s_msg);
try
{
size_t ret = udp->sendTo(&s_msg.data, s_msg.len, saddr);
if( ret < s_msg.len )
......@@ -302,6 +302,10 @@ void UNetSender::real_send( PackMessage& mypack )
{
unetcrit << myname << "(real_send): error: " << ex.displayText() << endl;
}
catch( std::exception& ex )
{
unetcrit << myname << "(real_send): error: " << ex.what() << endl;
}
}
// -----------------------------------------------------------------------------
void UNetSender::stop()
......
......@@ -98,20 +98,20 @@ class UNetSender
void start();
void stop();
void send();
void send() noexcept;
struct PackMessage
{
PackMessage( UniSetUDP::UDPMessage&& m ):msg(std::move(m)){}
PackMessage( UniSetUDP::UDPMessage&& m ) noexcept:msg(std::move(m)){}
PackMessage( const UniSetUDP::UDPMessage& m ) = delete;
PackMessage(){}
PackMessage() noexcept {}
UniSetUDP::UDPMessage msg;
UniSetTypes::uniset_rwmutex mut;
};
void real_send( PackMessage& mypack );
void real_send( PackMessage& mypack ) noexcept;
/*! (принудительно) обновить все данные (из SM) */
void updateFromSM();
......
......@@ -45,9 +45,9 @@ namespace VTypes
std::ostream& operator<<( std::ostream& os, const VType& vt );
// -------------------------------------------------------------------------
std::string type2str( VType t ); /*!< преобразование строки в тип */
VType str2type( const std::string& s ); /*!< преобразование названия в строку */
int wsize( VType t ); /*!< длина данных в словах */
std::string type2str( VType t ) noexcept; /*!< преобразование строки в тип */
VType str2type( const std::string& s ) noexcept; /*!< преобразование названия в строку */
int wsize( VType t ) noexcept; /*!< длина данных в словах */
// -------------------------------------------------------------------------
class F2
{
......@@ -63,22 +63,22 @@ namespace VTypes
} F2mem;
// ------------------------------------------
// конструкторы на разные случаи...
F2()
F2() noexcept
{
memset(raw.v, 0, sizeof(raw.v));
}
F2( const float& f )
F2( const float& f ) noexcept
{
raw.val = f;
}
F2( const ModbusRTU::ModbusData* data, size_t size )
F2( const ModbusRTU::ModbusData* data, size_t size ) noexcept
{
for( size_t i = 0; i < wsize() && i < size; i++ )
raw.v[i] = data[i];
}
~F2() {}
~F2() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -114,21 +114,21 @@ namespace VTypes
// ------------------------------------------
// конструкторы на разные случаи...
F2r() {}
F2r() noexcept {}
F2r( const float& f ): F2(f)
F2r( const float& f ) noexcept: F2(f)
{
raw_backorder = raw;
std::swap(raw_backorder.v[0], raw_backorder.v[1]);
}
F2r( const ModbusRTU::ModbusData* data, size_t size ): F2(data, size)
F2r( const ModbusRTU::ModbusData* data, size_t size ) noexcept: F2(data, size)
{
// принимаем в обратном порядке.. поэтому переворачиваем raw
raw_backorder = raw;
std::swap(raw.v[0], raw.v[1]);
}
~F2r() {}
~F2r() noexcept {}
F2mem raw_backorder;
};
......@@ -146,22 +146,22 @@ namespace VTypes
} F4mem;
// ------------------------------------------
// конструкторы на разные случаи...
F4()
F4() noexcept
{
memset(raw.v, 0, sizeof(raw.v));
}
F4( const float& f )
F4( const float& f ) noexcept
{
raw.val = f;
}
F4( const ModbusRTU::ModbusData* data, size_t size )
F4( const ModbusRTU::ModbusData* data, size_t size ) noexcept
{
for( size_t i = 0; i < wsize() && i < size; i++ )
raw.v[i] = data[i];
}
~F4() {}
~F4() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -201,27 +201,27 @@ namespace VTypes
} Bytemem;
// ------------------------------------------
// конструкторы на разные случаи...
Byte()
Byte() noexcept
{
raw.w = 0;
}
Byte( unsigned char b1, unsigned char b2 )
Byte( unsigned char b1, unsigned char b2 ) noexcept
{
raw.b[0] = b1;
raw.b[1] = b2;
}
Byte( const long& val )
Byte( const long& val ) noexcept
{
raw.w = val;
}
Byte( const ModbusRTU::ModbusData dat )
Byte( const ModbusRTU::ModbusData dat ) noexcept
{
raw.w = dat;
}
~Byte() {}
~Byte() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -257,19 +257,19 @@ namespace VTypes
// ------------------------------------------
// конструкторы на разные случаи...
Unsigned(): raw(0) {}
Unsigned() noexcept: raw(0) {}
Unsigned( const long& val )
Unsigned( const long& val ) noexcept
{
raw = val;
}
Unsigned( const ModbusRTU::ModbusData dat )
Unsigned( const ModbusRTU::ModbusData dat ) noexcept
{
raw = dat;
}
~Unsigned() {}
~Unsigned() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -296,19 +296,19 @@ namespace VTypes
// ------------------------------------------
// конструкторы на разные случаи...
Signed(): raw(0) {}
Signed() noexcept: raw(0) {}
Signed( const long& val )
Signed( const long& val ) noexcept
{
raw = val;
}
Signed( const ModbusRTU::ModbusData dat )
Signed( const ModbusRTU::ModbusData dat ) noexcept
{
raw = dat;
}
~Signed() {}
~Signed() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -343,22 +343,22 @@ namespace VTypes
} I2mem;
// ------------------------------------------
// конструкторы на разные случаи...
I2()
I2() noexcept
{
memset(raw.v, 0, sizeof(raw.v));
}
I2( int v )
I2( int v ) noexcept
{
raw.val = v;
}
I2( const ModbusRTU::ModbusData* data, size_t size )
I2( const ModbusRTU::ModbusData* data, size_t size ) noexcept
{
for( size_t i = 0; i < wsize() && i < size; i++ )
raw.v[i] = data[i];
}
~I2() {}
~I2() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -383,21 +383,22 @@ namespace VTypes
public I2
{
public:
I2r() {}
I2r() noexcept {}
I2r( const int v ): I2(v)
I2r( const int v ) noexcept: I2(v)
{
raw_backorder = raw;
std::swap(raw_backorder.v[0], raw_backorder.v[1]);
}
I2r( const ModbusRTU::ModbusData* data, size_t size ): I2(data, size)
I2r( const ModbusRTU::ModbusData* data, size_t size ) noexcept: I2(data, size)
{
// принимаем в обратном порядке.. поэтому переворачиваем raw
raw_backorder = raw;
std::swap(raw.v[0], raw.v[1]);
}
~I2r() {}
~I2r() noexcept {}
I2mem raw_backorder;
};
......@@ -416,22 +417,22 @@ namespace VTypes
} U2mem;
// ------------------------------------------
// конструкторы на разные случаи...
U2()
U2() noexcept
{
memset(raw.v, 0, sizeof(raw.v));
}
U2( unsigned int v )
U2( unsigned int v ) noexcept
{
raw.val = v;
}
U2( const ModbusRTU::ModbusData* data, size_t size )
U2( const ModbusRTU::ModbusData* data, size_t size ) noexcept
{
for( size_t i = 0; i < wsize() && i < size; i++ )
raw.v[i] = data[i];
}
~U2() {}
~U2() noexcept {}
// ------------------------------------------
/*! размер в словах */
static size_t wsize()
......@@ -456,14 +457,15 @@ namespace VTypes
public U2
{
public:
U2r() {}
U2r() noexcept {}
U2r( int v ): U2(v)
U2r( int v ) noexcept: U2(v)
{
raw_backorder = raw;
std::swap(raw_backorder.v[0], raw_backorder.v[1]);
}
U2r( const ModbusRTU::ModbusData* data, size_t size ): U2(data, size)
U2r( const ModbusRTU::ModbusData* data, size_t size ) noexcept: U2(data, size)
{
// принимаем в обратном порядке.. поэтому переворачиваем raw
raw_backorder = raw;
......
......@@ -27,7 +27,7 @@ namespace VTypes
return os << type2str(vt);
}
VType str2type( const std::string& s )
VType str2type( const std::string& s ) noexcept
{
if( s == "Byte" || s == "byte" )
return vtByte;
......@@ -62,7 +62,7 @@ namespace VTypes
return vtUnknown;
}
// -------------------------------------------------------------------------
string type2str( VType t )
string type2str( VType t ) noexcept
{
if( t == vtByte )
return "Byte";
......@@ -97,7 +97,7 @@ namespace VTypes
return "vtUnknown";
}
// -------------------------------------------------------------------------
int wsize( const VType t )
int wsize( const VType t ) noexcept
{
if( t == vtByte )
return Byte::wsize();
......
......@@ -23,7 +23,7 @@ class EvWatcher
// вызов своих ev::xxx.stop()
virtual void evfinish( const ev::loop_ref& ) {}
virtual std::string wname()
virtual std::string wname() const noexcept
{
return "";
}
......@@ -49,10 +49,10 @@ class CommonEventLoop
{
public:
CommonEventLoop();
CommonEventLoop() noexcept;
~CommonEventLoop();
bool evIsActive() const;
bool evIsActive() const noexcept;
/*! \return TRUE - если всё удалось. return актуален только для случая когда thread = true */
bool evrun( EvWatcher* w, bool thread = true );
......@@ -60,7 +60,7 @@ class CommonEventLoop
/*! \return TRUE - если это был последний EvWatcher и loop остановлен */
bool evstop( EvWatcher* w );
inline const ev::loop_ref evloop()
inline const ev::loop_ref evloop() noexcept
{
return loop;
}
......@@ -69,9 +69,9 @@ class CommonEventLoop
private:
void onStop();
void onPrepare();
void defaultLoop();
void onStop() noexcept;
void onPrepare() noexcept;
void defaultLoop() noexcept;
std::atomic_bool cancelled = { false };
std::atomic_bool isrunning = { false };
......
......@@ -92,20 +92,20 @@ struct Debug
/** Display the tags and descriptions of the current debug level
of ds
*/
static void showLevel(std::ostream& o, type level);
static void showLevel(std::ostream& o, type level) noexcept;
/** show all the possible tags that can be used for debugging */
static void showTags(std::ostream& o);
static void showTags(std::ostream& o) noexcept;
friend std::ostream& operator<<(std::ostream& os, Debug::type level );
friend std::ostream& operator<<(std::ostream& os, Debug::type level ) noexcept;
static std::string str( Debug::type level );
static std::string str( Debug::type level ) noexcept;
};
inline
void operator|=(Debug::type& d1, Debug::type d2)
void operator|=(Debug::type& d1, Debug::type d2) noexcept
{
d1 = static_cast<Debug::type>(d1 | d2);
}
......@@ -113,7 +113,7 @@ void operator|=(Debug::type& d1, Debug::type d2)
#include "DebugStream.h"
std::ostream& operator<<(std::ostream& o, Debug::type t);
std::ostream& operator<<(std::ostream& o, Debug::type t) noexcept;
//extern DebugStream ulog;
#endif
......@@ -105,25 +105,25 @@ class DebugStream : public std::ostream
StreamEvent_Signal signal_stream_event();
/// Sets the debug level to t.
void level(Debug::type t)
void level(Debug::type t) noexcept
{
dt = Debug::type(t & Debug::ANY);
}
/// Returns the current debug level.
Debug::type level() const
Debug::type level() const noexcept
{
return dt;
}
/// Adds t to the current debug level.
void addLevel(Debug::type t)
void addLevel(Debug::type t) noexcept
{
dt = Debug::type(dt | t);
}
/// Deletes t from the current debug level.
void delLevel(Debug::type t)
void delLevel(Debug::type t) noexcept
{
dt = Debug::type(dt & ~t);
}
......@@ -131,19 +131,19 @@ class DebugStream : public std::ostream
/// Sets the debugstreams' logfile to f.
virtual void logFile( const std::string& f, bool truncate = false );
inline std::string getLogFile() const
inline std::string getLogFile() const noexcept
{
return fname;
}
// имя лог файла можно установить отдельно, но не вклчать запись..
inline void setLogFile( const std::string& n )
inline void setLogFile( const std::string& n ) noexcept
{
fname = n;
}
// включена ли запись лог-файла
inline bool isOnLogFile() const
inline bool isOnLogFile() const noexcept
{
return isWriteLogFile;
}
......@@ -155,13 +155,13 @@ class DebugStream : public std::ostream
}
// отключить запись логфайла
inline void offLogFile()
inline void offLogFile() noexcept
{
logFile("");
}
/// Returns true if t is part of the current debug level.
inline bool debugging(Debug::type t = Debug::ANY) const
inline bool debugging(Debug::type t = Debug::ANY) const noexcept
{
return (dt & t);
}
......@@ -170,7 +170,7 @@ class DebugStream : public std::ostream
current debug level otherwise the real debug stream
is used.
*/
std::ostream& debug(Debug::type t = Debug::ANY);
std::ostream& debug(Debug::type t = Debug::ANY) noexcept;
// if (dt & t) return *this;
// return nullstream;
// }
......@@ -180,7 +180,7 @@ class DebugStream : public std::ostream
dbgstream[Debug::INFO] << "Info!\n";
Вывод осуществляется с датой и временем (если они не отключены)
*/
std::ostream& operator[](Debug::type t)
std::ostream& operator[](Debug::type t) noexcept
{
return debug(t);
}
......@@ -188,7 +188,7 @@ class DebugStream : public std::ostream
/**
Вывод продолжения логов (без даты и времени)
*/
inline std::ostream& to_end(Debug::type t)
inline std::ostream& to_end(Debug::type t) noexcept
{
return this->operator()(t);
}
......@@ -196,19 +196,19 @@ class DebugStream : public std::ostream
/**
Вывод продолжения логов (без даты и времени) "log()"
*/
std::ostream& operator()(Debug::type t);
std::ostream& operator()(Debug::type t) noexcept;
inline void showDateTime(bool s)
{
show_datetime = s;
}
inline void showLogType(bool s)
inline void showLogType(bool s) noexcept
{
show_logtype = s;
}
inline std::ostream& log(Debug::type l)
inline std::ostream& log(Debug::type l) noexcept
{
return this->operator[](l);
}
......@@ -219,14 +219,14 @@ class DebugStream : public std::ostream
// if( log.is_level1() ) - проверка включён ли лог.."
#define DMANIP(FNAME,LEVEL) \
inline std::ostream& FNAME( bool showdatetime=true ) \
inline std::ostream& FNAME( bool showdatetime=true ) noexcept \
{\
if( showdatetime )\
return operator[](Debug::LEVEL); \
return operator()(Debug::LEVEL); \
} \
\
inline bool is_##FNAME() const \
inline bool is_##FNAME() const noexcept\
{ return debugging(Debug::LEVEL); }
DMANIP(level1, LEVEL1)
......@@ -247,26 +247,26 @@ class DebugStream : public std::ostream
DMANIP(any, ANY)
#undef DMANIP
std::ostream& printDate(Debug::type t, char brk = '/');
std::ostream& printTime(Debug::type t, char brk = ':');
std::ostream& printDateTime(Debug::type t);
std::ostream& printDate(Debug::type t, char brk = '/') noexcept;
std::ostream& printTime(Debug::type t, char brk = ':') noexcept;
std::ostream& printDateTime(Debug::type t) noexcept;
std::ostream& pos(int x, int y);
std::ostream& pos(int x, int y) noexcept;
const DebugStream& operator=(const DebugStream& r);
inline void setLogName( const std::string& n )
inline void setLogName( const std::string& n ) noexcept
{
logname = n;
}
inline std::string getLogName() const
inline std::string getLogName() const noexcept
{
return logname;
}
protected:
void sbuf_overflow( const std::string& s );
void sbuf_overflow( const std::string& s ) noexcept;
// private:
/// The current debug level
......
......@@ -29,12 +29,12 @@ class DelayTimer
public:
DelayTimer(){}
DelayTimer( timeout_t on_msec, timeout_t off_msec ):
DelayTimer( timeout_t on_msec, timeout_t off_msec ) noexcept:
onDelay(on_msec), offDelay(off_msec){}
~DelayTimer() {}
~DelayTimer() noexcept {}
inline void set( timeout_t on_msec, timeout_t off_msec )
inline void set( timeout_t on_msec, timeout_t off_msec ) noexcept
{
onDelay = on_msec;
offDelay = off_msec;
......@@ -44,7 +44,7 @@ class DelayTimer
}
// запустить часы (заново)
inline void reset()
inline void reset() noexcept
{
pt.reset();
waiting_on = false;
......@@ -52,7 +52,7 @@ class DelayTimer
state = false;
}
inline bool check( bool st )
inline bool check( bool st ) noexcept
{
prevState = st;
......@@ -124,21 +124,21 @@ class DelayTimer
return state;
}
inline bool get()
inline bool get() noexcept
{
return check(prevState);
}
inline timeout_t getOnDelay() const
inline timeout_t getOnDelay() const noexcept
{
return onDelay;
}
inline timeout_t getOffDelay() const
inline timeout_t getOffDelay() const noexcept
{
return offDelay;
}
inline timeout_t getCurrent() const
inline timeout_t getCurrent() const noexcept
{
return pt.getCurrent();
}
......
......@@ -18,7 +18,7 @@ class EventLoopServer
EventLoopServer();
virtual ~EventLoopServer();
bool evIsActive() const;
bool evIsActive() const noexcept;
protected:
// действия при завершении
......@@ -37,8 +37,8 @@ class EventLoopServer
private:
void onStop();
void defaultLoop();
void onStop() noexcept;
void defaultLoop() noexcept;
std::atomic_bool cancelled = { false };
std::atomic_bool isrunning = { false };
......
......@@ -46,8 +46,8 @@ namespace UniSetTypes
{
public:
Exception(const std::string& txt): text(txt.c_str()) {}
Exception(): text("Exception") {}
Exception(const std::string& txt) noexcept: text(txt.c_str()) {}
Exception() noexcept: text("Exception") {}
virtual ~Exception() noexcept(true) {}
friend std::ostream& operator<<(std::ostream& os, const Exception& ex )
......@@ -68,8 +68,8 @@ namespace UniSetTypes
class OutOfRange: public Exception
{
public:
OutOfRange(): Exception("OutOfRange") {}
OutOfRange(const std::string& err): Exception(err) {}
OutOfRange() noexcept: Exception("OutOfRange") {}
OutOfRange(const std::string& err) noexcept: Exception(err) {}
};
/*! Исключение, вырабатываемое функциями репозитория объектов.
......@@ -78,10 +78,10 @@ namespace UniSetTypes
class ORepFailed: public Exception
{
public:
ORepFailed(): Exception("ORepFailed") {}
ORepFailed() noexcept: Exception("ORepFailed") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ORepFailed(const std::string& err): Exception(err) {}
ORepFailed(const std::string& err) noexcept: Exception(err) {}
};
......@@ -89,20 +89,20 @@ namespace UniSetTypes
class SystemError: public Exception
{
public:
SystemError(): Exception("SystemError") {}
SystemError() noexcept: Exception("SystemError") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
SystemError(const std::string& err): Exception(err) {}
SystemError(const std::string& err) noexcept: Exception(err) {}
};
/*! Ошибка соединения */
class CommFailed: public Exception
{
public:
CommFailed(): Exception("CommFailed") {}
CommFailed() noexcept: Exception("CommFailed") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
CommFailed(const std::string& err): Exception(err) {}
CommFailed(const std::string& err) noexcept: Exception(err) {}
};
......@@ -113,10 +113,10 @@ namespace UniSetTypes
class TimeOut: public CommFailed
{
public:
TimeOut(): CommFailed("TimeOut") {}
TimeOut() noexcept: CommFailed("TimeOut") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
TimeOut(const std::string& err): CommFailed(err) {}
TimeOut(const std::string& err) noexcept: CommFailed(err) {}
};
......@@ -124,16 +124,16 @@ namespace UniSetTypes
class ResolveNameError: public ORepFailed
{
public:
ResolveNameError(): ORepFailed("ResolveNameError") {}
ResolveNameError(const std::string& err): ORepFailed(err) {}
ResolveNameError() noexcept: ORepFailed("ResolveNameError") {}
ResolveNameError(const std::string& err) noexcept: ORepFailed(err) {}
};
class NSResolveError: public ORepFailed
{
public:
NSResolveError(): ORepFailed("NSResolveError") {}
NSResolveError(const std::string& err): ORepFailed(err) {}
NSResolveError() noexcept: ORepFailed("NSResolveError") {}
NSResolveError(const std::string& err) noexcept: ORepFailed(err) {}
};
......@@ -144,10 +144,10 @@ namespace UniSetTypes
class ObjectNameAlready: public ResolveNameError
{
public:
ObjectNameAlready(): ResolveNameError("ObjectNameAlready") {}
ObjectNameAlready() noexcept: ResolveNameError("ObjectNameAlready") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ObjectNameAlready(const std::string& err): ResolveNameError(err) {}
ObjectNameAlready(const std::string& err) noexcept: ResolveNameError(err) {}
};
/*!
......@@ -157,10 +157,10 @@ namespace UniSetTypes
class IOBadParam: public Exception
{
public:
IOBadParam(): Exception("IOBadParam") {}
IOBadParam() noexcept: Exception("IOBadParam") {}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
IOBadParam(const std::string& err): Exception(err) {}
IOBadParam(const std::string& err) noexcept: Exception(err) {}
};
/*!
......@@ -170,15 +170,15 @@ namespace UniSetTypes
class InvalidObjectName: public ResolveNameError
{
public:
InvalidObjectName(): ResolveNameError("InvalidObjectName") {}
InvalidObjectName(const std::string& err): ResolveNameError(err) {}
InvalidObjectName() noexcept: ResolveNameError("InvalidObjectName") {}
InvalidObjectName(const std::string& err) noexcept: ResolveNameError(err) {}
};
class NameNotFound: public ResolveNameError
{
public:
NameNotFound(): ResolveNameError("NameNotFound") {}
NameNotFound(const std::string& err): ResolveNameError(err) {}
NameNotFound() noexcept: ResolveNameError("NameNotFound") {}
NameNotFound(const std::string& err) noexcept: ResolveNameError(err) {}
};
//@}
......
......@@ -59,11 +59,11 @@
class HourGlass
{
public:
HourGlass() {}
~HourGlass() {}
HourGlass() noexcept {}
~HourGlass() noexcept {}
// запустить часы (заново)
inline void run( timeout_t msec )
inline void run( timeout_t msec ) noexcept
{
t.setTiming(msec);
_state = true;
......@@ -71,13 +71,13 @@ class HourGlass
_size = msec;
}
inline void reset()
inline void reset() noexcept
{
run(_size);
}
// "ёмкость" песочных часов..
inline timeout_t duration() const
inline timeout_t duration() const noexcept
{
return _size;
}
......@@ -85,7 +85,7 @@ class HourGlass
// true - засечь время
// false - перевернуть часы (обратный ход)
// возвращает аргумент (т.е. идёт ли отсчёт времени)
inline bool rotate( bool st )
inline bool rotate( bool st ) noexcept
{
if( st == _state )
return st;
......@@ -123,19 +123,19 @@ class HourGlass
}
// получить прошедшее время
inline timeout_t current() const
inline timeout_t current() const noexcept
{
return t.getCurrent();
}
// получить заданное время
inline timeout_t interval() const
inline timeout_t interval() const noexcept
{
return t.getInterval();
}
// проверить наступление
inline bool check() const
inline bool check() const noexcept
{
// пока часы не "стоят"
// всегда false
......@@ -145,19 +145,19 @@ class HourGlass
return t.checkTime();
}
inline bool enabled() const
inline bool enabled() const noexcept
{
return _state;
}
// текущее "насыпавшееся" количество "песка" (прошедшее время)
inline timeout_t amount() const
inline timeout_t amount() const noexcept
{
return ( _size - remain() );
}
// остаток песка (времени) (оставшееся время)
inline timeout_t remain() const
inline timeout_t remain() const noexcept
{
timeout_t c = t.getCurrent();
......
......@@ -87,20 +87,20 @@ class LogServer:
{
public:
LogServer( std::shared_ptr<DebugStream> log );
LogServer( std::shared_ptr<LogAgregator> log );
virtual ~LogServer();
LogServer( std::shared_ptr<DebugStream> log ) noexcept;
LogServer( std::shared_ptr<LogAgregator> log ) noexcept;
virtual ~LogServer() noexcept;
inline void setCmdTimeout( timeout_t msec )
inline void setCmdTimeout( timeout_t msec ) noexcept
{
cmdTimeout = msec;
}
inline void setSessionLog( Debug::type t )
inline void setSessionLog( Debug::type t ) noexcept
{
sessLogLevel = t;
}
inline void setMaxSessionCount( int num )
inline void setMaxSessionCount( int num ) noexcept
{
sessMaxCount = num;
}
......@@ -108,7 +108,7 @@ class LogServer:
void run( const std::string& addr, Poco::UInt16 port, bool thread = true );
void terminate();
inline bool isRunning()
inline bool isRunning() const noexcept
{
return isrunning;
}
......@@ -120,11 +120,11 @@ class LogServer:
std::string getShortInfo();
protected:
LogServer();
LogServer() noexcept;
virtual void evprepare( const ev::loop_ref& loop ) override;
virtual void evfinish( const ev::loop_ref& loop ) override;
virtual std::string wname()
virtual std::string wname() const noexcept override
{
return myname;
}
......
......@@ -37,7 +37,7 @@ class LogSession
~LogSession();
typedef sigc::slot<void, LogSession*> FinalSlot;
void connectFinalSession( FinalSlot sl );
void connectFinalSession( FinalSlot sl ) noexcept;
// сигнал о приходе команды: std::string func( LogSession*, command, logname );
// \return какую-то информацию, которая будет послана client-у. Если return.empty(), то ничего послано не будет.
......@@ -45,52 +45,52 @@ class LogSession
LogSessionCommand_Signal signal_logsession_command();
// прервать работу
void cancel();
void cancel() noexcept;
inline std::string getClientAddress() const
inline std::string getClientAddress() const noexcept
{
return caddr;
}
inline void setSessionLogLevel( Debug::type t )
inline void setSessionLogLevel( Debug::type t ) noexcept
{
mylog.level(t);
}
inline void addSessionLogLevel( Debug::type t )
inline void addSessionLogLevel( Debug::type t ) noexcept
{
mylog.addLevel(t);
}
inline void delSessionLogLevel( Debug::type t )
inline void delSessionLogLevel( Debug::type t ) noexcept
{
mylog.delLevel(t);
}
//! Установить размер буфера для сообщений (количество записей. Не в байтах!!)
void setMaxBufSize( size_t num );
size_t getMaxBufSize() const;
size_t getMaxBufSize() const noexcept;
// запуск обработки входящих запросов
void run( const ev::loop_ref& loop );
void run( const ev::loop_ref& loop ) noexcept;
void terminate();
bool isAcive() const;
bool isAcive() const noexcept;
std::string getShortInfo();
std::string getShortInfo() noexcept;
protected:
// LogSession( ost::TCPSocket& server );
void event( ev::async& watcher, int revents );
void callback( ev::io& watcher, int revents );
void readEvent( ev::io& watcher );
void event( ev::async& watcher, int revents ) noexcept;
void callback( ev::io& watcher, int revents ) noexcept;
void readEvent( ev::io& watcher ) noexcept;
void writeEvent( ev::io& watcher );
size_t readData( unsigned char* buf, int len );
void cmdProcessing( const std::string& cmdLogName, const LogServerTypes::lsMessage& msg );
void onCmdTimeout( ev::timer& watcher, int revents );
void onCheckConnectionTimer( ev::timer& watcher, int revents );
void final();
void onCmdTimeout( ev::timer& watcher, int revents ) noexcept;
void onCheckConnectionTimer( ev::timer& watcher, int revents ) noexcept;
void final() noexcept;
void logOnEvent( const std::string& s );
void logOnEvent( const std::string& s ) noexcept;
timeout_t cmdTimeout = { 2000 };
float checkConnectionTime = { 10. }; // время на проверку живости соединения..(сек)
......
......@@ -63,21 +63,21 @@ class MQAtomic
MQAtomic( size_t qsize = 2000 );
/*! поместить сообщение в очередь */
void push( const VoidMessagePtr& msg );
bool push( const VoidMessagePtr& msg ) noexcept;
/*! Извлечь сообщение из очереди
* \return не валидный shatred_ptr если сообщений нет
*/
VoidMessagePtr top();
VoidMessagePtr top() noexcept;
size_t size() const;
bool empty() const;
size_t size() const noexcept;
bool empty() const noexcept;
// ----- Настройки -----
// неявно подразумевается, что всё настривается до первого использования
// ----------------------
void setMaxSizeOfMessageQueue( size_t s );
size_t getMaxSizeOfMessageQueue() const;
size_t getMaxSizeOfMessageQueue() const noexcept;
/*! Стратегия при переполнении */
enum LostStrategy
......@@ -86,17 +86,17 @@ class MQAtomic
lostNewData
};
void setLostStrategy( LostStrategy s );
void setLostStrategy( LostStrategy s ) noexcept;
// ---- Статистика ----
/*! максимальное количество которое было в очереди сообщений */
inline size_t getMaxQueueMessages() const
inline size_t getMaxQueueMessages() const noexcept
{
return stMaxQueueMessages;
}
/*! сколько раз очередь переполнялась */
inline size_t getCountOfLostMessages() const
inline size_t getCountOfLostMessages() const noexcept
{
return stCountOfLostMessages;
}
......@@ -108,8 +108,8 @@ class MQAtomic
// для возможности тестирования переполнения
// специально делается такая функция
void set_wpos( unsigned long pos );
void set_rpos( unsigned long pos );
void set_wpos( unsigned long pos ) noexcept;
void set_rpos( unsigned long pos ) noexcept;
private:
......
......@@ -47,7 +47,7 @@ class MQMutex
/*! Извлечь сообщение из очереди
* \return не валидный shatred_ptr(nullptr) если сообщений нет
*/
VoidMessagePtr top();
VoidMessagePtr top() noexcept;
size_t size();
bool empty();
......@@ -55,8 +55,8 @@ class MQMutex
// ----- Настройки -----
// неявно подразумевается, что всё настраивается до первого использования
// ----------------------
void setMaxSizeOfMessageQueue( size_t s );
size_t getMaxSizeOfMessageQueue() const;
void setMaxSizeOfMessageQueue( size_t s ) noexcept;
size_t getMaxSizeOfMessageQueue() const noexcept;
/*! Стратегия при переполнении */
enum LostStrategy
......@@ -65,17 +65,17 @@ class MQMutex
lostNewData
};
void setLostStrategy( LostStrategy s );
void setLostStrategy( LostStrategy s ) noexcept;
// ---- Статистика ----
/*! максимальное количество которое было в очереди сообщений */
inline size_t getMaxQueueMessages() const
inline size_t getMaxQueueMessages() const noexcept
{
return stMaxQueueMessages;
}
/*! количество потерянных сообщений */
inline size_t getCountOfLostMessages() const
inline size_t getCountOfLostMessages() const noexcept
{
return stCountOfLostMessages;
}
......
......@@ -58,19 +58,19 @@ namespace UniSetTypes
ObjectId consumer = { UniSetTypes::DefaultObjectId }; // кому
struct timespec tm = { 0, 0 };
Message( Message&& ) = default;
Message& operator=(Message&& ) = default;
Message( const Message& ) = default;
Message& operator=(const Message& ) = default;
Message( Message&& ) noexcept = default;
Message& operator=(Message&& ) noexcept = default;
Message( const Message& ) noexcept = default;
Message& operator=(const Message& ) noexcept = default;
Message();
Message() noexcept;
// для оптимизации, делаем конструктор который не будет инициализировать свойства класса
// это необходимо для VoidMessage, который конструируется при помощи memcpy
explicit Message( int dummy_init ) {}
explicit Message( int dummy_init ) noexcept {}
template<class In>
static const TransportMessage transport(const In& msg)
static const TransportMessage transport(const In& msg) noexcept
{
TransportMessage tmsg;
assert(sizeof(UniSetTypes::RawDataOfTransportMessage) >= sizeof(msg));
......@@ -87,17 +87,17 @@ namespace UniSetTypes
{
public:
VoidMessage( VoidMessage&& ) = default;
VoidMessage& operator=(VoidMessage&& ) = default;
VoidMessage( const VoidMessage& ) = default;
VoidMessage& operator=( const VoidMessage& ) = default;
VoidMessage( VoidMessage&& ) noexcept = default;
VoidMessage& operator=(VoidMessage&& ) noexcept = default;
VoidMessage( const VoidMessage& ) noexcept = default;
VoidMessage& operator=( const VoidMessage& ) noexcept = default;
// для оптимизации, делаем конструктор который не будет инициализировать свойства класса
// это необходимо для VoidMessage, который конструируется при помощи memcpy
VoidMessage( int dummy ): Message(dummy) {}
VoidMessage( int dummy ) noexcept : Message(dummy) {}
VoidMessage( const TransportMessage& tm );
VoidMessage();
VoidMessage( const TransportMessage& tm ) noexcept;
VoidMessage() noexcept;
inline bool operator < ( const VoidMessage& msg ) const
{
if( priority != msg.priority )
......@@ -109,7 +109,7 @@ namespace UniSetTypes
return tm.tv_nsec >= msg.tm.tv_nsec;
}
inline TransportMessage transport_msg() const
inline TransportMessage transport_msg() const noexcept
{
return transport(*this);
}
......@@ -137,25 +137,25 @@ namespace UniSetTypes
bool threshold = { false }; /*!< TRUE - сработал порог, FALSE - порог отключился */
UniSetTypes::ThresholdId tid = { UniSetTypes::DefaultThresholdId };
SensorMessage( SensorMessage&& m) = default;
SensorMessage& operator=(SensorMessage&& m) = default;
SensorMessage( const SensorMessage& ) = default;
SensorMessage& operator=( const SensorMessage& ) = default;
SensorMessage( SensorMessage&& m) noexcept = default;
SensorMessage& operator=(SensorMessage&& m) noexcept = default;
SensorMessage( const SensorMessage& ) noexcept = default;
SensorMessage& operator=( const SensorMessage& ) noexcept = default;
SensorMessage();
SensorMessage() noexcept;
SensorMessage(ObjectId id, long value, const IOController_i::CalibrateInfo& ci = IOController_i::CalibrateInfo(),
Priority priority = Message::Medium,
UniversalIO::IOType st = UniversalIO::AI,
ObjectId consumer = UniSetTypes::DefaultObjectId);
ObjectId consumer = UniSetTypes::DefaultObjectId) noexcept;
// специальный конструктор, для оптимизации
// он не инициализирует поля по умолчанию
// и за инициализацию значений отвечает "пользователь"
// например см. IONotifyController::localSetValue()
explicit SensorMessage( int dummy );
explicit SensorMessage( int dummy ) noexcept;
SensorMessage(const VoidMessage* msg);
inline TransportMessage transport_msg() const
SensorMessage(const VoidMessage* msg) noexcept;
inline TransportMessage transport_msg() const noexcept
{
return transport(*this);
}
......@@ -183,17 +183,17 @@ namespace UniSetTypes
TheLastFieldOfCommand
};
SystemMessage( SystemMessage&& ) = default;
SystemMessage& operator=(SystemMessage&& ) = default;
SystemMessage( const SystemMessage& ) = default;
SystemMessage& operator=( const SystemMessage& ) = default;
SystemMessage( SystemMessage&& ) noexcept = default;
SystemMessage& operator=(SystemMessage&& ) noexcept = default;
SystemMessage( const SystemMessage& ) noexcept = default;
SystemMessage& operator=( const SystemMessage& ) noexcept = default;
SystemMessage();
SystemMessage() noexcept;
SystemMessage(Command command, Priority priority = Message::High,
ObjectId consumer = UniSetTypes::DefaultObjectId);
SystemMessage(const VoidMessage* msg);
ObjectId consumer = UniSetTypes::DefaultObjectId) noexcept;
SystemMessage(const VoidMessage* msg) noexcept;
inline TransportMessage transport_msg() const
inline TransportMessage transport_msg() const noexcept
{
return transport(*this);
}
......@@ -209,16 +209,16 @@ namespace UniSetTypes
class TimerMessage : public Message
{
public:
TimerMessage( TimerMessage&& ) = default;
TimerMessage& operator=(TimerMessage&& ) = default;
TimerMessage( const TimerMessage& ) = default;
TimerMessage& operator=( const TimerMessage& ) = default;
TimerMessage( TimerMessage&& ) noexcept = default;
TimerMessage& operator=(TimerMessage&& ) noexcept = default;
TimerMessage( const TimerMessage& ) noexcept = default;
TimerMessage& operator=( const TimerMessage& ) noexcept = default;
TimerMessage();
TimerMessage(UniSetTypes::TimerId id, Priority prior = Message::High,
ObjectId cons = UniSetTypes::DefaultObjectId);
TimerMessage(const VoidMessage* msg);
inline TransportMessage transport_msg() const
TimerMessage(const VoidMessage* msg) noexcept ;
inline TransportMessage transport_msg() const noexcept
{
return transport(*this);
}
......@@ -233,23 +233,23 @@ namespace UniSetTypes
{
public:
inline TransportMessage transport_msg() const
inline TransportMessage transport_msg() const noexcept
{
return transport(*this);
}
ConfirmMessage( const VoidMessage* msg );
ConfirmMessage( const VoidMessage* msg ) noexcept;
ConfirmMessage(ObjectId in_sensor_id,
const double& in_sensor_value,
const timespec& in_sensor_time,
const timespec& in_confirm_time,
Priority in_priority = Message::Medium);
Priority in_priority = Message::Medium) noexcept;
ConfirmMessage( ConfirmMessage&& ) = default;
ConfirmMessage& operator=(ConfirmMessage&& ) = default;
ConfirmMessage( const ConfirmMessage& ) = default;
ConfirmMessage& operator=( const ConfirmMessage& ) = default;
ConfirmMessage( ConfirmMessage&& ) noexcept = default;
ConfirmMessage& operator=(ConfirmMessage&& ) noexcept = default;
ConfirmMessage( const ConfirmMessage& ) noexcept = default;
ConfirmMessage& operator=( const ConfirmMessage& ) noexcept = default;
ObjectId sensor_id; /* ID датчика (события) */
double sensor_value; /* значение датчика (события) */
......@@ -266,7 +266,7 @@ namespace UniSetTypes
bool forward;
protected:
ConfirmMessage();
ConfirmMessage() noexcept;
};
}
......
......@@ -52,7 +52,7 @@ class NCRestorer
SInfo& operator=(SInfo&& ) = default;
SInfo( IOController_i::SensorInfo& si, UniversalIO::IOType& t,
UniSetTypes::Message::Message::Priority& p, long& def )
UniSetTypes::Message::Message::Priority& p, long& def ) noexcept
{
this->si = si;
this->type = t;
......@@ -60,7 +60,7 @@ class NCRestorer
this->default_val = def;
}
SInfo()
SInfo() noexcept
{
this->type = UniversalIO::DI;
this->priority = UniSetTypes::Message::Medium;
......@@ -88,16 +88,16 @@ class NCRestorer
ic->ioRegistration(inf, force);
}
static inline IOController::IOStateList::iterator ioFind( IONotifyController* ic, UniSetTypes::ObjectId k )
static inline IOController::IOStateList::iterator ioFind( IONotifyController* ic, UniSetTypes::ObjectId k ) noexcept
{
return ic->myiofind(k);
}
static inline IOController::IOStateList::iterator ioEnd( IONotifyController* ic )
static inline IOController::IOStateList::iterator ioEnd( IONotifyController* ic ) noexcept
{
return ic->myioEnd();
}
static inline IOController::IOStateList::iterator ioBegin( IONotifyController* ic )
static inline IOController::IOStateList::iterator ioBegin( IONotifyController* ic ) noexcept
{
return ic->myioBegin();
}
......@@ -135,7 +135,7 @@ class NCRestorer_XML:
void setThresholdsFilter( const std::string& filterField, const std::string& filterValue = "" );
bool setFileName( const std::string& file, bool create );
inline std::string getFileName() const
inline std::string getFileName() const noexcept
{
return fname;
}
......
......@@ -34,34 +34,43 @@ namespace UniSetTypes
virtual ~ObjectIndex() {};
// info
virtual const ObjectInfo* getObjectInfo( const UniSetTypes::ObjectId ) const = 0;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const = 0;
// \return nullptr if not found
virtual const ObjectInfo* getObjectInfo( const UniSetTypes::ObjectId ) const noexcept = 0;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept = 0;
static std::string getBaseName( const std::string& fname );
static std::string getBaseName( const std::string& fname ) noexcept;
// object id
virtual ObjectId getIdByName(const std::string& name) const = 0;
virtual std::string getNameById( const UniSetTypes::ObjectId id ) const;
//! \return UniSetTypes::DefaultObjectId if not found
virtual ObjectId getIdByName(const std::string& name) const noexcept = 0;
//! \return "" if not found
virtual std::string getNameById( const UniSetTypes::ObjectId id ) const noexcept;
// node
inline std::string getNodeName( const UniSetTypes::ObjectId id ) const
//! \return "" if not found
inline std::string getNodeName( const UniSetTypes::ObjectId id ) const noexcept
{
return getNameById(id);
}
inline ObjectId getNodeId( const std::string& name ) const
//! \return UniSetTypes::DefaultObjectId if not found
inline ObjectId getNodeId( const std::string& name ) const noexcept
{
return getIdByName(name);
}
// src name
virtual std::string getMapName( const UniSetTypes::ObjectId id ) const = 0;
virtual std::string getTextName( const UniSetTypes::ObjectId id ) const = 0;
//! \return "" if not found
virtual std::string getMapName( const UniSetTypes::ObjectId id ) const noexcept = 0;
//! \return "" if not found
virtual std::string getTextName( const UniSetTypes::ObjectId id ) const noexcept = 0;
//
virtual std::ostream& printMap(std::ostream& os) const = 0;
virtual std::ostream& printMap(std::ostream& os) const noexcept = 0;
void initLocalNode( const UniSetTypes::ObjectId nodeid );
void initLocalNode( const UniSetTypes::ObjectId nodeid ) noexcept;
protected:
std::string nmLocalNode = {""}; // поле для оптимизации получения LocalNode
......
......@@ -42,13 +42,13 @@ namespace UniSetTypes
ObjectIndex_Array(const ObjectInfo* objectInfo);
virtual ~ObjectIndex_Array();
virtual const ObjectInfo* getObjectInfo( const ObjectId ) const override;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const override;
virtual ObjectId getIdByName( const std::string& name ) const override;
virtual std::string getMapName( const ObjectId id ) const override;
virtual std::string getTextName( const ObjectId id ) const override;
virtual const ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override;
virtual const ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override;
virtual ObjectId getIdByName( const std::string& name ) const noexcept override;
virtual std::string getMapName( const ObjectId id ) const noexcept override;
virtual std::string getTextName( const ObjectId id ) const noexcept override;
virtual std::ostream& printMap(std::ostream& os) const override;
virtual std::ostream& printMap(std::ostream& os) const noexcept override;
friend std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi );
private:
......
......@@ -40,19 +40,19 @@ namespace UniSetTypes
ObjectIndex_XML( const std::shared_ptr<UniXML>& xml, size_t minSize = 1000 );
virtual ~ObjectIndex_XML();
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const ObjectId ) const override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const std::string& name ) const override;
virtual ObjectId getIdByName( const std::string& name ) const override;
virtual std::string getMapName( const ObjectId id ) const override;
virtual std::string getTextName( const ObjectId id ) const override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const ObjectId ) const noexcept override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override;
virtual ObjectId getIdByName( const std::string& name ) const noexcept override;
virtual std::string getMapName( const ObjectId id ) const noexcept override;
virtual std::string getTextName( const ObjectId id ) const noexcept override;
virtual std::ostream& printMap(std::ostream& os) const override;
virtual std::ostream& printMap(std::ostream& os) const noexcept override;
friend std::ostream& operator<<(std::ostream& os, ObjectIndex_XML& oi );
protected:
void build( const std::shared_ptr<UniXML>& xml );
unsigned int read_section( const std::shared_ptr<UniXML>& xml, const std::string& sec, unsigned int ind );
unsigned int read_nodes( const std::shared_ptr<UniXML>& xml, const std::string& sec, unsigned int ind );
size_t read_section(const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind );
size_t read_nodes( const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind );
private:
typedef std::unordered_map<std::string, ObjectId> MapObjectKey;
......
......@@ -30,13 +30,13 @@ class ObjectIndex_idXML:
ObjectIndex_idXML( const std::shared_ptr<UniXML>& xml );
virtual ~ObjectIndex_idXML();
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const UniSetTypes::ObjectId ) const override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const std::string& name ) const override;
virtual UniSetTypes::ObjectId getIdByName( const std::string& name ) const override;
virtual std::string getMapName( const UniSetTypes::ObjectId id ) const override;
virtual std::string getTextName( const UniSetTypes::ObjectId id ) const override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const UniSetTypes::ObjectId ) const noexcept override;
virtual const UniSetTypes::ObjectInfo* getObjectInfo( const std::string& name ) const noexcept override;
virtual UniSetTypes::ObjectId getIdByName( const std::string& name ) const noexcept override;
virtual std::string getMapName( const UniSetTypes::ObjectId id ) const noexcept override;
virtual std::string getTextName( const UniSetTypes::ObjectId id ) const noexcept override;
virtual std::ostream& printMap( std::ostream& os ) const override;
virtual std::ostream& printMap( std::ostream& os ) const noexcept override;
friend std::ostream& operator<<(std::ostream& os, ObjectIndex_idXML& oi );
protected:
......
......@@ -42,23 +42,23 @@ class UniSetTimer
public:
virtual ~UniSetTimer() {};
virtual bool checkTime() const = 0; /*!< проверка наступления заданного времени */
virtual timeout_t setTiming( timeout_t msec ) = 0; /*!< установить таймер и запустить */
virtual void reset() = 0; /*!< перезапустить таймер */
virtual bool checkTime() const noexcept = 0; /*!< проверка наступления заданного времени */
virtual timeout_t setTiming( timeout_t msec ) noexcept = 0; /*!< установить таймер и запустить */
virtual void reset() noexcept = 0; /*!< перезапустить таймер */
virtual timeout_t getCurrent() const = 0; /*!< получить текущее значение таймера */
virtual timeout_t getInterval() const = 0; /*!< получить интервал, на который установлен таймер, в мс */
virtual timeout_t getCurrent() const noexcept = 0; /*!< получить текущее значение таймера */
virtual timeout_t getInterval() const noexcept = 0; /*!< получить интервал, на который установлен таймер, в мс */
timeout_t getLeft( timeout_t timeout ) const; /*!< получить время, которое остается от timeout после прошествия времени getCurrent() */
timeout_t getLeft( timeout_t timeout ) const noexcept; /*!< получить время, которое остается от timeout после прошествия времени getCurrent() */
// объявлены не чисто виртуальными т.к.
// некоторые классы могут не иметь подобных
// свойств.
virtual bool wait(timeout_t timeMS); /*!< заснуть ожидая наступления времени */
virtual void terminate() {} /*!< прервать работу таймера */
virtual void terminate(){} /*!< прервать работу таймера */
/*! завершить работу таймера */
virtual void stop();
virtual void stop() noexcept;
/*! Время засыпания, до момента пока не будет вызвана функция прерывания
* terminate() или stop()
......@@ -66,8 +66,8 @@ class UniSetTimer
static const timeout_t WaitUpTime = std::numeric_limits<timeout_t>::max();
// преобразование в Poco::Timespan с учётом WaitUpTime
static const Poco::Timespan millisecToPoco( const timeout_t msec );
static const Poco::Timespan microsecToPoco( const timeout_t usec );
static const Poco::Timespan millisecToPoco( const timeout_t msec ) noexcept;
static const Poco::Timespan microsecToPoco( const timeout_t usec ) noexcept;
/*! Минимальное время срабатывания. Задается в мсек.
* Используется в LT_Object и CallbackTimer
......@@ -88,22 +88,22 @@ class PassiveTimer:
public UniSetTimer
{
public:
PassiveTimer();
PassiveTimer( timeout_t msec ); /*!< установить таймер */
virtual ~PassiveTimer();
PassiveTimer() noexcept;
PassiveTimer( timeout_t msec ) noexcept; /*!< установить таймер */
virtual ~PassiveTimer() noexcept;
virtual bool checkTime() const; /*!< проверка наступления заданного времени */
virtual timeout_t setTiming( timeout_t msec ); /*!< установить таймер и запустить. timeMS = 0 вызовет немедленное срабатывание */
virtual void reset(); /*!< перезапустить таймер */
virtual bool checkTime() const noexcept override; /*!< проверка наступления заданного времени */
virtual timeout_t setTiming( timeout_t msec ) noexcept override; /*!< установить таймер и запустить. timeMS = 0 вызовет немедленное срабатывание */
virtual void reset() noexcept; /*!< перезапустить таймер */
virtual timeout_t getCurrent() const override; /*!< получить текущее значение таймера, в мс */
virtual timeout_t getCurrent() const noexcept override; /*!< получить текущее значение таймера, в мс */
/*! получить интервал, на который установлен таймер, в мс
* \return msec или 0 если интервал равен WaitUpTime
*/
virtual timeout_t getInterval() const override;
virtual timeout_t getInterval() const noexcept override;
virtual void terminate(); /*!< прервать работу таймера */
virtual void terminate() noexcept; /*!< прервать работу таймера */
protected:
timeout_t t_msec = { 0 }; /*!< интервал таймера, в милисекундах (для "пользователей") */
......@@ -134,11 +134,11 @@ class PassiveCondTimer:
{
public:
PassiveCondTimer();
virtual ~PassiveCondTimer();
PassiveCondTimer() noexcept;
virtual ~PassiveCondTimer() noexcept;
virtual bool wait(timeout_t t_msec); /*!< блокировать вызывающий поток на заданное время */
virtual void terminate(); /*!< прервать работу таймера */
virtual bool wait(timeout_t t_msec) noexcept override; /*!< блокировать вызывающий поток на заданное время */
virtual void terminate() noexcept override; /*!< прервать работу таймера */
protected:
......
......@@ -33,12 +33,12 @@
class Pulse
{
public:
Pulse() {}
~Pulse() {}
Pulse() noexcept {}
~Pulse() noexcept {}
// t1_msec - интервал "вкл"
// t0_msec - интерфал "откл"
inline void run( timeout_t _t1_msec, timeout_t _t0_msec )
inline void run( timeout_t _t1_msec, timeout_t _t0_msec ) noexcept
{
t1_msec = _t1_msec;
t0_msec = _t0_msec;
......@@ -47,18 +47,18 @@ class Pulse
set(true);
}
inline void set_next( timeout_t _t1_msec, timeout_t _t0_msec )
inline void set_next( timeout_t _t1_msec, timeout_t _t0_msec ) noexcept
{
t1_msec = _t1_msec;
t0_msec = _t0_msec;
}
inline void reset()
inline void reset() noexcept
{
set(true);
}
inline bool step()
inline bool step() noexcept
{
if( !isOn )
{
......@@ -81,12 +81,12 @@ class Pulse
return ostate;
}
inline bool out()
inline bool out() noexcept
{
return step(); // ostate;
}
inline void set( bool state )
inline void set( bool state ) noexcept
{
isOn = state;
......@@ -102,7 +102,7 @@ class Pulse
friend std::ostream& operator<<(std::ostream& os, Pulse& p )
{
return os << " idOn=" << p.isOn
return os << " idOn=" << p.isOn
<< " t1=" << p.t1.getInterval()
<< " t0=" << p.t0.getInterval()
<< " out=" << p.out();
......@@ -113,11 +113,11 @@ class Pulse
return os << (*p);
}
inline timeout_t getT1() const
inline timeout_t getT1() const noexcept
{
return t1_msec;
}
inline timeout_t getT0() const
inline timeout_t getT0() const noexcept
{
return t0_msec;
}
......
......@@ -29,8 +29,8 @@
class TCPCheck
{
public:
TCPCheck();
~TCPCheck();
TCPCheck() noexcept;
~TCPCheck() noexcept;
/*! Проверка связи с сервисом на определённом порту
* \param _ip - ip проверяемого узла
......
......@@ -26,13 +26,13 @@
class Trigger
{
public:
Trigger(bool initial = false)
Trigger(bool initial = false) noexcept
{
oldstate = initial;
}
/*! Срабатываем по верхнему фронту (при наступлении true) */
bool hi(bool state)
bool hi(bool state) noexcept
{
if (oldstate != state)
{
......@@ -45,7 +45,7 @@ class Trigger
return false;
}
/*! Срабатываем по нижнему фронту (при наступлении false) */
bool low(bool state)
bool low(bool state) noexcept
{
if (oldstate != state)
{
......@@ -58,7 +58,7 @@ class Trigger
return false;
}
/*! Срабатывает при любом изменении */
bool change(bool state)
bool change(bool state) noexcept
{
if (oldstate != state)
{
......@@ -69,7 +69,7 @@ class Trigger
return false;
}
inline bool get() const
inline bool get() const noexcept
{
return oldstate;
}
......
......@@ -79,16 +79,16 @@ class TriggerAND
*/
typedef void(Caller::* Action)(bool newstate);
TriggerAND(Caller* r, Action a);
~TriggerAND();
TriggerAND(Caller* r, Action a) noexcept;
~TriggerAND() noexcept;
inline bool state() const
inline bool state() const noexcept
{
return out;
}
bool getState(InputType in) const;
bool getState(InputType in) const noexcept;
bool commit(InputType in, bool state);
void add(InputType in, bool state);
......@@ -96,12 +96,12 @@ class TriggerAND
typedef std::unordered_map<InputType, bool> InputMap;
inline typename InputMap::const_iterator begin()
inline typename InputMap::const_iterator begin() noexcept
{
return inputs.begin();
}
inline typename InputMap::const_iterator end()
inline typename InputMap::const_iterator end() noexcept
{
return inputs.end();
}
......
......@@ -21,7 +21,7 @@
#include "TriggerAND.h"
//---------------------------------------------------------------------------
template<class Caller, typename InputType>
TriggerAND<Caller,InputType>::TriggerAND(Caller* c, Action a):
TriggerAND<Caller,InputType>::TriggerAND(Caller* c, Action a) noexcept:
out(false),
cal(c),
act(a)
......@@ -29,7 +29,7 @@ act(a)
}
template<class Caller, typename InputType>
TriggerAND<Caller,InputType>::~TriggerAND()
TriggerAND<Caller,InputType>::~TriggerAND() noexcept
{
}
......@@ -69,11 +69,15 @@ void TriggerAND<Caller,InputType>::remove(InputType num)
//---------------------------------------------------------------------------
template<class Caller, typename InputType>
bool TriggerAND<Caller,InputType>::getState(InputType num) const
bool TriggerAND<Caller,InputType>::getState(InputType num) const noexcept
{
auto it=inputs.find(num);
if( it!=inputs.end() )
return it->second;
try
{
auto it=inputs.find(num);
if( it!=inputs.end() )
return it->second;
}
catch(...){}
return false; // throw NotFound
}
......
......@@ -78,15 +78,15 @@ class TriggerOR
*/
typedef void(Caller::* Action)(bool newstate);
TriggerOR(Caller* r, Action a);
~TriggerOR();
TriggerOR(Caller* r, Action a) noexcept;
~TriggerOR() noexcept;
inline bool state() const
inline bool state() const noexcept
{
return out;
}
bool getState(InputType in) const;
bool getState(InputType in) const noexcept;
bool commit(InputType in, bool state);
void add(InputType in, bool state);
......@@ -94,12 +94,12 @@ class TriggerOR
typedef std::unordered_map<InputType, bool> InputMap;
inline typename InputMap::const_iterator begin()
inline typename InputMap::const_iterator begin() noexcept
{
return inputs.begin();
}
inline typename InputMap::const_iterator end()
inline typename InputMap::const_iterator end() noexcept
{
return inputs.end();
}
......
......@@ -21,7 +21,7 @@
#include "TriggerOR.h"
//---------------------------------------------------------------------------
template<class Caller, typename InputType>
TriggerOR<Caller,InputType>::TriggerOR(Caller* c, Action a):
TriggerOR<Caller,InputType>::TriggerOR(Caller* c, Action a) noexcept:
out(false),
cal(c),
act(a)
......@@ -29,7 +29,7 @@ act(a)
}
template<class Caller, typename InputType>
TriggerOR<Caller,InputType>::~TriggerOR()
TriggerOR<Caller,InputType>::~TriggerOR() noexcept
{
}
......@@ -69,11 +69,15 @@ void TriggerOR<Caller,InputType>::remove(InputType num)
//---------------------------------------------------------------------------
template<class Caller, typename InputType>
bool TriggerOR<Caller,InputType>::getState(InputType num) const
bool TriggerOR<Caller,InputType>::getState(InputType num) const noexcept
{
auto it=inputs.find(num);
if( it!=inputs.end() )
return it->second;
try
{
auto it=inputs.find(num);
if( it!=inputs.end() )
return it->second;
}
catch(...){}
return false; // throw NotFound
}
......
......@@ -89,12 +89,12 @@ class TriggerOUT
*/
typedef void(Caller::* Action)(OutIdType out, ValueType val);
TriggerOUT(Caller* r, Action a);
~TriggerOUT();
TriggerOUT(Caller* r, Action a) noexcept;
~TriggerOUT() noexcept;
/*! получить текущее значение указанного 'выхода' */
bool getState(OutIdType out) const;
bool getState(OutIdType out) const noexcept;
/*! установить значение одного из 'выходов'
\param out - идентификатор 'выхода'
......@@ -109,7 +109,7 @@ class TriggerOUT
void add(OutIdType out, ValueType val);
/*! удалить указанный 'выход' */
void remove(OutIdType out);
void remove(OutIdType out) noexcept;
void update();
void reset();
......
......@@ -24,14 +24,14 @@
//---------------------------------------------------------------------------
template<class Caller, typename OutIdType, typename ValueType>
TriggerOUT<Caller,OutIdType,ValueType>::TriggerOUT( Caller* r, Action a):
TriggerOUT<Caller,OutIdType,ValueType>::TriggerOUT( Caller* r, Action a) noexcept:
cal(r),
act(a)
{
}
template <class Caller, typename OutIdType, typename ValueType>
TriggerOUT<Caller,OutIdType,ValueType>::~TriggerOUT()
TriggerOUT<Caller,OutIdType,ValueType>::~TriggerOUT() noexcept
{
}
......@@ -48,21 +48,28 @@ void TriggerOUT<Caller,OutIdType,ValueType>::add(OutIdType num, ValueType val)
//---------------------------------------------------------------------------
template <class Caller, typename OutIdType, typename ValueType>
void TriggerOUT<Caller,OutIdType,ValueType>::remove(OutIdType num)
void TriggerOUT<Caller,OutIdType,ValueType>::remove(OutIdType num) noexcept
{
auto it=outs.find(num);
if( it!=outs.end() )
outs.erase(it);
try
{
auto it=outs.find(num);
if( it!=outs.end() )
outs.erase(it);
}
catch(...){}
}
//---------------------------------------------------------------------------
template <class Caller, typename OutIdType, typename ValueType>
bool TriggerOUT<Caller,OutIdType,ValueType>::getState(OutIdType out) const
bool TriggerOUT<Caller,OutIdType,ValueType>::getState(OutIdType out) const noexcept
{
auto it=outs.find(out);
if( it!=outs.end() )
return it->second;
try
{
auto it=outs.find(out);
if( it!=outs.end() )
return it->second;
}
catch(...){}
return false;
}
//---------------------------------------------------------------------------
......
......@@ -129,13 +129,12 @@ class UInterface
UniversalIO::IOType getIOType(const UniSetTypes::ObjectId id) const;
// read from xml (only for xml!) т.е. без удалённого запроса
UniversalIO::IOType getConfIOType( const UniSetTypes::ObjectId id ) const;
UniversalIO::IOType getConfIOType( const UniSetTypes::ObjectId id ) const noexcept;
// Получение типа объекта..
UniSetTypes::ObjectType getType(const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node) const throw(UI_THROW_EXCEPTIONS);
UniSetTypes::ObjectType getType(const UniSetTypes::ObjectId id) const;
//! Время последнего изменения датчика
IOController_i::ShortIOInfo getChangedTime( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const;
......@@ -173,49 +172,49 @@ class UInterface
// Проверка доступности объекта или датчика
bool isExist( const UniSetTypes::ObjectId id ) const;
bool isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const;
bool isExist( const UniSetTypes::ObjectId id ) const noexcept;
bool isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const noexcept;
// used for check 'isExist'
bool waitReady( const UniSetTypes::ObjectId id, int msec, int pause = 5000,
const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ) noexcept;
// used for check 'getValue'
bool waitWorking( const UniSetTypes::ObjectId id, int msec, int pause = 3000,
const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
const UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ) noexcept;
// ---------------------------------------------------------------
// Работа с ID, Name
/*! получение идентификатора объекта по имени */
inline UniSetTypes::ObjectId getIdByName( const std::string& name ) const
inline UniSetTypes::ObjectId getIdByName( const std::string& name ) const noexcept
{
return oind->getIdByName(name);
}
/*! получение имени по идентификатору объекта */
inline std::string getNameById( const UniSetTypes::ObjectId id ) const
inline std::string getNameById( const UniSetTypes::ObjectId id ) const noexcept
{
return oind->getNameById(id);
}
inline UniSetTypes::ObjectId getNodeId( const std::string& fullname ) const
inline UniSetTypes::ObjectId getNodeId( const std::string& fullname ) const noexcept
{
return oind->getNodeId(fullname);
}
inline std::string getTextName( const UniSetTypes::ObjectId id ) const
inline std::string getTextName( const UniSetTypes::ObjectId id ) const noexcept
{
return oind->getTextName(id);
}
// ---------------------------------------------------------------
// Получение указателей на вспомогательные классы.
inline const std::shared_ptr<UniSetTypes::ObjectIndex> getObjectIndex()
inline const std::shared_ptr<UniSetTypes::ObjectIndex> getObjectIndex() noexcept
{
return oind;
}
inline const std::shared_ptr<UniSetTypes::Configuration> getConf()
inline const std::shared_ptr<UniSetTypes::Configuration> getConf() noexcept
{
return uconf;
}
......@@ -229,7 +228,7 @@ class UInterface
// ---------------------------------------------------------------
// Вспомогательный класс для кэширования ссылок на удалённые объекты
inline void setCacheMaxSize( size_t newsize )
inline void setCacheMaxSize( size_t newsize ) noexcept
{
rcache.setMaxSize(newsize);
}
......@@ -244,9 +243,9 @@ class UInterface
UniSetTypes::ObjectPtr resolve( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const throw(UniSetTypes::NameNotFound);
void cache(const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node, UniSetTypes::ObjectVar& ptr ) const;
void erase( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const;
void erase( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const noexcept;
inline void setMaxSize( size_t ms )
inline void setMaxSize( size_t ms ) noexcept
{
MaxSize = ms;
};
......@@ -256,8 +255,8 @@ class UInterface
private:
bool clean(); /*!< функция очистки кэш-а от старых ссылок */
inline void clear() /*!< удаление всей информации */
bool clean() noexcept; /*!< функция очистки кэш-а от старых ссылок */
inline void clear() noexcept /*!< удаление всей информации */
{
UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
mcache.clear();
......
......@@ -8,7 +8,7 @@
// -------------------------------------------------------------------------
namespace UTCPCore
{
bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 );
bool setKeepAliveParams( int sock, timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ) noexcept;
// -------------------------------------------
// author: https://gist.github.com/koblas/3364414
......@@ -17,48 +17,17 @@ namespace UTCPCore
// Buffer class - allow for output buffering such that it can be written out into async pieces
struct Buffer
{
unsigned char* data = { 0 };
ssize_t len;
ssize_t pos;
Buffer( const unsigned char* bytes, ssize_t nbytes )
{
pos = 0;
len = nbytes;
if( len <= 0 ) // ??!!
return;
data = new unsigned char[nbytes];
std::memcpy(data, bytes, nbytes);
}
Buffer( const unsigned char* bytes, ssize_t nbytes );
Buffer( const std::string& s );
virtual ~Buffer();
Buffer( const std::string& s )
{
pos = 0;
len = s.length();
unsigned char* dpos() noexcept;
if( len <= 0 ) // ??!!
return;
ssize_t nbytes() noexcept;
data = new unsigned char[len];
std::memcpy(data, s.data(), len);
}
virtual ~Buffer()
{
delete [] data;
}
unsigned char* dpos()
{
return data + pos;
}
ssize_t nbytes()
{
return len - pos;
}
unsigned char* data = { 0 };
ssize_t len;
ssize_t pos;
};
}
// -------------------------------------------------------------------------
......
......@@ -24,7 +24,7 @@ class UTCPSocket:
// return true if OK
bool setKeepAliveParams( timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 );
int getSocket();
int getSocket() noexcept;
protected:
void init();
......
......@@ -36,7 +36,7 @@ class UTCPStream:
void create( const std::string& hname, int port, timeout_t tout_msec = 1000 );
bool isConnected();
bool isConnected() noexcept;
// set keepalive params
// return true if OK
......
......@@ -84,7 +84,7 @@ namespace UniSetTypes
typedef CORBA::Object_ptr ObjectPtr; /*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef CORBA::Object_var ObjectVar; /*!< Ссылка на объект регистрируемый в ObjectRepository */
UniversalIO::IOType getIOType( const std::string& s );
UniversalIO::IOType getIOType( const std::string& s ) noexcept;
std::ostream& operator<<( std::ostream& os, const UniversalIO::IOType t );
std::ostream& operator<<( std::ostream& os, const IONotifyController_i::ThresholdInfo& ti );
std::ostream& operator<<( std::ostream& os, const IOController_i::ShortIOInfo& s );
......@@ -114,23 +114,23 @@ namespace UniSetTypes
void add( ObjectId id );
void del( ObjectId id );
inline int size() const
inline int size() const noexcept
{
return lst.size();
}
inline bool empty() const
inline bool empty() const noexcept
{
return lst.empty();
}
std::list<ObjectId> getList();
std::list<ObjectId> getList() noexcept;
// за освобождение выделеной памяти
// отвечает вызывающий!
IDSeq* getIDSeq() const;
//
ObjectId getFirst() const;
ObjectId getFirst() const noexcept;
ObjectId node; // узел, на котором находятся датчики
private:
......@@ -140,7 +140,7 @@ namespace UniSetTypes
/*! Информация об имени объекта */
struct ObjectInfo
{
ObjectInfo():
ObjectInfo() noexcept:
id(DefaultObjectId),
repName(""), textName(""), data(0) {}
......@@ -164,16 +164,16 @@ namespace UniSetTypes
// Различные преобразования
//! Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
int uni_atoi( const char* str );
inline int uni_atoi( const std::string& str )
int uni_atoi( const char* str ) noexcept;
inline int uni_atoi( const std::string& str ) noexcept
{
return uni_atoi(str.c_str());
}
char* uni_strdup( const std::string& src );
std::string timeToString(time_t tm = time(0), const std::string& brk = ":"); /*!< Преобразование времени в строку HH:MM:SS */
std::string dateToString(time_t tm = time(0), const std::string& brk = "/"); /*!< Преобразование даты в строку DD/MM/YYYY */
std::string timeToString(time_t tm = time(0), const std::string& brk = ":") noexcept; /*!< Преобразование времени в строку HH:MM:SS */
std::string dateToString(time_t tm = time(0), const std::string& brk = "/") noexcept; /*!< Преобразование даты в строку DD/MM/YYYY */
struct timeval to_timeval( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timeval */
struct timespec to_timespec( const std::chrono::system_clock::duration& d ); /*!< конвертирование std::chrono в posix timespec */
......@@ -211,7 +211,7 @@ namespace UniSetTypes
std::list<UniSetTypes::ConsumerInfo> getObjectsList( const std::string& s, std::shared_ptr<UniSetTypes::Configuration> conf = nullptr );
/*! проверка является текст в строке - числом..*/
bool is_digit( const std::string& s );
bool is_digit( const std::string& s ) noexcept;
/*! замена всех вхождений подстроки
* \param src - исходная строка
......@@ -228,7 +228,7 @@ namespace UniSetTypes
*/
inline std::string getArgParam( const std::string& name,
int _argc, const char* const* _argv,
const std::string& defval = "" )
const std::string& defval = "" ) noexcept
{
for( int i = 1; i < (_argc - 1) ; i++ )
{
......@@ -241,7 +241,7 @@ namespace UniSetTypes
inline int getArgInt( const std::string& name,
int _argc, const char* const* _argv,
const std::string defval = "" )
const std::string defval = "" ) noexcept
{
return uni_atoi(getArgParam(name, _argc, _argv, defval));
}
......@@ -291,7 +291,7 @@ namespace UniSetTypes
// Проверка xml-узла на соответствие <...f_prop="f_val">,
// если не задано f_val, то проверяется, что просто f_prop!=""
bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" );
bool check_filter( UniXML::iterator& it, const std::string& f_prop, const std::string& f_val = "" ) noexcept;
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
template<typename InputIterator,
......
......@@ -39,67 +39,67 @@ class UniXML_iterator:
public std::iterator<std::bidirectional_iterator_tag, xmlNode, ptrdiff_t, xmlNode*, xmlNode&>
{
public:
UniXML_iterator(xmlNode* node) :
UniXML_iterator(xmlNode* node) noexcept:
curNode(node)
{}
UniXML_iterator(): curNode(0) {}
UniXML_iterator() noexcept: curNode(0) {}
std::string getProp2( const std::string& name, const std::string& defval = "" );
std::string getProp( const std::string& name );
int getIntProp( const std::string& name );
std::string getProp2( const std::string& name, const std::string& defval = "" ) const noexcept;
std::string getProp( const std::string& name ) const noexcept;
int getIntProp( const std::string& name ) const noexcept;
/// if value if not positive ( <= 0 ), returns def
int getPIntProp( const std::string& name, int def );
void setProp( const std::string& name, const std::string& text );
int getPIntProp( const std::string& name, int def ) const noexcept;
void setProp( const std::string& name, const std::string& text ) noexcept;
bool findName( const std::string& node, const std::string& searchname, bool deepfind = true );
bool find( const std::string& searchnode, bool deepfind = true);
xmlNode* findX( xmlNode* root, const std::string& searchnode, bool deepfind = true );
bool findName( const std::string& node, const std::string& searchname, bool deepfind = true ) noexcept;
bool find( const std::string& searchnode, bool deepfind = true) noexcept;
xmlNode* findX( xmlNode* root, const std::string& searchnode, bool deepfind = true ) noexcept;
/*! Перейти к следующему узлу. Возвращает false, если некуда перейти */
bool goNext();
bool goNext() noexcept;
/*! Перейти насквозь к следующему узлу. Возвращает false, если некуда перейти */
bool goThrowNext();
bool goThrowNext() noexcept;
/*! Перейти к предыдущему узлу */
bool goPrev();
bool goPrev() noexcept;
bool canPrev();
bool canNext();
bool canPrev() const noexcept;
bool canNext() const noexcept;
// Перейти к следующему узлу
UniXML_iterator& operator+(int);
UniXML_iterator& operator++(int);
UniXML_iterator& operator+=(int);
UniXML_iterator& operator++();
UniXML_iterator& operator+(int) noexcept;
UniXML_iterator& operator++(int) noexcept;
UniXML_iterator& operator+=(int) noexcept;
UniXML_iterator& operator++() noexcept;
// Перейти к предыдущему узлу
UniXML_iterator& operator-(int);
UniXML_iterator& operator--(int);
UniXML_iterator& operator--();
UniXML_iterator& operator-=(int);
UniXML_iterator& operator-(int) noexcept;
UniXML_iterator& operator--(int) noexcept;
UniXML_iterator& operator--() noexcept;
UniXML_iterator& operator-=(int) noexcept;
/*! Перейти на один уровень выше
\note Если перейти не удалось, итератор остаётся указывать на прежний узел
*/
bool goParent();
bool goParent() noexcept;
/*! Перейти на один уровень ниже
\note Если перейти не удалось, итератор остаётся указывать на прежний узел
*/
bool goChildren();
bool goChildren() noexcept;
// Получить текущий узел
xmlNode* getCurrent();
xmlNode* getCurrent() noexcept;
// Получить название текущего узла
const std::string getName() const;
const std::string getContent() const;
const std::string getName() const noexcept;
const std::string getContent() const noexcept;
operator xmlNode* () const;
operator xmlNode* () const noexcept;
void goBegin();
void goEnd();
void goBegin() noexcept;
void goEnd() noexcept;
private:
......@@ -116,32 +116,32 @@ class UniXML
UniXML();
~UniXML();
xmlNode* getFirstNode();
xmlNode* getFirstNode() const;
xmlNode* getFirstNode() noexcept;
xmlNode* getFirstNode() const noexcept;
/*! возвращает итератор на самый первый узел документа */
iterator begin();
iterator end();
iterator begin() noexcept;
iterator end() noexcept;
// Загружает указанный файл
void open( const std::string& filename );
bool isOpen() const noexcept;
void close();
bool isOpen() const;
std::string getFileName() const;
std::string getFileName() const noexcept;
// Создать новый XML-документ
void newDoc( const std::string& root_node, const std::string& xml_ver = "1.0");
// Получить свойство name указанного узла node
static std::string getProp(const xmlNode* node, const std::string& name);
static std::string getProp2(const xmlNode* node, const std::string& name, const std::string& defval = "" );
static std::string getProp(const xmlNode* node, const std::string& name) noexcept;
static std::string getProp2(const xmlNode* node, const std::string& name, const std::string& defval = "" ) noexcept;
static int getIntProp(const xmlNode* node, const std::string& name);
static int getIntProp(const xmlNode* node, const std::string& name) noexcept;
/// if value if not positive ( <= 0 ), returns def
static int getPIntProp(const xmlNode* node, const std::string& name, int def);
static int getPIntProp(const xmlNode* node, const std::string& name, int def) noexcept;
// Установить свойство name указанного узла node
static void setProp(xmlNode* node, const std::string& name, const std::string& text);
......
......@@ -23,12 +23,12 @@
// -----------------------------------------------------------------------------
using namespace std;
// -----------------------------------------------------------------------------
TCPCheck::TCPCheck():
TCPCheck::TCPCheck() noexcept:
tout_msec(0)
{
}
// -----------------------------------------------------------------------------
TCPCheck::~TCPCheck()
TCPCheck::~TCPCheck() noexcept
{
}
......
......@@ -4,7 +4,7 @@
// -------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------------------
bool UTCPCore::setKeepAliveParams( int fd, timeout_t timeout_sec, int keepcnt, int keepintvl )
bool UTCPCore::setKeepAliveParams( int fd, timeout_t timeout_sec, int keepcnt, int keepintvl ) noexcept
{
int enable = 1;
bool ok = true;
......@@ -24,3 +24,42 @@ bool UTCPCore::setKeepAliveParams( int fd, timeout_t timeout_sec, int keepcnt, i
return ok;
}
// -------------------------------------------------------------------------
UTCPCore::Buffer::Buffer(const unsigned char* bytes, ssize_t nbytes)
{
pos = 0;
len = nbytes;
if( len <= 0 ) // ??!!
return;
data = new unsigned char[nbytes];
std::memcpy(data, bytes, nbytes);
}
// -------------------------------------------------------------------------
UTCPCore::Buffer::Buffer(const string& s)
{
pos = 0;
len = s.length();
if( len <= 0 ) // ??!!
return;
data = new unsigned char[len];
std::memcpy(data, s.data(), len);
}
// -------------------------------------------------------------------------
UTCPCore::Buffer::~Buffer()
{
delete [] data;
}
// -------------------------------------------------------------------------
unsigned char*UTCPCore::Buffer::dpos() noexcept
{
return data + pos;
}
// -------------------------------------------------------------------------
ssize_t UTCPCore::Buffer::nbytes() noexcept
{
return len - pos;
}
// -------------------------------------------------------------------------
......@@ -37,7 +37,7 @@ bool UTCPSocket::setKeepAliveParams(timeout_t timeout_sec, int keepcnt, int keep
return UTCPCore::setKeepAliveParams(Poco::Net::ServerSocket::sockfd() , timeout_sec, keepcnt, keepintvl);
}
// -------------------------------------------------------------------------
int UTCPSocket::getSocket()
int UTCPSocket::getSocket() noexcept
{
return Poco::Net::ServerSocket::sockfd();
}
......
......@@ -93,7 +93,7 @@ void UTCPStream::create(const std::string& hname, int port, timeout_t tout_msec
setKeepAliveParams();
}
// -------------------------------------------------------------------------
bool UTCPStream::isConnected()
bool UTCPStream::isConnected() noexcept
{
return ( Poco::Net::StreamSocket::sockfd() > 0 );
/*
......
......@@ -1139,7 +1139,7 @@ void UInterface::CacheOfResolve::cache( const ObjectId id, const ObjectId node,
}
}
// ------------------------------------------------------------------------------------------------------------
bool UInterface::CacheOfResolve::clean()
bool UInterface::CacheOfResolve::clean() noexcept
{
UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
......@@ -1148,7 +1148,13 @@ bool UInterface::CacheOfResolve::clean()
for( auto it = mcache.begin(); it != mcache.end();)
{
if( it->second.ncall <= minCallCount )
mcache.erase(it++);
{
try
{
mcache.erase(it++);
}
catch(...){}
}
else
++it;
}
......@@ -1160,17 +1166,21 @@ bool UInterface::CacheOfResolve::clean()
}
// ------------------------------------------------------------------------------------------------------------
void UInterface::CacheOfResolve::erase( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const
void UInterface::CacheOfResolve::erase( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const noexcept
{
UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
auto it = mcache.find( key(id, node) );
try
{
auto it = mcache.find( key(id, node) );
if( it != mcache.end() )
mcache.erase(it);
if( it != mcache.end() )
mcache.erase(it);
}
catch(...){}
}
// ------------------------------------------------------------------------------------------------------------
bool UInterface::isExist( const UniSetTypes::ObjectId id ) const
bool UInterface::isExist( const UniSetTypes::ObjectId id ) const noexcept
{
try
{
......@@ -1201,7 +1211,7 @@ bool UInterface::isExist( const UniSetTypes::ObjectId id ) const
return false;
}
// ------------------------------------------------------------------------------------------------------------
bool UInterface::isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const
bool UInterface::isExist( const UniSetTypes::ObjectId id, const UniSetTypes::ObjectId node ) const noexcept
{
if( node == uconf->getLocalNode() )
return isExist(id);
......@@ -2181,7 +2191,7 @@ IONotifyController_i::ThresholdsListSeq* UInterface::getThresholdsList( const Un
throw UniSetTypes::TimeOut(set_err("UI(getThresholdsList): Timeout", id, node));
}
// -----------------------------------------------------------------------------
bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const ObjectId node )
bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const ObjectId node ) noexcept
{
if( msec < 0 )
msec = 0;
......@@ -2218,7 +2228,7 @@ bool UInterface::waitReady( const ObjectId id, int msec, int pmsec, const Object
return ready;
}
// -----------------------------------------------------------------------------
bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const ObjectId node )
bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const ObjectId node ) noexcept
{
if( msec < 0 )
msec = 0;
......@@ -2245,7 +2255,7 @@ bool UInterface::waitWorking( const ObjectId id, int msec, int pmsec, const Obje
return ready;
}
// -----------------------------------------------------------------------------
UniversalIO::IOType UInterface::getConfIOType( const UniSetTypes::ObjectId id ) const
UniversalIO::IOType UInterface::getConfIOType( const UniSetTypes::ObjectId id ) const noexcept
{
if( !uconf )
return UniversalIO::UnknownIOType;
......
......@@ -106,7 +106,7 @@ Debug::type Debug::value(string const& val)
}
void Debug::showLevel(ostream& o, Debug::type level)
void Debug::showLevel(ostream& o, Debug::type level) noexcept
{
// Show what features are traced
for (int i = 0 ; i < numErrorTags ; ++i)
......@@ -117,7 +117,7 @@ void Debug::showLevel(ostream& o, Debug::type level)
<< "' (" << errorTags[i].desc << ')' << endl;
}
void Debug::showTags(ostream& os)
void Debug::showTags(ostream& os) noexcept
{
for (int i = 0 ; i < numErrorTags ; ++i)
os << setw(7) << errorTags[i].level
......@@ -127,7 +127,7 @@ void Debug::showTags(ostream& os)
os.flush();
}
std::ostream& operator<<(std::ostream& os, Debug::type level )
std::ostream& operator<<(std::ostream& os, Debug::type level ) noexcept
{
for (int i = 0 ; i < numErrorTags ; ++i)
......@@ -139,7 +139,7 @@ std::ostream& operator<<(std::ostream& os, Debug::type level )
return os << "???Debuglevel"; // << "(" << int(level) << ")";
}
std::string Debug::str( Debug::type level )
std::string Debug::str( Debug::type level ) noexcept
{
if( level == Debug::NONE )
return "NONE";
......
......@@ -73,9 +73,13 @@ DebugStream::DebugStream(char const* f, Debug::type t, bool truncate )
internal->sbuf.signal_overflow().connect(sigc::mem_fun(*this, &DebugStream::sbuf_overflow));
}
//--------------------------------------------------------------------------
void DebugStream::sbuf_overflow( const std::string& s )
void DebugStream::sbuf_overflow( const std::string& s ) noexcept
{
s_stream.emit(s);
try
{
s_stream.emit(s);
}
catch(...){}
}
//--------------------------------------------------------------------------
DebugStream::~DebugStream()
......@@ -132,7 +136,7 @@ void DebugStream::logFile( const std::string& f, bool truncate )
delete rdbuf(new teebuf(cerr.rdbuf(), &internal->sbuf));
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::debug(Debug::type t)
std::ostream& DebugStream::debug(Debug::type t) noexcept
{
if(dt & t)
{
......@@ -148,7 +152,7 @@ std::ostream& DebugStream::debug(Debug::type t)
return nullstream;
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::operator()(Debug::type t)
std::ostream& DebugStream::operator()(Debug::type t) noexcept
{
if(dt & t)
return *this;
......@@ -156,7 +160,7 @@ std::ostream& DebugStream::operator()(Debug::type t)
return nullstream;
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::printDate(Debug::type t, char brk)
std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
{
if(dt && t)
{
......@@ -170,7 +174,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk)
return nullstream;
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::printTime(Debug::type t, char brk)
std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
{
if(dt && t)
{
......@@ -184,7 +188,7 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk)
return nullstream;
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::printDateTime(Debug::type t)
std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
{
if(dt & t)
{
......@@ -201,7 +205,7 @@ std::ostream& DebugStream::printDateTime(Debug::type t)
return nullstream;
}
//--------------------------------------------------------------------------
std::ostream& DebugStream::pos(int x, int y)
std::ostream& DebugStream::pos(int x, int y) noexcept
{
if( !dt )
return nullstream;
......
......@@ -29,19 +29,23 @@ using namespace UniSetTypes;
// -------------------------------------------------------------------------
CommonEventLoop LogServer::loop;
// -------------------------------------------------------------------------
LogServer::~LogServer()
LogServer::~LogServer() noexcept
{
if( isrunning )
loop.evstop(this);
try
{
if( isrunning )
loop.evstop(this);
}
catch(...){}
}
// -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<LogAgregator> log ):
LogServer::LogServer( std::shared_ptr<LogAgregator> log ) noexcept:
LogServer(static_pointer_cast<DebugStream>(log))
{
}
// -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<DebugStream> log ):
LogServer::LogServer( std::shared_ptr<DebugStream> log ) noexcept:
timeout(UniSetTimer::WaitUpTime),
cmdTimeout(2000),
sessLogLevel(Debug::NONE),
......@@ -50,7 +54,7 @@ LogServer::LogServer( std::shared_ptr<DebugStream> log ):
{
}
// -------------------------------------------------------------------------
LogServer::LogServer():
LogServer::LogServer() noexcept:
timeout(UniSetTimer::WaitUpTime),
cmdTimeout(2000),
sessLogLevel(Debug::NONE),
......
......@@ -110,11 +110,12 @@ LogSession::LogSession( const Poco::Net::StreamSocket& s, std::shared_ptr<DebugS
mylog.crit() << "LOG NULL!!" << endl;
}
// -------------------------------------------------------------------------
void LogSession::logOnEvent( const std::string& s )
void LogSession::logOnEvent( const std::string& s ) noexcept
{
if( cancelled || s.empty() )
return;
try
{
// чтобы поменьше удерживать mutex
std::unique_lock<std::mutex> lk(logbuf_mutex);
......@@ -151,12 +152,13 @@ void LogSession::logOnEvent( const std::string& s )
lostMsg = false;
logbuf.emplace(new UTCPCore::Buffer(s));
}
catch(...){}
if( asyncEvent.is_active() )
asyncEvent.send();
}
// -------------------------------------------------------------------------
void LogSession::run( const ev::loop_ref& loop )
void LogSession::run( const ev::loop_ref& loop ) noexcept
{
setSessionLogLevel(Debug::ANY);
......@@ -198,7 +200,7 @@ void LogSession::terminate()
final();
}
// -------------------------------------------------------------------------
void LogSession::event( ev::async& watcher, int revents )
void LogSession::event( ev::async& watcher, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -211,7 +213,7 @@ void LogSession::event( ev::async& watcher, int revents )
io.set(ev::WRITE);
}
// ---------------------------------------------------------------------
void LogSession::callback( ev::io& watcher, int revents )
void LogSession::callback( ev::io& watcher, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -222,10 +224,22 @@ void LogSession::callback( ev::io& watcher, int revents )
}
if (revents & EV_READ)
readEvent(watcher);
{
try
{
readEvent(watcher);
}
catch(...){}
}
if (revents & EV_WRITE)
writeEvent(watcher);
{
try
{
writeEvent(watcher);
}
catch(...){}
}
if( cancelled )
{
......@@ -234,11 +248,14 @@ void LogSession::callback( ev::io& watcher, int revents )
io.stop();
cmdTimer.stop();
try
{
std::unique_lock<std::mutex> lk(logbuf_mutex);
asyncEvent.stop();
conn.disconnect();
}
catch(...){}
final();
}
}
......@@ -340,13 +357,17 @@ size_t LogSession::readData( unsigned char* buf, int len )
{
}
catch( std::exception& ex )
{
}
mylog.info() << peername << "(readData): client disconnected.." << endl;
cancelled = true;
return 0;
}
// --------------------------------------------------------------------------------
void LogSession::readEvent( ev::io& watcher )
void LogSession::readEvent( ev::io& watcher ) noexcept
{
if( cancelled )
return;
......@@ -367,11 +388,20 @@ void LogSession::readEvent( ev::io& watcher )
}
if( mylog.is_info() )
mylog.info() << peername << "(run): receive command: '" << msg.cmd << "'" << endl;
mylog.info() << peername << "(readEvent): receive command: '" << msg.cmd << "'" << endl;
string cmdLogName(msg.logname);
cmdProcessing(cmdLogName, msg);
try
{
cmdProcessing(cmdLogName, msg);
}
catch( std::exception& ex )
{
if( mylog.is_warn() )
mylog.warn() << peername << "(readEvent): " << ex.what() << endl;
}
catch(...){}
#if 0
// Выводим итоговый получившийся список (с учётом выполненных команд)
......@@ -524,7 +554,7 @@ void LogSession::cmdProcessing( const string& cmdLogName, const LogServerTypes::
}
}
// -------------------------------------------------------------------------
void LogSession::onCmdTimeout( ev::timer& watcher, int revents )
void LogSession::onCmdTimeout( ev::timer& watcher, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -538,7 +568,7 @@ void LogSession::onCmdTimeout( ev::timer& watcher, int revents )
asyncEvent.start();
}
// -------------------------------------------------------------------------
void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents )
void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents ) noexcept
{
if( EV_ERROR & revents )
{
......@@ -559,17 +589,26 @@ void LogSession::onCheckConnectionTimer( ev::timer& watcher, int revents )
// если клиент уже отвалился.. то при попытке write.. сессия будет закрыта.
// длинное сообщение ("keep alive message") забивает логи, что потом неудобно смотреть, поэтому пишем "пустоту"
logbuf.emplace(new UTCPCore::Buffer(""));
try
{
logbuf.emplace(new UTCPCore::Buffer(""));
}
catch(...){}
io.set(ev::WRITE);
checkConnectionTimer.start( checkConnectionTime ); // restart timer
}
// -------------------------------------------------------------------------
void LogSession::final()
void LogSession::final() noexcept
{
slFin(this);
try
{
slFin(this);
}
catch(...){}
}
// -------------------------------------------------------------------------
void LogSession::connectFinalSession( FinalSlot sl )
void LogSession::connectFinalSession( FinalSlot sl ) noexcept
{
slFin = sl;
}
......@@ -579,7 +618,7 @@ LogSession::LogSessionCommand_Signal LogSession::signal_logsession_command()
return m_command_sig;
}
// ---------------------------------------------------------------------
void LogSession::cancel()
void LogSession::cancel() noexcept
{
cancelled = true;
}
......@@ -590,17 +629,17 @@ void LogSession::setMaxBufSize( size_t num )
maxRecordsNum = num;
}
// ---------------------------------------------------------------------
size_t LogSession::getMaxBufSize() const
size_t LogSession::getMaxBufSize() const noexcept
{
return maxRecordsNum;
}
// ---------------------------------------------------------------------
bool LogSession::isAcive() const
bool LogSession::isAcive() const noexcept
{
return io.is_active();
}
// ---------------------------------------------------------------------
string LogSession::getShortInfo()
string LogSession::getShortInfo() noexcept
{
size_t sz = 0;
{
......
......@@ -29,22 +29,26 @@ using namespace UniSetTypes;
//const std::string ObjectIndex::sepNode = ":";
// -----------------------------------------------------------------------------------------
string ObjectIndex::getNameById( const ObjectId id ) const
string ObjectIndex::getNameById( const ObjectId id ) const noexcept
{
return getMapName(id);
}
// -----------------------------------------------------------------------------------------
std::string ObjectIndex::getBaseName( const std::string& fname )
std::string ObjectIndex::getBaseName( const std::string& fname ) noexcept
{
string::size_type pos = fname.rfind('/');
if( pos != string::npos )
return fname.substr(pos + 1);
try
{
if( pos != string::npos )
return fname.substr(pos + 1);
}
catch(...){}
return fname;
}
// -----------------------------------------------------------------------------------------
void ObjectIndex::initLocalNode( const ObjectId nodeid )
void ObjectIndex::initLocalNode( const ObjectId nodeid ) noexcept
{
nmLocalNode = getMapName(nodeid);
}
......
......@@ -47,7 +47,7 @@ ObjectIndex_Array::ObjectIndex_Array( const ObjectInfo* objectInfo ):
}
}
// -----------------------------------------------------------------------------------------
ObjectId ObjectIndex_Array::getIdByName( const string& name ) const
ObjectId ObjectIndex_Array::getIdByName( const string& name ) const noexcept
{
auto it = mok.find(name);
......@@ -58,7 +58,7 @@ ObjectId ObjectIndex_Array::getIdByName( const string& name ) const
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_Array::getMapName( const ObjectId id ) const
string ObjectIndex_Array::getMapName( const ObjectId id ) const noexcept
{
if( id != UniSetTypes::DefaultObjectId && id >= 0 && id < maxId )
return objectInfo[id].repName;
......@@ -67,7 +67,7 @@ string ObjectIndex_Array::getMapName( const ObjectId id ) const
// throw OutOfRange("ObjectIndex_Array::getMapName OutOfRange");
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_Array::getTextName( const ObjectId id ) const
string ObjectIndex_Array::getTextName( const ObjectId id ) const noexcept
{
if( id != UniSetTypes::DefaultObjectId && id >= 0 && id < maxId )
return objectInfo[id].textName;
......@@ -82,7 +82,7 @@ std::ostream& operator<<(std::ostream& os, ObjectIndex_Array& oi )
}
// -----------------------------------------------------------------------------------------
std::ostream& ObjectIndex_Array::printMap( std::ostream& os ) const
std::ostream& ObjectIndex_Array::printMap( std::ostream& os ) const noexcept
{
auto oind = uniset_conf()->oind;
......@@ -101,7 +101,7 @@ std::ostream& ObjectIndex_Array::printMap( std::ostream& os ) const
return os;
}
// -----------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_Array::getObjectInfo( const ObjectId id ) const
const ObjectInfo* ObjectIndex_Array::getObjectInfo( const ObjectId id ) const noexcept
{
if( id != UniSetTypes::DefaultObjectId && id >= 0 && id < maxId )
return &(objectInfo[id]);
......@@ -109,7 +109,7 @@ const ObjectInfo* ObjectIndex_Array::getObjectInfo( const ObjectId id ) const
return NULL;
}
// -----------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_Array::getObjectInfo( const std::string& name ) const
const ObjectInfo* ObjectIndex_Array::getObjectInfo( const std::string& name ) const noexcept
{
auto it = mok.find(name);
......
......@@ -46,17 +46,20 @@ ObjectIndex_XML::~ObjectIndex_XML()
{
}
// -----------------------------------------------------------------------------------------
ObjectId ObjectIndex_XML::getIdByName( const string& name ) const
ObjectId ObjectIndex_XML::getIdByName( const string& name ) const noexcept
{
auto it = mok.find(name);
if( it != mok.end() )
return it->second;
try
{
auto it = mok.find(name);
if( it != mok.end() )
return it->second;
}
catch(...){}
return DefaultObjectId;
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_XML::getMapName( const ObjectId id ) const
string ObjectIndex_XML::getMapName( const ObjectId id ) const noexcept
{
if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return omap[id].repName;
......@@ -64,7 +67,7 @@ string ObjectIndex_XML::getMapName( const ObjectId id ) const
return "";
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_XML::getTextName( const ObjectId id ) const
string ObjectIndex_XML::getTextName( const ObjectId id ) const noexcept
{
if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return omap[id].textName;
......@@ -77,7 +80,7 @@ std::ostream& operator<<(std::ostream& os, ObjectIndex_XML& oi )
return oi.printMap(os);
}
// -----------------------------------------------------------------------------------------
std::ostream& ObjectIndex_XML::printMap( std::ostream& os ) const
std::ostream& ObjectIndex_XML::printMap( std::ostream& os ) const noexcept
{
os << "size: " << omap.size() << endl;
......@@ -99,7 +102,7 @@ void ObjectIndex_XML::build( const std::shared_ptr<UniXML>& xml )
{
// выделяем память
// ObjectInfo* omap = new ObjectInfo[maxSize];
ObjectId ind = 1;
size_t ind = 1;
ind = read_section(xml, "sensors", ind);
ind = read_section(xml, "objects", ind);
ind = read_section(xml, "controllers", ind);
......@@ -113,9 +116,9 @@ void ObjectIndex_XML::build( const std::shared_ptr<UniXML>& xml )
// omap[ind].id = ind;
}
// ------------------------------------------------------------------------------------------
unsigned int ObjectIndex_XML::read_section( const std::shared_ptr<UniXML>& xml, const std::string& sec, unsigned int ind )
size_t ObjectIndex_XML::read_section( const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind )
{
if( (unsigned)ind >= omap.size() )
if( ind >= omap.size() )
{
uwarn << "(ObjectIndex_XML::build): не хватило размера массива maxSize=" << omap.size()
<< "... Делаем resize + 100" << endl;
......@@ -208,13 +211,12 @@ unsigned int ObjectIndex_XML::read_section( const std::shared_ptr<UniXML>& xml,
return ind;
}
// ------------------------------------------------------------------------------------------
unsigned int ObjectIndex_XML::read_nodes( const std::shared_ptr<UniXML>& xml, const std::string& sec, unsigned int ind )
size_t ObjectIndex_XML::read_nodes(const std::shared_ptr<UniXML>& xml, const std::string& sec, size_t ind )
{
if( ind >= omap.size() )
{
ostringstream msg;
msg << "(ObjectIndex_XML::build): не хватило размера массива maxSize=" << omap.size();
uinfo << msg.str() << "... Делаем resize + 100\n";
uinfo << "(ObjectIndex_XML::build): не хватило размера массива maxSize=" << omap.size()
<< "... Делаем resize + 100" << endl;
omap.resize(omap.size() + 100);
}
......@@ -272,21 +274,25 @@ unsigned int ObjectIndex_XML::read_nodes( const std::shared_ptr<UniXML>& xml, co
return ind;
}
// ------------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_XML::getObjectInfo( const ObjectId id ) const
const ObjectInfo* ObjectIndex_XML::getObjectInfo( const ObjectId id ) const noexcept
{
if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return &omap[id];
return NULL;
return nullptr;
}
// ------------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_XML::getObjectInfo( const std::string& name ) const
const ObjectInfo* ObjectIndex_XML::getObjectInfo( const std::string& name ) const noexcept
{
auto it = mok.find(name);
try
{
auto it = mok.find(name);
if( it != mok.end() )
return &(omap[it->second]);
if( it != mok.end() )
return &(omap[it->second]);
}
catch(...){}
return NULL;
return nullptr;
}
// ------------------------------------------------------------------------------------------
......@@ -43,32 +43,43 @@ ObjectIndex_idXML::~ObjectIndex_idXML()
{
}
// -----------------------------------------------------------------------------------------
ObjectId ObjectIndex_idXML::getIdByName( const string& name ) const
ObjectId ObjectIndex_idXML::getIdByName( const string& name ) const noexcept
{
auto it = mok.find(name);
try
{
auto it = mok.find(name);
if( it != mok.end() )
return it->second;
if( it != mok.end() )
return it->second;
}
catch(...){}
return DefaultObjectId;
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_idXML::getMapName( const ObjectId id ) const
string ObjectIndex_idXML::getMapName( const ObjectId id ) const noexcept
{
auto it = omap.find(id);
if( it != omap.end() )
return it->second.repName;
try
{
auto it = omap.find(id);
if( it != omap.end() )
return it->second.repName;
}
catch(...){}
return "";
}
// -----------------------------------------------------------------------------------------
string ObjectIndex_idXML::getTextName( const ObjectId id ) const
string ObjectIndex_idXML::getTextName( const ObjectId id ) const noexcept
{
auto it = omap.find(id);
try
{
auto it = omap.find(id);
if( it != omap.end() )
return it->second.textName;
if( it != omap.end() )
return it->second.textName;
}
catch(...){}
return "";
}
......@@ -78,7 +89,7 @@ std::ostream& operator<<(std::ostream& os, ObjectIndex_idXML& oi )
return oi.printMap(os);
}
// -----------------------------------------------------------------------------------------
std::ostream& ObjectIndex_idXML::printMap( std::ostream& os ) const
std::ostream& ObjectIndex_idXML::printMap( std::ostream& os ) const noexcept
{
os << "size: " << omap.size() << endl;
......@@ -235,23 +246,31 @@ void ObjectIndex_idXML::read_nodes( const std::shared_ptr<UniXML>& xml, const st
}
}
// ------------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_idXML::getObjectInfo( const ObjectId id ) const
const ObjectInfo* ObjectIndex_idXML::getObjectInfo( const ObjectId id ) const noexcept
{
auto it = omap.find(id);
try
{
auto it = omap.find(id);
if( it != omap.end() )
return &(it->second);
if( it != omap.end() )
return &(it->second);
}
catch(...){}
return NULL;
return nullptr;
}
// ------------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_idXML::getObjectInfo( const std::string& name ) const
const ObjectInfo* ObjectIndex_idXML::getObjectInfo( const std::string& name ) const noexcept
{
auto it = mok.find(name);
try
{
auto it = mok.find(name);
if( it != mok.end() )
return getObjectInfo(it->second);
if( it != mok.end() )
return getObjectInfo(it->second);
}
catch(...){}
return NULL;
return nullptr;
}
// ------------------------------------------------------------------------------------------
......@@ -172,12 +172,12 @@ void UniSetTypes::IDList::del( ObjectId id )
}
}
std::list<UniSetTypes::ObjectId> UniSetTypes::IDList::getList()
std::list<UniSetTypes::ObjectId> UniSetTypes::IDList::getList() noexcept
{
return lst;
}
UniSetTypes::ObjectId UniSetTypes::IDList::getFirst() const
UniSetTypes::ObjectId UniSetTypes::IDList::getFirst() const noexcept
{
if( lst.empty() )
return UniSetTypes::DefaultObjectId;
......@@ -266,7 +266,7 @@ std::vector<std::string> UniSetTypes::explode_str( const string& str, char sep )
return std::move(v);
}
// ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s )
bool UniSetTypes::is_digit( const std::string& s ) noexcept
{
for( const auto& c : s )
{
......@@ -411,7 +411,7 @@ std::list<UniSetTypes::ConsumerInfo> UniSetTypes::getObjectsList( const string&
return std::move(res);
}
// --------------------------------------------------------------------------------------
UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype )
UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype ) noexcept
{
if ( stype == "DI" || stype == "di" )
return UniversalIO::DI;
......@@ -425,7 +425,7 @@ UniversalIO::IOType UniSetTypes::getIOType( const std::string& stype )
if ( stype == "AO" || stype == "ao" )
return UniversalIO::AO;
return UniversalIO::UnknownIOType;
return UniversalIO::UnknownIOType;
}
// ------------------------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOType t )
......@@ -445,7 +445,7 @@ std::ostream& UniSetTypes::operator<<( std::ostream& os, const UniversalIO::IOTy
return os << "UnknownIOType";
}
// ------------------------------------------------------------------------------------------
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 ) noexcept
{
if( f_prop.empty() )
return true;
......@@ -461,7 +461,7 @@ bool UniSetTypes::check_filter( UniXML::iterator& it, const std::string& f_prop,
return true;
}
// ------------------------------------------------------------------------------------------
string UniSetTypes::timeToString(time_t tm, const std::string& brk )
string UniSetTypes::timeToString(time_t tm, const std::string& brk ) noexcept
{
struct tm* tms = localtime(&tm);
ostringstream time;
......@@ -471,7 +471,7 @@ string UniSetTypes::timeToString(time_t tm, const std::string& brk )
return time.str();
}
string UniSetTypes::dateToString(time_t tm, const std::string& brk )
string UniSetTypes::dateToString(time_t tm, const std::string& brk ) noexcept
{
struct tm* tms = localtime(&tm);
ostringstream date;
......@@ -482,7 +482,7 @@ string UniSetTypes::dateToString(time_t tm, const std::string& brk )
}
//--------------------------------------------------------------------------------------------
int UniSetTypes::uni_atoi( const char* str )
int UniSetTypes::uni_atoi( const char* str ) noexcept
{
// if str is NULL or sscanf failed, we return 0
if( str == nullptr )
......
......@@ -4,7 +4,7 @@
// -------------------------------------------------------------------------
using namespace std;
// -------------------------------------------------------------------------
CommonEventLoop::CommonEventLoop()
CommonEventLoop::CommonEventLoop() noexcept
{
evterm.set(loop);
evterm.set<CommonEventLoop, &CommonEventLoop::onStop>(this);
......@@ -76,7 +76,7 @@ bool CommonEventLoop::evrun(EvWatcher* w, bool thread )
return true;
}
// ---------------------------------------------------------------------------
bool CommonEventLoop::evIsActive() const
bool CommonEventLoop::evIsActive() const noexcept
{
return isrunning;
}
......@@ -120,7 +120,7 @@ bool CommonEventLoop::evstop( EvWatcher* w )
return true;
}
// -------------------------------------------------------------------------
void CommonEventLoop::onPrepare()
void CommonEventLoop::onPrepare() noexcept
{
if( wprep )
{
......@@ -141,7 +141,7 @@ void CommonEventLoop::onPrepare()
prep_event.notify_all();
}
// -------------------------------------------------------------------------
void CommonEventLoop::onStop()
void CommonEventLoop::onStop() noexcept
{
// здесь список не защищаем wlist_mutex
// потому-что onStop будет вызываться
......@@ -165,7 +165,7 @@ void CommonEventLoop::onStop()
}
// -------------------------------------------------------------------------
void CommonEventLoop::defaultLoop()
void CommonEventLoop::defaultLoop() noexcept
{
isrunning = true;
......
......@@ -32,7 +32,7 @@ void EventLoopServer::evrun( bool thread )
thr = make_shared<std::thread>( [ = ] { defaultLoop(); } );
}
// ---------------------------------------------------------------------------
bool EventLoopServer::evIsActive() const
bool EventLoopServer::evIsActive() const noexcept
{
return isrunning;
}
......@@ -49,7 +49,7 @@ void EventLoopServer::evstop()
}
}
// -------------------------------------------------------------------------
void EventLoopServer::onStop()
void EventLoopServer::onStop() noexcept
{
try
{
......@@ -64,7 +64,7 @@ void EventLoopServer::onStop()
loop.break_loop(ev::ALL);
}
// -------------------------------------------------------------------------
void EventLoopServer::defaultLoop()
void EventLoopServer::defaultLoop() noexcept
{
evterm.start();
evprepare();
......
......@@ -27,44 +27,53 @@
using namespace std;
// ------------------------------------------------------------------------------------------
PassiveCondTimer::PassiveCondTimer():
PassiveCondTimer::PassiveCondTimer() noexcept:
terminated(ATOMIC_VAR_INIT(1))
{
}
// ------------------------------------------------------------------------------------------
PassiveCondTimer::~PassiveCondTimer()
PassiveCondTimer::~PassiveCondTimer() noexcept
{
terminate();
}
// ------------------------------------------------------------------------------------------
void PassiveCondTimer::terminate()
void PassiveCondTimer::terminate() noexcept
{
try
{
std::unique_lock<std::mutex> lk(m_working);
terminated = true;
}
catch(...){}
cv_working.notify_all();
}
// ------------------------------------------------------------------------------------------
bool PassiveCondTimer::wait( timeout_t time_msec )
bool PassiveCondTimer::wait( timeout_t time_msec ) noexcept
{
std::unique_lock<std::mutex> lk(m_working);
terminated = false;
try
{
std::unique_lock<std::mutex> lk(m_working);
terminated = false;
timeout_t t_msec = PassiveTimer::setTiming(time_msec); // вызываем для совместимости с обычным PassiveTimer-ом
timeout_t t_msec = PassiveTimer::setTiming(time_msec); // вызываем для совместимости с обычным PassiveTimer-ом
if( time_msec == WaitUpTime )
{
while( !terminated )
cv_working.wait(lk);
if( time_msec == WaitUpTime )
{
while( !terminated )
cv_working.wait(lk);
}
else
cv_working.wait_for(lk, std::chrono::milliseconds(t_msec), [&]()
{
return (terminated == true);
} );
terminated = true;
return true;
}
else
cv_working.wait_for(lk, std::chrono::milliseconds(t_msec), [&]()
{
return (terminated == true);
} );
catch(...){}
terminated = true;
return true;
return false;
}
// ------------------------------------------------------------------------------------------
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