From c9b1010a9401e792f815bb31ddbdb630b39dfb7b Mon Sep 17 00:00:00 2001 From: Karl Palsson Date: Thu, 9 Jun 2022 13:34:54 +0000 Subject: [PATCH] allow user provided address checking If user provided address checking is enabled, the user function takes complete responsibility for validating. An example function would be: ``` BOOL isMBUserAddressValid( UCHAR ucMBAddress, UCHAR ucRcvAddress ) { if ( /* Accept our originally configured address */ (ucMBAddress == ucRcvAddress) || /* Accept all even, non-broadcast addresses less than 50 */ (ucRcvAddress > 0 && ucRcvAddress < 50 && ((ucRcvAddress & 0x1) == 0)) ) { return true; } return false; } ``` This allows fixing issues such as: https://github.com/cwalter-at/freemodbus/pull/27 in a more general fashion. Note that this does not affect the STRICT_ADDRESSING or QUIRK_REPLY_BROADCAST_READ options, which are _after_ we have decided to look at the frame. Signed-off-by: Karl Palsson --- modbus/include/mb.h | 13 +++++++++++++ modbus/include/mbconfig.h | 5 +++++ modbus/mb.c | 6 +++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/modbus/include/mb.h b/modbus/include/mb.h index a4b3b7d..9d486c3 100644 --- a/modbus/include/mb.h +++ b/modbus/include/mb.h @@ -243,6 +243,19 @@ eMBErrorCode eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, UCHAR const *pucAdditional, USHORT usAdditionalLen ); +/*! \ingroup modbus + * \brief Require user validation of the addresses. + * You can use this to "allow" a custom range of modbus addresses, + * instead of just the single address provided in \ref eMBInit + * This function is only called if MB_USER_ADDRESS_VALIDATION > 0 + * in your mbconfig.h + * + * \param ucMBAddress Value provided at eMBInit time + * \param ucRcvAddress Value currently being evaluated + * \return true if the address should be accepted + */ +BOOL isMBUserAddressValid( UCHAR ucMBAddress, UCHAR ucRcvAddress ); + /*! \ingroup modbus * \brief Registers a callback handler for a given function code. * diff --git a/modbus/include/mbconfig.h b/modbus/include/mbconfig.h index efdd1bc..e0658f2 100644 --- a/modbus/include/mbconfig.h +++ b/modbus/include/mbconfig.h @@ -175,6 +175,11 @@ PR_BEGIN_EXTERN_C #endif +#ifndef MB_USER_ADDRESS_VALIDATION +/*! \brief require user code to validate addresses */ +#define MB_USER_ADDRESS_VALIDATION ( 0 ) +#endif + /*! @} */ #ifdef __cplusplus PR_END_EXTERN_C diff --git a/modbus/mb.c b/modbus/mb.c index e97dbc9..06cc292 100644 --- a/modbus/mb.c +++ b/modbus/mb.c @@ -361,7 +361,11 @@ eMBPoll( void ) if( eStatus == MB_ENOERR ) { /* Check if the frame is for us. If not ignore the frame. */ - if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) ) +#if MB_USER_ADDRESS_VALIDATION > 0 + if( isMBUserAddressValid( ucMBAddress, ucRcvAddress ) ) +#else + if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) ) +#endif { ( void )xMBPortEventPost( EV_EXECUTE ); }