Commit ae323107 authored by Pavel Vainerman's avatar Pavel Vainerman

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

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