feature add modbus user error handler

This commit is contained in:
Alex Lisitsyn
2024-06-07 20:46:15 +08:00
parent 5e7a26b640
commit b643775c08
15 changed files with 500 additions and 108 deletions
+20 -4
View File
@@ -180,7 +180,7 @@ esp_err_t mbc_master_start(void)
}
eMBErrorCode eMBMasterRegDiscreteCB(UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNDiscrete)
USHORT usNDiscrete)
{
eMBErrorCode error = MB_ENOERR;
MB_MASTER_CHECK((master_interface_ptr != NULL),
@@ -194,7 +194,7 @@ eMBErrorCode eMBMasterRegDiscreteCB(UCHAR * pucRegBuffer, USHORT usAddress,
}
eMBErrorCode eMBMasterRegCoilsCB(UCHAR* pucRegBuffer, USHORT usAddress,
USHORT usNCoils, eMBRegisterMode eMode)
USHORT usNCoils, eMBRegisterMode eMode)
{
eMBErrorCode error = MB_ENOERR;
MB_MASTER_CHECK((master_interface_ptr != NULL),
@@ -209,7 +209,7 @@ eMBErrorCode eMBMasterRegCoilsCB(UCHAR* pucRegBuffer, USHORT usAddress,
}
eMBErrorCode eMBMasterRegHoldingCB(UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNRegs, eMBRegisterMode eMode)
USHORT usNRegs, eMBRegisterMode eMode)
{
eMBErrorCode error = MB_ENOERR;
MB_MASTER_CHECK((master_interface_ptr != NULL),
@@ -224,7 +224,7 @@ eMBErrorCode eMBMasterRegHoldingCB(UCHAR * pucRegBuffer, USHORT usAddress,
}
eMBErrorCode eMBMasterRegInputCB(UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNRegs)
USHORT usNRegs)
{
eMBErrorCode error = MB_ENOERR;
MB_MASTER_CHECK((master_interface_ptr != NULL),
@@ -237,6 +237,22 @@ eMBErrorCode eMBMasterRegInputCB(UCHAR * pucRegBuffer, USHORT usAddress,
return error;
}
/**
* Helper function to get current transaction info
*/
esp_err_t mbc_master_get_transaction_info(mb_trans_info_t *ptinfo)
{
MB_MASTER_CHECK((ptinfo),
ESP_ERR_INVALID_ARG,
"Wrong argument.");
MB_MASTER_CHECK(xMBMasterGetLastTransactionInfo(&ptinfo->trans_id, &ptinfo->dest_addr,
&ptinfo->func_code, &ptinfo->exception,
&ptinfo->err_type),
ESP_ERR_INVALID_STATE,
"Master can not get transaction info.");
return ESP_OK;
}
// Helper function to set parameter buffer according to its type
esp_err_t mbc_master_set_param_data(void* dest, void* src, mb_descr_type_t param_type, size_t param_size)
{
@@ -150,6 +150,17 @@ typedef struct {
uint16_t reg_size; /*!< Modbus number of registers */
} mb_param_request_t;
/**
* @brief Modbus transacion info structure
*/
typedef struct {
uint64_t trans_id; /*!< Modbus unique transaction identificator */
uint16_t err_type; /*!< Modbus last transaction error type */
uint8_t dest_addr; /*!< Modbus destination short address (or UID) */
uint8_t func_code; /*!< Modbus last transaction function code */
uint8_t exception; /*!< Modbus last transaction exception code returned by slave */
} mb_trans_info_t;
/**
* @brief Initialize Modbus controller and stack for TCP port
*
@@ -321,6 +332,18 @@ esp_err_t mbc_master_set_parameter(uint16_t cid, char* name, uint8_t* value, uin
*/
esp_err_t mbc_master_set_param_data(void* dest, void* src, mb_descr_type_t param_type, size_t param_size);
/**
* @brief The helper function to expose transaction info from modbus layer
*
* @param[in] ptinfo the pointer to transaction info structure
*
* @return
* - esp_err_t ESP_OK - the transaction info is saved in the appropriate parameter structure
* - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function or parameter descriptor
* - esp_err_t ESP_ERR_INVALID_STATE - invalid state during data processing or allocation failure
*/
esp_err_t mbc_master_get_transaction_info(mb_trans_info_t *ptinfo);
#ifdef __cplusplus
}
#endif
+1
View File
@@ -18,6 +18,7 @@
#include "esp_modbus_common.h" // for common types
#include "esp_modbus_master.h" // for public master types
#include "esp_modbus_callbacks.h"
#include "mb_m.h" // this is required to expose current transaction info
/* ----------------------- Defines ------------------------------------------*/
-1
View File
@@ -83,7 +83,6 @@ typedef enum
/* These Modbus values are shared in ASCII mode*/
extern volatile UCHAR ucMasterRcvBuf[];
extern volatile UCHAR ucMasterSndBuf[];
extern volatile eMBMasterTimerMode eMasterCurTimerMode;
/* ----------------------- Static functions ---------------------------------*/
static UCHAR prvucMBCHAR2BIN( UCHAR ucCharacter );
+33 -13
View File
@@ -95,16 +95,33 @@ typedef enum
MB_MRE_EXE_FUN /*!< execute function error. */
} eMBMasterReqErrCode;
/*! \ingroup modbus
* \brief Transaction information structure.
*/
typedef struct
{
uint64_t xTransId;
UCHAR ucDestAddr;
UCHAR ucFuncCode;
eMBException eException;
UCHAR ucFrameError;
} TransactionInfo_t;
/*! \ingroup modbus
* \brief TimerMode is Master 3 kind of Timer modes.
*/
typedef enum
{
MB_TMODE_T35, /*!< Master receive frame T3.5 timeout. */
MB_TMODE_RESPOND_TIMEOUT, /*!< Master wait respond for slave. */
MB_TMODE_CONVERT_DELAY /*!< Master sent broadcast ,then delay sometime.*/
MB_TMODE_T35, /*!< Master receive frame T3.5 timeout. */
MB_TMODE_RESPOND_TIMEOUT, /*!< Master wait respond for slave. */
MB_TMODE_CONVERT_DELAY /*!< Master sent broadcast ,then delay sometime.*/
} eMBMasterTimerMode;
extern _lock_t xMBMLock; // Modbus lock object
#define MB_ATOMIC_SECTION CRITICAL_SECTION(xMBMLock)
/* ----------------------- Function prototypes ------------------------------*/
/*! \ingroup modbus
* \brief Initialize the Modbus Master protocol stack.
@@ -128,7 +145,7 @@ typedef enum
* - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error.
*/
eMBErrorCode eMBMasterSerialInit( eMBMode eMode, UCHAR ucPort,
ULONG ulBaudRate, eMBParity eParity );
ULONG ulBaudRate, eMBParity eParity );
/*! \ingroup modbus
* \brief Initialize the Modbus Master protocol stack for Modbus TCP.
@@ -220,7 +237,7 @@ eMBErrorCode eMBMasterPoll( void );
* valid it returns eMBErrorCode::MB_EINVAL.
*/
eMBErrorCode eMBMasterRegisterCB( UCHAR ucFunctionCode,
pxMBFunctionHandler pxHandler );
pxMBFunctionHandler pxHandler );
/* ----------------------- Callback -----------------------------------------*/
@@ -261,7 +278,7 @@ eMBErrorCode eMBMasterRegisterCB( UCHAR ucFunctionCode,
* <b>ILLEGAL DATA ADDRESS</b> is sent as a response.
*/
eMBErrorCode eMBMasterRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNRegs );
USHORT usNRegs );
/*! \ingroup modbus_registers
* \brief Callback function used if a <em>Holding Register</em> value is
@@ -290,7 +307,7 @@ eMBErrorCode eMBMasterRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress,
* <b>ILLEGAL DATA ADDRESS</b> is sent as a response.
*/
eMBErrorCode eMBMasterRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNRegs, eMBRegisterMode eMode );
USHORT usNRegs, eMBRegisterMode eMode );
/*! \ingroup modbus_registers
* \brief Callback function used if a <em>Coil Register</em> value is
@@ -319,7 +336,7 @@ eMBErrorCode eMBMasterRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress,
* <b>ILLEGAL DATA ADDRESS</b> is sent as a response.
*/
eMBErrorCode eMBMasterRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNCoils, eMBRegisterMode eMode );
USHORT usNCoils, eMBRegisterMode eMode );
/*! \ingroup modbus_registers
* \brief Callback function used if a <em>Input Discrete Register</em> value is
@@ -342,7 +359,7 @@ eMBErrorCode eMBMasterRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress,
* <b>ILLEGAL DATA ADDRESS</b> is sent as a response.
*/
eMBErrorCode eMBMasterRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress,
USHORT usNDiscrete );
USHORT usNDiscrete );
/*! \ingroup modbus
*\brief These Modbus functions are called for user when Modbus run in Master Mode.
@@ -353,20 +370,20 @@ eMBMasterReqErrCode
eMBMasterReqWriteHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usRegData, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqWriteMultipleHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr,
USHORT usNRegs, USHORT * pusDataBuffer, LONG lTimeOut );
USHORT usNRegs, USHORT * pusDataBuffer, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqReadHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usNRegs, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqReadWriteMultipleHoldingRegister( UCHAR ucSndAddr,
USHORT usReadRegAddr, USHORT usNReadRegs, USHORT * pusDataBuffer,
USHORT usWriteRegAddr, USHORT usNWriteRegs, LONG lTimeOut );
USHORT usReadRegAddr, USHORT usNReadRegs, USHORT * pusDataBuffer,
USHORT usWriteRegAddr, USHORT usNWriteRegs, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqReadCoils( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usNCoils, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqWriteCoil( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usCoilData, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqWriteMultipleCoils( UCHAR ucSndAddr,
USHORT usCoilAddr, USHORT usNCoils, UCHAR * pucDataBuffer, LONG lTimeOut );
USHORT usCoilAddr, USHORT usNCoils, UCHAR * pucDataBuffer, LONG lTimeOut );
eMBMasterReqErrCode
eMBMasterReqReadDiscreteInputs( UCHAR ucSndAddr, USHORT usDiscreteAddr, USHORT usNDiscreteIn, LONG lTimeOut );
@@ -409,6 +426,9 @@ eMBMasterErrorEventType eMBMasterGetErrorType( void );
void vMBMasterSetErrorType( eMBMasterErrorEventType errorType );
eMBMasterReqErrCode eMBMasterWaitRequestFinish( void );
eMBMode ucMBMasterGetCommMode( void );
BOOL xMBMasterGetLastTransactionInfo( uint64_t *pxTransId, UCHAR *pucDestAddress,
UCHAR *pucFunctionCode, UCHAR *pucException,
USHORT *pusErrorType );
/* ----------------------- Callback -----------------------------------------*/
+16 -11
View File
@@ -40,6 +40,7 @@
#include "mbconfig.h" // for options
#ifdef __cplusplus
PR_BEGIN_EXTERN_C
#endif
@@ -92,10 +93,10 @@ typedef enum {
} eMBMasterErrorEventType;
typedef struct _MbEventType {
eMBMasterEventEnum eEvent; /*!< event itself. */
uint64_t xTransactionId; /*!< ID of the transaction */
uint64_t xPostTimestamp; /*!< timestamp of event posted */
uint64_t xGetTimestamp; /*!< timestamp of event get */
eMBMasterEventEnum eEvent; /*!< event itself. */
uint64_t xTransactionId; /*!< ID of the transaction */
uint64_t xPostTimestamp; /*!< timestamp of event posted */
uint64_t xGetTimestamp; /*!< timestamp of event get */
} xMBMasterEventType;
#endif
@@ -207,16 +208,20 @@ void vMBMasterPortTimersDisable( void );
/* ----------------- Callback for the master error process ------------------*/
void vMBMasterErrorCBRespondTimeout( UCHAR ucDestAddress, const UCHAR* pucPDUData,
USHORT ucPDULength );
void vMBMasterErrorCBRespondTimeout( uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucSendData, USHORT ucSendLength );
void vMBMasterErrorCBReceiveData( UCHAR ucDestAddress, const UCHAR* pucPDUData,
USHORT ucPDULength );
void vMBMasterErrorCBReceiveData( uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength );
void vMBMasterErrorCBExecuteFunction( UCHAR ucDestAddress, const UCHAR* pucPDUData,
USHORT ucPDULength );
void vMBMasterErrorCBExecuteFunction( uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength );
void vMBMasterCBRequestSuccess( void );
void vMBMasterCBRequestSuccess( uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength );
#endif
/* ----------------------- Callback for the protocol stack ------------------*/
/*!
+121 -58
View File
@@ -36,15 +36,14 @@
*/
/* ----------------------- System includes ----------------------------------*/
#include <stdatomic.h>
#include <stdlib.h>
#include <string.h>
#include <stdatomic.h>
/* ----------------------- Platform includes --------------------------------*/
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb_m.h"
#include "mbconfig.h"
#include "mbframe.h"
@@ -69,20 +68,29 @@
#define MB_PORT_HAS_CLOSE 1
#endif
/* ----------------------- Static variables ---------------------------------*/
static UCHAR ucMBMasterDestAddress;
static BOOL xMBRunInMasterMode = FALSE;
static volatile eMBMasterErrorEventType eMBMasterCurErrorType;
static volatile USHORT usMasterSendPDULength;
static volatile eMBMode eMBMasterCurrentMode;
/*------------------------ Shared variables ---------------------------------*/
_lock_t xMBMLock; // base modbus object lock
volatile UCHAR ucMasterSndBuf[MB_SERIAL_BUF_SIZE];
volatile UCHAR ucMasterRcvBuf[MB_SERIAL_BUF_SIZE];
volatile eMBMasterTimerMode eMasterCurTimerMode;
volatile BOOL xFrameIsBroadcast = FALSE;
static _Atomic USHORT usMasterSendPDULength = 0;
static _Atomic eMBMasterErrorEventType eMBMasterCurErrorType = EV_ERROR_INIT;
static _Atomic BOOL xMBRunInMasterMode = FALSE;
static _Atomic UCHAR ucMBMasterDestAddress = 0;
static _Atomic BOOL xFrameIsBroadcast = FALSE;
static _Atomic eMBMasterTimerMode eMasterCurTimerMode;
/* ----------------------- Static variables ---------------------------------*/
static uint64_t xCurTransactionId = 0;
static UCHAR *pucMBSendFrame = NULL;
static UCHAR *pucMBRecvFrame = NULL;
static UCHAR ucRecvAddress = 0;
static eMBMode eMBMasterCurrentMode;
/* The transaction information structure which keep last processing state */
static TransactionInfo_t xTransactionInfo = {0};
static enum
{
@@ -172,9 +180,21 @@ eMBMasterTCPInit( USHORT ucTCPPort )
peMBMasterFrameSendCur = eMBMasterTCPSend;
pxMBMasterPortCBTimerExpired = xMBMasterTCPTimerExpired;
pvMBMasterFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBMasterTCPPortClose : NULL;
ucMBMasterDestAddress = MB_TCP_PSEUDO_ADDRESS;
eMBMasterCurrentMode = MB_TCP;
eMBState = STATE_DISABLED;
ucRecvAddress = MB_TCP_PSEUDO_ADDRESS;
xCurTransactionId = 0;
xTransactionInfo.xTransId = 0;
xTransactionInfo.ucDestAddr = 0;
xTransactionInfo.ucFuncCode = 0;
xTransactionInfo.eException = MB_EX_NONE;
xTransactionInfo.ucFrameError = 0;
/* initialize the state values. */
atomic_init(&usMasterSendPDULength, 0);
atomic_init(&eMBMasterCurErrorType, EV_ERROR_INIT);
atomic_init(&xMBRunInMasterMode, FALSE);
atomic_init(&ucMBMasterDestAddress, MB_TCP_PSEUDO_ADDRESS);
// initialize the OS resource for modbus master.
vMBMasterOsResInit();
@@ -240,6 +260,19 @@ eMBMasterSerialInit( eMBMode eMode, UCHAR ucPort, ULONG ulBaudRate, eMBParity eP
else
{
eMBState = STATE_DISABLED;
ucRecvAddress = 0;
xCurTransactionId = 0;
xTransactionInfo.xTransId = 0;
xTransactionInfo.ucDestAddr = 0;
xTransactionInfo.ucFuncCode = 0;
xTransactionInfo.eException = MB_EX_NONE;
xTransactionInfo.ucFrameError = 0;
/* initialize the state values. */
atomic_init(&usMasterSendPDULength, 0);
atomic_init(&eMBMasterCurErrorType, EV_ERROR_INIT);
atomic_init(&xMBRunInMasterMode, FALSE);
atomic_init(&ucMBMasterDestAddress, 0);
}
/* initialize the OS resource for modbus master. */
vMBMasterOsResInit();
@@ -311,18 +344,14 @@ eMBMasterDisable( void )
eMBErrorCode
eMBMasterPoll( void )
{
static UCHAR *ucMBSendFrame = NULL;
static UCHAR *ucMBRcvFrame = NULL;
static UCHAR ucRcvAddress;
static UCHAR ucFunctionCode;
static USHORT usLength;
static eMBException eException;
static uint64_t xCurTransactionId = 0;
int i;
int j;
eMBErrorCode eStatus = MB_ENOERR;
int i;
int j;
eMBErrorCode eStatus = MB_ENOERR;
xMBMasterEventType xEvent;
eMBMasterErrorEventType errorType;
eMBMasterErrorEventType errorType = EV_ERROR_INIT;
static eMBException eException = MB_EX_NONE;
static UCHAR ucFunctionCode = 0;
static USHORT usRecvLength = 0;
/* Check if the protocol stack is ready. */
if( eMBState != STATE_ENABLED ) {
@@ -343,9 +372,9 @@ eMBMasterPoll( void )
case EV_MASTER_FRAME_TRANSMIT:
ESP_LOGD(MB_PORT_TAG, "%" PRIu64 ":EV_MASTER_FRAME_TRANSMIT", xEvent.xTransactionId);
/* Master is busy now. */
vMBMasterGetPDUSndBuf( &ucMBSendFrame );
ESP_LOG_BUFFER_HEX_LEVEL("POLL transmit buffer", (void*)ucMBSendFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG);
eStatus = peMBMasterFrameSendCur( ucMBMasterGetDestAddress(), ucMBSendFrame, usMBMasterGetPDUSndLength() );
vMBMasterGetPDUSndBuf( &pucMBSendFrame );
ESP_LOG_BUFFER_HEX_LEVEL("POLL transmit buffer", (void*)pucMBSendFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG);
eStatus = peMBMasterFrameSendCur( ucMBMasterGetDestAddress(), pucMBSendFrame, usMBMasterGetPDUSndLength() );
if (eStatus != MB_ENOERR) {
vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA);
( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS );
@@ -356,24 +385,24 @@ eMBMasterPoll( void )
case EV_MASTER_FRAME_SENT:
if (xCurTransactionId == xEvent.xTransactionId) {
ESP_LOGD( MB_PORT_TAG, "%" PRIu64 ":EV_MASTER_FRAME_SENT", xEvent.xTransactionId );
ESP_LOG_BUFFER_HEX_LEVEL("POLL sent buffer", (void*)ucMBSendFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG);
ESP_LOG_BUFFER_HEX_LEVEL("POLL sent buffer", (void*)pucMBSendFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG);
}
break;
case EV_MASTER_FRAME_RECEIVED:
ESP_LOGD( MB_PORT_TAG, "%" PRIu64 ":EV_MASTER_FRAME_RECEIVED", xEvent.xTransactionId );
eStatus = peMBMasterFrameReceiveCur( &ucRcvAddress, &ucMBRcvFrame, &usLength);
eStatus = peMBMasterFrameReceiveCur( &ucRecvAddress, &pucMBRecvFrame, &usRecvLength);
if (xCurTransactionId == xEvent.xTransactionId) {
MB_PORT_CHECK(ucMBSendFrame, MB_EILLSTATE, "Send buffer initialization fail.");
MB_PORT_CHECK(pucMBSendFrame, MB_EILLSTATE, "Send buffer initialization fail.");
// Check if the frame is for us. If not ,send an error process event.
if ( ( eStatus == MB_ENOERR ) && ( ( ucRcvAddress == ucMBMasterGetDestAddress() )
|| ( ucRcvAddress == MB_TCP_PSEUDO_ADDRESS) ) ) {
if ( ( ucMBRcvFrame[MB_PDU_FUNC_OFF] & ~MB_FUNC_ERROR ) == ( ucMBSendFrame[MB_PDU_FUNC_OFF] ) ) {
if ( ( eStatus == MB_ENOERR ) && ( ( ucRecvAddress == ucMBMasterGetDestAddress() )
|| ( ucRecvAddress == MB_TCP_PSEUDO_ADDRESS) ) ) {
if ( ( pucMBRecvFrame[MB_PDU_FUNC_OFF] & ~MB_FUNC_ERROR ) == ( pucMBSendFrame[MB_PDU_FUNC_OFF] ) ) {
ESP_LOGD(MB_PORT_TAG, "%" PRIu64 ": Packet data received successfully (%u).", xEvent.xTransactionId, (unsigned)eStatus);
ESP_LOG_BUFFER_HEX_LEVEL("POLL receive buffer", (void*)ucMBRcvFrame, (uint16_t)usLength, ESP_LOG_DEBUG);
ESP_LOG_BUFFER_HEX_LEVEL("POLL receive buffer", (void*)pucMBRecvFrame, (uint16_t)usRecvLength, ESP_LOG_DEBUG);
( void ) xMBMasterPortEventPost( EV_MASTER_EXECUTE );
} else {
ESP_LOGE( MB_PORT_TAG, "Drop incorrect frame, receive_func(%u) != send_func(%u)",
ucMBRcvFrame[MB_PDU_FUNC_OFF], ucMBSendFrame[MB_PDU_FUNC_OFF]);
pucMBRecvFrame[MB_PDU_FUNC_OFF], pucMBSendFrame[MB_PDU_FUNC_OFF]);
vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA);
( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS );
}
@@ -381,7 +410,7 @@ eMBMasterPoll( void )
vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA);
( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS );
ESP_LOGD( MB_PORT_TAG, "%" PRIu64 ": Packet data receive failed (addr=%u)(%u).",
xEvent.xTransactionId, (unsigned)ucRcvAddress, (unsigned)eStatus);
xEvent.xTransactionId, (unsigned)ucRecvAddress, (unsigned)eStatus);
}
} else {
// Ignore the `EV_MASTER_FRAME_RECEIVED` event because the respond timeout occurred
@@ -393,15 +422,15 @@ eMBMasterPoll( void )
if (xCurTransactionId == xEvent.xTransactionId) {
if ( xMBMasterRequestIsBroadcast()
&& (( ucMBMasterGetCommMode() == MB_RTU ) || ( ucMBMasterGetCommMode() == MB_ASCII ) ) ) {
ucMBRcvFrame = ucMBSendFrame;
pucMBRecvFrame = pucMBSendFrame;
}
MB_PORT_CHECK(ucMBRcvFrame, MB_EILLSTATE, "receive buffer initialization fail.");
MB_PORT_CHECK(pucMBRecvFrame, MB_EILLSTATE, "receive buffer initialization fail.");
ESP_LOGD(MB_PORT_TAG, "%" PRIu64 ":EV_MASTER_EXECUTE", xEvent.xTransactionId);
ucFunctionCode = ucMBRcvFrame[MB_PDU_FUNC_OFF];
ucFunctionCode = pucMBRecvFrame[MB_PDU_FUNC_OFF];
eException = MB_EX_ILLEGAL_FUNCTION;
/* If receive frame has exception. The receive function code highest bit is 1.*/
if (ucFunctionCode & MB_FUNC_ERROR) {
eException = (eMBException)ucMBRcvFrame[MB_PDU_DATA_OFF];
eException = (eMBException)pucMBRecvFrame[MB_PDU_DATA_OFF];
} else {
for ( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
{
@@ -415,14 +444,14 @@ eMBMasterPoll( void )
* the master need execute function for all slave.
*/
if ( xMBMasterRequestIsBroadcast() ) {
usLength = usMBMasterGetPDUSndLength();
USHORT usLength = usMBMasterGetPDUSndLength();
for(j = 1; j <= MB_MASTER_TOTAL_SLAVE_NUM; j++)
{
vMBMasterSetDestAddress(j);
eException = xMasterFuncHandlers[i].pxHandler(ucMBRcvFrame, &usLength);
eException = xMasterFuncHandlers[i].pxHandler(pucMBRecvFrame, &usLength);
}
} else {
eException = xMasterFuncHandlers[i].pxHandler( ucMBRcvFrame, &usLength );
eException = xMasterFuncHandlers[i].pxHandler(pucMBRecvFrame, &usRecvLength);
}
vMBMasterSetCBRunInMasterMode( FALSE );
break;
@@ -449,23 +478,31 @@ eMBMasterPoll( void )
ESP_LOGD( MB_PORT_TAG, "%" PRIu64 ":EV_MASTER_ERROR_PROCESS", xEvent.xTransactionId);
/* Execute specified error process callback function. */
errorType = eMBMasterGetErrorType( );
vMBMasterGetPDUSndBuf( &ucMBSendFrame );
vMBMasterGetPDUSndBuf( &pucMBSendFrame );
switch ( errorType )
{
case EV_ERROR_RESPOND_TIMEOUT:
vMBMasterErrorCBRespondTimeout( ucMBMasterGetDestAddress( ),
ucMBSendFrame, usMBMasterGetPDUSndLength( ) );
vMBMasterErrorCBRespondTimeout( xEvent.xTransactionId,
ucMBMasterGetDestAddress( ),
pucMBSendFrame, usMBMasterGetPDUSndLength( ) );
break;
case EV_ERROR_RECEIVE_DATA:
vMBMasterErrorCBReceiveData( ucMBMasterGetDestAddress( ),
ucMBSendFrame, usMBMasterGetPDUSndLength( ) );
vMBMasterErrorCBReceiveData( xEvent.xTransactionId,
ucMBMasterGetDestAddress( ),
pucMBRecvFrame, usRecvLength,
pucMBSendFrame, usMBMasterGetPDUSndLength( ) );
break;
case EV_ERROR_EXECUTE_FUNCTION:
vMBMasterErrorCBExecuteFunction( ucMBMasterGetDestAddress( ),
ucMBSendFrame, usMBMasterGetPDUSndLength( ) );
vMBMasterErrorCBExecuteFunction( xEvent.xTransactionId,
ucMBMasterGetDestAddress( ),
pucMBRecvFrame, usRecvLength,
pucMBSendFrame, usMBMasterGetPDUSndLength( ) );
break;
case EV_ERROR_OK:
vMBMasterCBRequestSuccess( );
vMBMasterCBRequestSuccess( xEvent.xTransactionId,
ucMBMasterGetDestAddress( ),
pucMBRecvFrame, usRecvLength,
pucMBSendFrame, usMBMasterGetPDUSndLength( ) );
break;
default:
ESP_LOGE( MB_PORT_TAG, "%" PRIu64 ":incorrect error type = %d.", xEvent.xTransactionId, (int)errorType);
@@ -475,6 +512,13 @@ eMBMasterPoll( void )
vMBMasterPortTimersDisable( );
uint64_t xProcTime = xCurTransactionId ? ( xEvent.xPostTimestamp - xCurTransactionId ) : 0;
ESP_LOGD( MB_PORT_TAG, "Transaction (%" PRIu64 "), processing time(us) = %" PRId64, xCurTransactionId, xProcTime );
MB_ATOMIC_SECTION {
xTransactionInfo.xTransId = xCurTransactionId;
xTransactionInfo.ucDestAddr = ucMBMasterGetDestAddress();
xTransactionInfo.ucFuncCode = ucFunctionCode;
xTransactionInfo.eException = eException;
xTransactionInfo.ucFrameError = errorType;
}
xCurTransactionId = 0;
vMBMasterSetErrorType( EV_ERROR_INIT );
vMBMasterRunResRelease( );
@@ -500,7 +544,7 @@ BOOL xMBMasterGetCBRunInMasterMode( void )
// Set whether the Modbus Master is run in master mode.
void vMBMasterSetCBRunInMasterMode( BOOL IsMasterMode )
{
atomic_store(&(xMBRunInMasterMode), IsMasterMode);
atomic_store(&xMBRunInMasterMode, IsMasterMode);
}
// Get Modbus Master send destination address.
@@ -512,7 +556,7 @@ UCHAR ucMBMasterGetDestAddress( void )
// Set Modbus Master send destination address.
void vMBMasterSetDestAddress( UCHAR Address )
{
atomic_store(&(ucMBMasterDestAddress), Address);
atomic_store(&ucMBMasterDestAddress, Address);
}
// Get Modbus Master current error event type.
@@ -524,7 +568,7 @@ eMBMasterErrorEventType inline eMBMasterGetErrorType( void )
// Set Modbus Master current error event type.
void IRAM_ATTR vMBMasterSetErrorType( eMBMasterErrorEventType errorType )
{
atomic_store(&(eMBMasterCurErrorType), errorType);
atomic_store(&eMBMasterCurErrorType, errorType);
}
/* Get Modbus Master send PDU's buffer address pointer.*/
@@ -536,7 +580,7 @@ void vMBMasterGetPDUSndBuf( UCHAR ** pucFrame )
/* Set Modbus Master send PDU's buffer length.*/
void vMBMasterSetPDUSndLength( USHORT SendPDULength )
{
atomic_store(&(usMasterSendPDULength), SendPDULength);
atomic_store(&usMasterSendPDULength, SendPDULength);
}
/* Get Modbus Master send PDU's buffer length.*/
@@ -548,7 +592,7 @@ USHORT usMBMasterGetPDUSndLength( void )
/* Set Modbus Master current timer mode.*/
void vMBMasterSetCurTimerMode( eMBMasterTimerMode eMBTimerMode )
{
atomic_store(&(eMasterCurTimerMode), eMBTimerMode);
atomic_store(&eMasterCurTimerMode, eMBTimerMode);
}
/* Get Modbus Master current timer mode.*/
@@ -560,13 +604,13 @@ eMBMasterTimerMode MB_PORT_ISR_ATTR xMBMasterGetCurTimerMode( void )
/* The master request is broadcast? */
BOOL MB_PORT_ISR_ATTR xMBMasterRequestIsBroadcast( void )
{
return xFrameIsBroadcast;
return atomic_load(&xFrameIsBroadcast);
}
/* The master request is broadcast? */
void vMBMasterRequestSetType( BOOL xIsBroadcast )
{
atomic_store(&(xFrameIsBroadcast), xIsBroadcast);
atomic_store(&xFrameIsBroadcast, xIsBroadcast);
}
// Get Modbus Master communication mode.
@@ -575,4 +619,23 @@ eMBMode ucMBMasterGetCommMode(void)
return eMBMasterCurrentMode;
}
/* Get current transaction information */
BOOL xMBMasterGetLastTransactionInfo( uint64_t *pxTransId, UCHAR *pucDestAddress,
UCHAR *pucFunctionCode, UCHAR *pucException,
USHORT *pusErrorType )
{
BOOL xState = (eMBState == STATE_ENABLED);
if (xState && pxTransId && pucDestAddress && pucFunctionCode
&& pucException && pusErrorType) {
MB_ATOMIC_SECTION {
*pxTransId = xTransactionInfo.xTransId;
*pucDestAddress = xTransactionInfo.ucDestAddr;
*pucFunctionCode = xTransactionInfo.ucFuncCode;
*pucException = xTransactionInfo.eException;
*pusErrorType = xTransactionInfo.ucFrameError;
}
}
return xState;
}
#endif // MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED
+13 -3
View File
@@ -39,7 +39,6 @@
/* ----------------------- Modbus includes ----------------------------------*/
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "sys/lock.h"
#include "port.h"
/* ----------------------- Variables ----------------------------------------*/
@@ -47,13 +46,24 @@ static _lock_t s_port_lock;
static UCHAR ucPortMode = 0;
/* ----------------------- Start implementation -----------------------------*/
inline void
INLINE int lock_obj(_lock_t *plock)
{
_lock_acquire(plock);
return 1;
}
INLINE void unlock_obj(_lock_t *plock)
{
_lock_release(plock);
}
INLINE void
vMBPortEnterCritical(void)
{
_lock_acquire(&s_port_lock);
}
inline void
INLINE void
vMBPortExitCritical(void)
{
_lock_release(&s_port_lock);
+50 -1
View File
@@ -37,6 +37,8 @@
#ifndef PORT_COMMON_H_
#define PORT_COMMON_H_
#include "sys/lock.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h" // for queue
@@ -52,7 +54,7 @@
#include "mbconfig.h"
#define INLINE inline
#define INLINE inline __attribute__((always_inline))
#define PR_BEGIN_EXTERN_C extern "C" {
#define PR_END_EXTERN_C }
@@ -105,6 +107,8 @@
#define MB_TCP_DEBUG (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) // Enable legacy debug output in TCP module.
#define MB_ATTR_WEAK __attribute__ ((weak))
#define MB_TCP_GET_FIELD(buffer, field) ((USHORT)((buffer[field] << 8U) | buffer[field + 1]))
#define MB_PORT_CHECK(a, ret_val, str, ...) \
@@ -121,6 +125,35 @@
} \
} while(0)
int lock_obj(_lock_t *plock);
void unlock_obj(_lock_t *plock);
#define CRITICAL_SECTION_INIT(lock) \
do \
{ \
_lock_init((_lock_t *)&lock); \
} while (0)
#define CRITICAL_SECTION_CLOSE(lock) \
do \
{ \
_lock_close((_lock_t *)&lock); \
} while (0)
#define CRITICAL_SECTION_LOCK(lock) \
do \
{ \
lock_obj((_lock_t *)&lock); \
} while (0)
#define CRITICAL_SECTION_UNLOCK(lock) \
do \
{ \
unlock_obj((_lock_t *)&lock); \
} while (0)
#define CRITICAL_SECTION(lock) for (int st = lock_obj((_lock_t *)&lock); (st > 0); unlock_obj((_lock_t *)&lock), st = -1)
#ifdef __cplusplus
PR_BEGIN_EXTERN_C
#endif /* __cplusplus */
@@ -198,6 +231,22 @@ UCHAR ucMBPortGetMode( void );
BOOL xMBPortSerialWaitEvent(QueueHandle_t xMbUartQueue, uart_event_t* pxEvent, ULONG xTimeout);
/**
* This is modbus master user error handling funcion.
* If it is defined in the user application, then helps to handle the errors
* and received/sent buffers to transfer as well as handle the slave exception codes.
*
* @param xTransId - the identification of the trasaction
* @param ucDestAddress destination salve address
* @param usError - the error code, see the enumeration eMBMasterErrorEventType
* @param pucRecvData current receive data pointer
* @param ucRecvLength current length of receive buffer
* @param pucSendData Send buffer data
* @param ucSendLength Send buffer length
*/
void vMBMasterErrorCBUserHandler( uint64_t xTransId, USHORT usError, UCHAR ucDestAddress, const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength ) MB_ATTR_WEAK;
#ifdef __cplusplus
PR_END_EXTERN_C
#endif /* __cplusplus */
+59 -16
View File
@@ -35,7 +35,6 @@
*/
/* ----------------------- Modbus includes ----------------------------------*/
#include <stdatomic.h>
#include "freertos/FreeRTOS.h"
@@ -66,7 +65,7 @@ static EventGroupHandle_t xEventGroupMasterHdl;
static EventGroupHandle_t xEventGroupMasterConfirmHdl;
static QueueHandle_t xQueueMasterHdl;
static uint64_t xTransactionID = 0;
static _Atomic uint64_t xTransactionID = 0;
/* ----------------------- Start implementation -----------------------------*/
@@ -80,7 +79,7 @@ xMBMasterPortEventInit( void )
xQueueMasterHdl = xQueueCreate(MB_EVENT_QUEUE_SIZE, sizeof(xMBMasterEventType));
MB_PORT_CHECK(xQueueMasterHdl, FALSE, "mb stack event group creation error.");
vQueueAddToRegistry(xQueueMasterHdl, "MbMasterPortEventQueue");
xTransactionID = 0;
atomic_init(&xTransactionID, 0);
return TRUE;
}
@@ -191,30 +190,49 @@ void vMBMasterRunResRelease( void )
* This is modbus master respond timeout error process callback function.
* @note There functions will block modbus master poll while execute OS waiting.
*
* @param xTransId - the identification of the trasaction
* @param ucDestAddress destination salve address
* @param pucPDUData PDU buffer data
* @param ucPDULength PDU buffer length
* @param pucRecvData current receive data pointer
* @param ucRecvLength current length of receive buffer
* @param pucSendData Send buffer data
* @param ucSendLength Send buffer length
*
*/
void vMBMasterErrorCBRespondTimeout(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength)
void vMBMasterErrorCBRespondTimeout(uint64_t xTransId, UCHAR ucDestAddress, const UCHAR* pucSendData, USHORT ucSendLength)
{
(void)xEventGroupSetBits( xEventGroupMasterHdl, EV_MASTER_ERROR_RESPOND_TIMEOUT );
ESP_LOGD(MB_PORT_TAG,"%s:Callback respond timeout.", __func__);
if (vMBMasterErrorCBUserHandler) {
vMBMasterErrorCBUserHandler( xTransId,
(USHORT)EV_ERROR_RESPOND_TIMEOUT, ucDestAddress,
NULL, 0,
pucSendData, ucSendLength );
}
}
/**
* This is modbus master receive data error process callback function.
* @note There functions will block modbus master poll while execute OS waiting.
*
* @param xTransId - the identification of the trasaction
* @param ucDestAddress destination salve address
* @param pucPDUData PDU buffer data
* @param ucPDULength PDU buffer length
* @param pucRecvData current receive data pointer
* @param ucRecvLength current length of receive buffer
* @param pucSendData Send buffer data
* @param ucSendLength Send buffer length
*/
void vMBMasterErrorCBReceiveData(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength)
void vMBMasterErrorCBReceiveData(uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength)
{
(void)xEventGroupSetBits( xEventGroupMasterHdl, EV_MASTER_ERROR_RECEIVE_DATA );
ESP_LOGD(MB_PORT_TAG,"%s:Callback receive data timeout failure.", __func__);
ESP_LOG_BUFFER_HEX_LEVEL("Err rcv buf", (void *)pucPDUData, (USHORT)ucPDULength, ESP_LOG_DEBUG);
ESP_LOGD(MB_PORT_TAG,"%s:Callback receive data failure.", __func__);
if (vMBMasterErrorCBUserHandler) {
vMBMasterErrorCBUserHandler( xTransId,
(USHORT)EV_ERROR_RECEIVE_DATA, ucDestAddress,
pucRecvData, ucRecvLength,
pucSendData, ucSendLength );
}
}
/**
@@ -222,27 +240,52 @@ void vMBMasterErrorCBReceiveData(UCHAR ucDestAddress, const UCHAR* pucPDUData, U
* @note There functions will block modbus master poll while execute OS waiting.
* So,for real-time of system.Do not execute too much waiting process.
*
* @param xTransId - the identification of the trasaction
* @param ucDestAddress destination salve address
* @param pucPDUData PDU buffer data
* @param ucPDULength PDU buffer length
* @param pucRecvData current receive data pointer
* @param ucRecvLength current length of receive buffer
* @param pucSendData Send buffer data
* @param ucSendLength Send buffer length
*
*/
void vMBMasterErrorCBExecuteFunction(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength)
void vMBMasterErrorCBExecuteFunction(uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength)
{
xEventGroupSetBits( xEventGroupMasterHdl, EV_MASTER_ERROR_EXECUTE_FUNCTION );
ESP_LOGD(MB_PORT_TAG,"%s:Callback execute data handler failure.", __func__);
ESP_LOG_BUFFER_HEX_LEVEL("Exec func buf", (void*)pucPDUData, (USHORT)ucPDULength, ESP_LOG_DEBUG);
if (vMBMasterErrorCBUserHandler) {
vMBMasterErrorCBUserHandler( xTransId,
(USHORT)EV_ERROR_EXECUTE_FUNCTION, ucDestAddress,
pucRecvData, ucRecvLength,
pucSendData, ucSendLength );
}
}
/**
* This is modbus master request process success callback function.
* @note There functions will block modbus master poll while execute OS waiting.
* So,for real-time of system. Do not execute too much waiting process.
*
* @param xTransId - the identification of the trasaction
* @param ucDestAddress destination salve address
* @param pucRecvData current receive data pointer
* @param ucRecvLength current length of receive buffer
* @param pucSendData Send buffer data
* @param ucSendLength Send buffer length
*/
void vMBMasterCBRequestSuccess( void )
void vMBMasterCBRequestSuccess(uint64_t xTransId, UCHAR ucDestAddress,
const UCHAR* pucRecvData, USHORT ucRecvLength,
const UCHAR* pucSendData, USHORT ucSendLength)
{
(void)xEventGroupSetBits( xEventGroupMasterHdl, EV_MASTER_PROCESS_SUCCESS );
ESP_LOGD(MB_PORT_TAG,"%s: Callback request success.", __func__);
if (vMBMasterErrorCBUserHandler) {
vMBMasterErrorCBUserHandler( xTransId,
(USHORT)EV_ERROR_OK, ucDestAddress,
pucRecvData, ucRecvLength,
pucSendData, ucSendLength );
}
}
/**