diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4eb6c2eff..383dbd8d9 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -296,6 +296,7 @@ build_docs: - docs/en/sphinx-warning-log.txt - docs/en/sphinx-warning-log-sanitized.txt - docs/en/_build/html + - docs/sphinx-err-* # Chinese version of documentation - docs/zh_CN/doxygen-warning-log.txt - docs/zh_CN/sphinx-warning-log.txt @@ -307,7 +308,7 @@ build_docs: - ./check_lang_folder_sync.sh - cd en - make gh-linkcheck - - make html + - make html || cat /tmp/sphinx-err*.log - ../check_doc_warnings.sh - cd ../zh_CN - make gh-linkcheck diff --git a/components/freemodbus/CMakeLists.txt b/components/freemodbus/CMakeLists.txt new file mode 100644 index 000000000..80eba174f --- /dev/null +++ b/components/freemodbus/CMakeLists.txt @@ -0,0 +1,26 @@ +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) +set(COMPONENT_SRCS "modbus/ascii/mbascii.c" + "modbus/rtu/mbcrc.c" + "modbus/functions/mbfunccoils.c" + "modbus/functions/mbfuncdiag.c" + "modbus/functions/mbfuncdisc.c" + "modbus/functions/mbfuncholding.c" + "modbus/functions/mbfuncinput.c" + "modbus/functions/mbfuncother.c" + "modbus/rtu/mbrtu.c" + "modbus/tcp/mbtcp.c" + "modbus/functions/mbutils.c" + "port/portevent.c" + "port/portother.c" + "port/portserial.c" + "port/porttimer.c" + "modbus_controller/mbcontroller.c" + "modbus/mb.c") + +set(COMPONENT_ADD_INCLUDEDIRS modbus/include modbus_controller) +set(COMPONENT_PRIV_INCLUDEDIRS modbus port modbus/ascii modbus/functions modbus/rtu modbus/include) +set(COMPONENT_REQUIRES "driver") + +register_component() diff --git a/components/freemodbus/Kconfig b/components/freemodbus/Kconfig new file mode 100644 index 000000000..fd4314bec --- /dev/null +++ b/components/freemodbus/Kconfig @@ -0,0 +1,133 @@ +menu "Modbus configuration" + +config MB_UART_RXD + int "UART RXD pin number" + range 0 34 + default 22 + help + GPIO number for UART RX pin. See UART documentation for more information + about available pin numbers for UART. + +config MB_UART_TXD + int "UART TXD pin number" + range 0 34 + default 23 + help + GPIO number for UART TX pin. See UART documentation for more information + about available pin numbers for UART. + +config MB_UART_RTS + int "UART RTS pin number" + range 0 34 + default 18 + help + GPIO number for UART RTS pin. This pin is connected to + ~RE/DE pin of RS485 transceiver to switch direction. + +config MB_QUEUE_LENGTH + int "Modbus serial task queue length" + range 0 200 + default 20 + help + Modbus serial driver queue length. It is used by event queue task. + See the serial driver API for more information. + +config MB_SERIAL_TASK_STACK_SIZE + int "Modbus serial task stack size" + range 768 8192 + default 2048 + help + Modbus serial task stack size for event queue task. + It may be adjusted when debugging is enabled (for example). + +config MB_SERIAL_BUF_SIZE + int "Modbus serial task RX/TX buffer size" + range 0 2048 + default 256 + help + Modbus serial task RX and TX buffer size for UART driver initialization. + This buffer is used for modbus frame transfer. The Modbus protocol maximum + frame size is 256 bytes. Bigger size can be used for non standard implementations. + +config MB_SERIAL_TASK_PRIO + int "Modbus serial task priority" + range 3 10 + default 10 + help + Modbus UART driver event task priority. + The priority of Modbus controller task is equal to (CONFIG_MB_SERIAL_TASK_PRIO - 1). + +config MB_CONTROLLER_SLAVE_ID_SUPPORT + bool "Modbus controller slave ID support" + default n + help + Modbus slave ID support enable. + When enabled the Modbus command is supported by stack. + +config MB_CONTROLLER_SLAVE_ID + hex "Modbus controller slave ID" + range 0 4294967295 + default 0x00112233 + depends on MB_CONTROLLER_SLAVE_ID_SUPPORT + help + Modbus slave ID value to identify modbus device + in the network using command. + Most significant byte of ID is used as short device ID and + other three bytes used as long ID. + +config MB_CONTROLLER_NOTIFY_TIMEOUT + int "Modbus controller notification timeout (ms)" + range 0 200 + default 20 + help + Modbus controller notification timeout in milliseconds. + This timeout is used to send notification about accessed parameters. + +config MB_CONTROLLER_NOTIFY_QUEUE_SIZE + int "Modbus controller notification queue size" + range 0 200 + default 20 + help + Modbus controller notification queue size. + The notification queue is used to get information about accessed parameters. + +config MB_CONTROLLER_STACK_SIZE + int "Modbus controller stack size" + range 0 8192 + default 4096 + help + Modbus controller task stack size. The Stack size may be adjusted when + debug mode is used which requires more stack size (for example). + +config MB_EVENT_QUEUE_TIMEOUT + int "Modbus stack event queue timeout (ms)" + range 0 500 + default 20 + help + Modbus stack event queue timeout in milliseconds. This may help to optimize + Modbus stack event processing time. + +config MB_TIMER_PORT_ENABLED + bool "Modbus stack use timer for 3.5T symbol time measurement" + default y + help + If this option is set the Modbus stack uses timer for T3.5 time measurement. + Else the internal UART TOUT timeout is used for 3.5T symbol time measurement. + +config MB_TIMER_GROUP + int "Modbus Timer group number" + range 0 1 + depends on MB_TIMER_PORT_ENABLED + default 0 + help + Modbus Timer group number that is used for timeout measurement. + +config MB_TIMER_INDEX + int "Modbus Timer index in the group" + range 0 1 + depends on MB_TIMER_PORT_ENABLED + default 0 + help + Modbus Timer Index in the group that is used for timeout measurement. + +endmenu diff --git a/components/freemodbus/component.mk b/components/freemodbus/component.mk new file mode 100644 index 000000000..c4f3a55b0 --- /dev/null +++ b/components/freemodbus/component.mk @@ -0,0 +1,3 @@ +COMPONENT_ADD_INCLUDEDIRS := modbus/include modbus_controller +COMPONENT_PRIV_INCLUDEDIRS := . modbus port modbus/ascii modbus/functions modbus/rtu modbus/include +COMPONENT_SRCDIRS := . modbus port modbus/ascii modbus/functions modbus/rtu modbus_controller \ No newline at end of file diff --git a/components/freemodbus/modbus/ascii/mbascii.c b/components/freemodbus/modbus/ascii/mbascii.c new file mode 100644 index 000000000..c513457ea --- /dev/null +++ b/components/freemodbus/modbus/ascii/mbascii.c @@ -0,0 +1,486 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbascii.c,v 1.17 2010/06/06 13:47:07 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbascii.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +#if MB_ASCII_ENABLED > 0 + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_ASCII_DEFAULT_CR '\r' /*!< Default CR character for Modbus ASCII. */ +#define MB_ASCII_DEFAULT_LF '\n' /*!< Default LF character for Modbus ASCII. */ +#define MB_SER_PDU_SIZE_MIN 3 /*!< Minimum size of a Modbus ASCII frame. */ +#define MB_SER_PDU_SIZE_MAX 256 /*!< Maximum size of a Modbus ASCII frame. */ +#define MB_SER_PDU_SIZE_LRC 1 /*!< Size of LRC field in PDU. */ +#define MB_SER_PDU_ADDR_OFF 0 /*!< Offset of slave address in Ser-PDU. */ +#define MB_SER_PDU_PDU_OFF 1 /*!< Offset of Modbus-PDU in Ser-PDU. */ + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_RX_RCV, /*!< Frame is beeing received. */ + STATE_RX_WAIT_EOF /*!< Wait for End of Frame. */ +} eMBRcvState; + +typedef enum +{ + STATE_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_TX_START, /*!< Starting transmission (':' sent). */ + STATE_TX_DATA, /*!< Sending of data (Address, Data, LRC). */ + STATE_TX_END, /*!< End of transmission. */ + STATE_TX_NOTIFY /*!< Notify sender that the frame has been sent. */ +} eMBSndState; + +typedef enum +{ + BYTE_HIGH_NIBBLE, /*!< Character for high nibble of byte. */ + BYTE_LOW_NIBBLE /*!< Character for low nibble of byte. */ +} eMBBytePos; + +/* ----------------------- Static functions ---------------------------------*/ +static UCHAR prvucMBCHAR2BIN( UCHAR ucCharacter ); + +static UCHAR prvucMBBIN2CHAR( UCHAR ucByte ); + +static UCHAR prvucMBLRC( UCHAR * pucFrame, USHORT usLen ); + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBSndState eSndState; +static volatile eMBRcvState eRcvState; + +/* We reuse the Modbus RTU buffer because only one buffer is needed and the + * RTU buffer is bigger. */ +extern volatile UCHAR ucRTUBuf[]; +static volatile UCHAR *ucASCIIBuf = ucRTUBuf; + +static volatile USHORT usRcvBufferPos; +static volatile eMBBytePos eBytePos; + +static volatile UCHAR *pucSndBufferCur; +static volatile USHORT usSndBufferCount; + +static volatile UCHAR ucLRC; +static volatile UCHAR ucMBLFCharacter; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBASCIIInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + ( void )ucSlaveAddress; + + ENTER_CRITICAL_SECTION( ); + ucMBLFCharacter = MB_ASCII_DEFAULT_LF; + + if( xMBPortSerialInit( ucPort, ulBaudRate, 7, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else if( xMBPortTimersInit( MB_ASCII_TIMEOUT_SEC * 20000UL ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBASCIIStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( TRUE, FALSE ); + eRcvState = STATE_RX_IDLE; + EXIT_CRITICAL_SECTION( ); + + /* No special startup required for ASCII. */ + ( void )xMBPortEventPost( EV_READY ); +} + +void +eMBASCIIStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( FALSE, FALSE ); + vMBPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +eMBErrorCode +eMBASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN ) + && ( prvucMBLRC( ( UCHAR * ) ucASCIIBuf, usRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucASCIIBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_LRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucASCIIBuf[MB_SER_PDU_PDU_OFF]; + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +eMBErrorCode +eMBASCIISend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR usLRC; + + ENTER_CRITICAL_SECTION( ); + /* Check if the receiver is still in idle state. If not we where too + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if( eRcvState == STATE_RX_IDLE ) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucSndBufferCur = ( UCHAR * ) pucFrame - 1; + usSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usSndBufferCount += usLength; + + /* Calculate LRC checksum for Modbus-Serial-Line-PDU. */ + usLRC = prvucMBLRC( ( UCHAR * ) pucSndBufferCur, usSndBufferCount ); + ucASCIIBuf[usSndBufferCount++] = usLRC; + + /* Activate the transmitter. */ + eSndState = STATE_TX_START; + vMBPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBASCIIReceiveFSM( void ) +{ + BOOL xNeedPoll = FALSE; + UCHAR ucByte; + UCHAR ucResult; + + assert( eSndState == STATE_TX_IDLE ); + + ( void )xMBPortSerialGetByte( ( CHAR * ) & ucByte ); + switch ( eRcvState ) + { + /* A new character is received. If the character is a ':' the input + * buffer is cleared. A CR-character signals the end of the data + * block. Other characters are part of the data block and their + * ASCII value is converted back to a binary representation. + */ + case STATE_RX_RCV: + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + if( ucByte == ':' ) + { + /* Empty receive buffer. */ + eBytePos = BYTE_HIGH_NIBBLE; + usRcvBufferPos = 0; + } + else if( ucByte == MB_ASCII_DEFAULT_CR ) + { + eRcvState = STATE_RX_WAIT_EOF; + } + else + { + ucResult = prvucMBCHAR2BIN( ucByte ); + switch ( eBytePos ) + { + /* High nibble of the byte comes first. We check for + * a buffer overflow here. */ + case BYTE_HIGH_NIBBLE: + if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + ucASCIIBuf[usRcvBufferPos] = ( UCHAR )( ucResult << 4 ); + eBytePos = BYTE_LOW_NIBBLE; + break; + } + else + { + /* not handled in Modbus specification but seems + * a resonable implementation. */ + eRcvState = STATE_RX_IDLE; + /* Disable previously activated timer because of error state. */ + vMBPortTimersDisable( ); + } + break; + + case BYTE_LOW_NIBBLE: + ucASCIIBuf[usRcvBufferPos] |= ucResult; + usRcvBufferPos++; + eBytePos = BYTE_HIGH_NIBBLE; + break; + } + } + break; + + case STATE_RX_WAIT_EOF: + if( ucByte == ucMBLFCharacter ) + { + /* Disable character timeout timer because all characters are + * received. */ + vMBPortTimersDisable( ); + /* Receiver is again in idle state. */ + eRcvState = STATE_RX_IDLE; + + /* Notify the caller of eMBASCIIReceive that a new frame + * was received. */ + xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED ); + } + else if( ucByte == ':' ) + { + /* Empty receive buffer and back to receive state. */ + eBytePos = BYTE_HIGH_NIBBLE; + usRcvBufferPos = 0; + eRcvState = STATE_RX_RCV; + + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + } + else + { + /* Frame is not okay. Delete entire frame. */ + eRcvState = STATE_RX_IDLE; + } + break; + + case STATE_RX_IDLE: + if( ucByte == ':' ) + { + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + /* Reset the input buffers to store the frame. */ + usRcvBufferPos = 0;; + eBytePos = BYTE_HIGH_NIBBLE; + eRcvState = STATE_RX_RCV; + } + break; + } + + return xNeedPoll; +} + +BOOL +xMBASCIITransmitFSM( void ) +{ + BOOL xNeedPoll = FALSE; + UCHAR ucByte; + + assert( eRcvState == STATE_RX_IDLE ); + switch ( eSndState ) + { + /* Start of transmission. The start of a frame is defined by sending + * the character ':'. */ + case STATE_TX_START: + ucByte = ':'; + xMBPortSerialPutByte( ( CHAR )ucByte ); + eSndState = STATE_TX_DATA; + eBytePos = BYTE_HIGH_NIBBLE; + break; + + /* Send the data block. Each data byte is encoded as a character hex + * stream with the high nibble sent first and the low nibble sent + * last. If all data bytes are exhausted we send a '\r' character + * to end the transmission. */ + case STATE_TX_DATA: + if( usSndBufferCount > 0 ) + { + switch ( eBytePos ) + { + case BYTE_HIGH_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucSndBufferCur >> 4 ) ); + xMBPortSerialPutByte( ( CHAR ) ucByte ); + eBytePos = BYTE_LOW_NIBBLE; + break; + + case BYTE_LOW_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucSndBufferCur & 0x0F ) ); + xMBPortSerialPutByte( ( CHAR )ucByte ); + pucSndBufferCur++; + eBytePos = BYTE_HIGH_NIBBLE; + usSndBufferCount--; + break; + } + } + else + { + xMBPortSerialPutByte( MB_ASCII_DEFAULT_CR ); + eSndState = STATE_TX_END; + } + break; + + /* Finish the frame by sending a LF character. */ + case STATE_TX_END: + xMBPortSerialPutByte( ( CHAR )ucMBLFCharacter ); + /* We need another state to make sure that the CR character has + * been sent. */ + eSndState = STATE_TX_NOTIFY; + break; + + /* Notify the task which called eMBASCIISend that the frame has + * been sent. */ + case STATE_TX_NOTIFY: + eSndState = STATE_TX_IDLE; + xNeedPoll = xMBPortEventPost( EV_FRAME_SENT ); + + /* Disable transmitter. This prevents another transmit buffer + * empty interrupt. */ + vMBPortSerialEnable( TRUE, FALSE ); + eSndState = STATE_TX_IDLE; + break; + + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_TX_IDLE: + /* enable receiver/disable transmitter. */ + vMBPortSerialEnable( TRUE, FALSE ); + break; + } + + return xNeedPoll; +} + +BOOL +xMBASCIITimerT1SExpired( void ) +{ + switch ( eRcvState ) + { + /* If we have a timeout we go back to the idle state and wait for + * the next frame. + */ + case STATE_RX_RCV: + case STATE_RX_WAIT_EOF: + eRcvState = STATE_RX_IDLE; + break; + + default: + assert( ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_WAIT_EOF ) ); + break; + } + vMBPortTimersDisable( ); + + /* no context switch required. */ + return FALSE; +} + + +static UCHAR +prvucMBCHAR2BIN( UCHAR ucCharacter ) +{ + if( ( ucCharacter >= '0' ) && ( ucCharacter <= '9' ) ) + { + return ( UCHAR )( ucCharacter - '0' ); + } + else if( ( ucCharacter >= 'A' ) && ( ucCharacter <= 'F' ) ) + { + return ( UCHAR )( ucCharacter - 'A' + 0x0A ); + } + else + { + return 0xFF; + } +} + +static UCHAR +prvucMBBIN2CHAR( UCHAR ucByte ) +{ + if( ucByte <= 0x09 ) + { + return ( UCHAR )( '0' + ucByte ); + } + else if( ( ucByte >= 0x0A ) && ( ucByte <= 0x0F ) ) + { + return ( UCHAR )( ucByte - 0x0A + 'A' ); + } + else + { + /* Programming error. */ + assert( 0 ); + } + return '0'; +} + + +static UCHAR +prvucMBLRC( UCHAR * pucFrame, USHORT usLen ) +{ + UCHAR ucLRC = 0; /* LRC char initialized */ + + while( usLen-- ) + { + ucLRC += *pucFrame++; /* Add buffer byte without carry */ + } + + /* Return twos complement */ + ucLRC = ( UCHAR ) ( -( ( CHAR ) ucLRC ) ); + return ucLRC; +} + +#endif diff --git a/components/freemodbus/modbus/ascii/mbascii.h b/components/freemodbus/modbus/ascii/mbascii.h new file mode 100644 index 000000000..47846ddec --- /dev/null +++ b/components/freemodbus/modbus/ascii/mbascii.h @@ -0,0 +1,56 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbascii.h,v 1.8 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_ASCII_H +#define _MB_ASCII_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#if MB_ASCII_ENABLED > 0 +eMBErrorCode eMBASCIIInit( UCHAR slaveAddress, UCHAR ucPort, + ULONG ulBaudRate, eMBParity eParity ); +void eMBASCIIStart( void ); +void eMBASCIIStop( void ); + +eMBErrorCode eMBASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBASCIISend( UCHAR slaveAddress, const UCHAR * pucFrame, + USHORT usLength ); +BOOL xMBASCIIReceiveFSM( void ); +BOOL xMBASCIITransmitFSM( void ); +BOOL xMBASCIITimerT1SExpired( void ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/functions/mbfunccoils.c b/components/freemodbus/modbus/functions/mbfunccoils.c new file mode 100644 index 000000000..54227b335 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfunccoils.c @@ -0,0 +1,270 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfunccoils.c,v 1.8 2007/02/18 23:47:16 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_COILCNT_MAX ( 0x07D0 ) + +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_FUNC_WRITE_MUL_COILCNT_MAX ( 0x07B0 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ + +#if MB_FUNC_READ_COILS_ENABLED > 0 + +eMBException +eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usCoilCount; + UCHAR ucNBytes; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF] << 8 ); + usCoilCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usCoilCount >= 1 ) && + ( usCoilCount < MB_PDU_FUNC_READ_COILCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_COILS; + *usLen += 1; + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usCoilCount & 0x0007 ) != 0 ) + { + ucNBytes = ( UCHAR )( usCoilCount / 8 + 1 ); + } + else + { + ucNBytes = ( UCHAR )( usCoilCount / 8 ); + } + *pucFrameCur++ = ucNBytes; + *usLen += 1; + + eRegStatus = + eMBRegCoilsCB( pucFrameCur, usRegAddress, usCoilCount, + MB_REG_READ ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen += ucNBytes;; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 +eMBException +eMBFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + UCHAR ucBuf[2]; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + if( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF + 1] == 0x00 ) && + ( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) || + ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0x00 ) ) ) + { + ucBuf[1] = 0; + if( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) + { + ucBuf[0] = 1; + } + else + { + ucBuf[0] = 0; + } + eRegStatus = + eMBRegCoilsCB( &ucBuf[0], usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +eMBException +eMBFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usCoilCnt; + UCHAR ucByteCount; + UCHAR ucByteCountVerify; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen > ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCnt = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF] << 8 ); + usCoilCnt |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF + 1] ); + + ucByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; + + /* Compute the number of expected bytes in the request. */ + if( ( usCoilCnt & 0x0007 ) != 0 ) + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 + 1 ); + } + else + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 ); + } + + if( ( usCoilCnt >= 1 ) && + ( usCoilCnt <= MB_PDU_FUNC_WRITE_MUL_COILCNT_MAX ) && + ( ucByteCountVerify == ucByteCount ) ) + { + eRegStatus = + eMBRegCoilsCB( &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], + usRegAddress, usCoilCnt, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncdiag.c b/components/freemodbus/modbus/functions/mbfuncdiag.c new file mode 100644 index 000000000..d75ffc0f7 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncdiag.c @@ -0,0 +1,29 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncdiag.c,v 1.3 2006/12/07 22:10:34 wolti Exp $ + */ diff --git a/components/freemodbus/modbus/functions/mbfuncdisc.c b/components/freemodbus/modbus/functions/mbfuncdisc.c new file mode 100644 index 000000000..fb378441b --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncdisc.c @@ -0,0 +1,125 @@ + /* + * FreeRTOS Modbus Libary: A Modbus serial implementation for FreeRTOS + * Copyright (C) 2006 Christian Walter + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_DISCCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_DISCCNT_MAX ( 0x07D0 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ + +#if MB_FUNC_READ_COILS_ENABLED > 0 + +eMBException +eMBFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usDiscreteCnt; + UCHAR ucNBytes; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usDiscreteCnt = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF] << 8 ); + usDiscreteCnt |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usDiscreteCnt >= 1 ) && + ( usDiscreteCnt < MB_PDU_FUNC_READ_DISCCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_DISCRETE_INPUTS; + *usLen += 1; + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usDiscreteCnt & 0x0007 ) != 0 ) + { + ucNBytes = ( UCHAR ) ( usDiscreteCnt / 8 + 1 ); + } + else + { + ucNBytes = ( UCHAR ) ( usDiscreteCnt / 8 ); + } + *pucFrameCur++ = ucNBytes; + *usLen += 1; + + eRegStatus = + eMBRegDiscreteCB( pucFrameCur, usRegAddress, usDiscreteCnt ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen += ucNBytes;; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncholding.c b/components/freemodbus/modbus/functions/mbfuncholding.c new file mode 100644 index 000000000..e74a0624d --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncholding.c @@ -0,0 +1,308 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncholding.c,v 1.12 2007/02/18 23:48:22 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_FUNC_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D ) + +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ( 0x0078 ) + +#define MB_PDU_FUNC_READWRITE_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF ( MB_PDU_DATA_OFF + 6 ) +#define MB_PDU_FUNC_READWRITE_BYTECNT_OFF ( MB_PDU_DATA_OFF + 8 ) +#define MB_PDU_FUNC_READWRITE_WRITE_VALUES_OFF ( MB_PDU_DATA_OFF + 9 ) +#define MB_PDU_FUNC_READWRITE_SIZE_MIN ( 9 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ + +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 + +eMBException +eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + /* Make callback to update the value. */ + eRegStatus = eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF], + usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 +eMBException +eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR ucRegByteCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen >= ( MB_PDU_FUNC_WRITE_MUL_SIZE_MIN + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF + 1] ); + + ucRegByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; + + if( ( usRegCount >= 1 ) && + ( usRegCount <= MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ) && + ( ucRegByteCount == ( UCHAR ) ( 2 * usRegCount ) ) ) + { + /* Make callback to update the register values. */ + eRegStatus = + eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], + usRegAddress, usRegCount, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting + * address and the quantity of registers. We reuse the + * old values in the buffer because they are still valid. + */ + *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + +eMBException +eMBFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8 ); + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) && ( usRegCount <= MB_PDU_FUNC_READ_REGCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_HOLDING_REGISTER; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR ) ( usRegCount * 2 ); + *usLen += 1; + + /* Make callback to fill the buffer. */ + eRegStatus = eMBRegHoldingCB( pucFrameCur, usRegAddress, usRegCount, MB_REG_READ ); + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + *usLen += usRegCount * 2; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + +eMBException +eMBFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegReadAddress; + USHORT usRegReadCount; + USHORT usRegWriteAddress; + USHORT usRegWriteCount; + UCHAR ucRegWriteByteCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen >= ( MB_PDU_FUNC_READWRITE_SIZE_MIN + MB_PDU_SIZE_MIN ) ) + { + usRegReadAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_ADDR_OFF] << 8U ); + usRegReadAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_ADDR_OFF + 1] ); + usRegReadAddress++; + + usRegReadCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF] << 8U ); + usRegReadCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF + 1] ); + + usRegWriteAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF] << 8U ); + usRegWriteAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF + 1] ); + usRegWriteAddress++; + + usRegWriteCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF] << 8U ); + usRegWriteCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF + 1] ); + + ucRegWriteByteCount = pucFrame[MB_PDU_FUNC_READWRITE_BYTECNT_OFF]; + + if( ( usRegReadCount >= 1 ) && ( usRegReadCount <= 0x7D ) && + ( usRegWriteCount >= 1 ) && ( usRegWriteCount <= 0x79 ) && + ( ( 2 * usRegWriteCount ) == ucRegWriteByteCount ) ) + { + /* Make callback to update the register values. */ + eRegStatus = eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_READWRITE_WRITE_VALUES_OFF], + usRegWriteAddress, usRegWriteCount, MB_REG_WRITE ); + + if( eRegStatus == MB_ENOERR ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READWRITE_MULTIPLE_REGISTERS; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR ) ( usRegReadCount * 2 ); + *usLen += 1; + + /* Make the read callback. */ + eRegStatus = + eMBRegHoldingCB( pucFrameCur, usRegReadAddress, usRegReadCount, MB_REG_READ ); + if( eRegStatus == MB_ENOERR ) + { + *usLen += 2 * usRegReadCount; + } + } + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncinput.c b/components/freemodbus/modbus/functions/mbfuncinput.c new file mode 100644 index 000000000..cceedbafe --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncinput.c @@ -0,0 +1,122 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncinput.c,v 1.10 2007/09/12 10:15:56 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D ) + +#define MB_PDU_FUNC_READ_RSP_BYTECNT_OFF ( MB_PDU_DATA_OFF ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_FUNC_READ_INPUT_ENABLED > 0 + +eMBException +eMBFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) + && ( usRegCount < MB_PDU_FUNC_READ_REGCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_INPUT_REGISTER; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR )( usRegCount * 2 ); + *usLen += 1; + + eRegStatus = + eMBRegInputCB( pucFrameCur, usRegAddress, usRegCount ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + *usLen += usRegCount * 2; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read input register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncother.c b/components/freemodbus/modbus/functions/mbfuncother.c new file mode 100644 index 000000000..fcee972bf --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncother.c @@ -0,0 +1,88 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncother.c,v 1.8 2006/12/07 22:10:34 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +#if MB_FUNC_OTHER_REP_SLAVEID_ENABLED > 0 + +/* ----------------------- Static variables ---------------------------------*/ +static UCHAR ucMBSlaveID[MB_FUNC_OTHER_REP_SLAVEID_BUF]; +static USHORT usMBSlaveIDLen; + +/* ----------------------- Start implementation -----------------------------*/ + +eMBErrorCode +eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, + UCHAR const *pucAdditional, USHORT usAdditionalLen ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + /* the first byte and second byte in the buffer is reserved for + * the parameter ucSlaveID and the running flag. The rest of + * the buffer is available for additional data. */ + if( usAdditionalLen + 2 < MB_FUNC_OTHER_REP_SLAVEID_BUF ) + { + usMBSlaveIDLen = 0; + ucMBSlaveID[usMBSlaveIDLen++] = ucSlaveID; + ucMBSlaveID[usMBSlaveIDLen++] = ( UCHAR )( xIsRunning ? 0xFF : 0x00 ); + if( usAdditionalLen > 0 ) + { + memcpy( &ucMBSlaveID[usMBSlaveIDLen], pucAdditional, + ( size_t )usAdditionalLen ); + usMBSlaveIDLen += usAdditionalLen; + } + } + else + { + eStatus = MB_ENORES; + } + return eStatus; +} + +eMBException +eMBFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ) +{ + memcpy( &pucFrame[MB_PDU_DATA_OFF], &ucMBSlaveID[0], ( size_t )usMBSlaveIDLen ); + *usLen = ( USHORT )( MB_PDU_DATA_OFF + usMBSlaveIDLen ); + return MB_EX_NONE; +} + +#endif diff --git a/components/freemodbus/modbus/functions/mbutils.c b/components/freemodbus/modbus/functions/mbutils.c new file mode 100644 index 000000000..6a725703e --- /dev/null +++ b/components/freemodbus/modbus/functions/mbutils.c @@ -0,0 +1,141 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbutils.c,v 1.6 2007/02/18 23:49:07 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbproto.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define BITS_UCHAR 8U + +/* ----------------------- Start implementation -----------------------------*/ +void +xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits, + UCHAR ucValue ) +{ + USHORT usWordBuf; + USHORT usMask; + USHORT usByteOffset; + USHORT usNPreBits; + USHORT usValue = ucValue; + + assert( ucNBits <= 8 ); + assert( ( size_t )BITS_UCHAR == sizeof( UCHAR ) * 8 ); + + /* Calculate byte offset for first byte containing the bit values starting + * at usBitOffset. */ + usByteOffset = ( USHORT )( ( usBitOffset ) / BITS_UCHAR ); + + /* How many bits precede our bits to set. */ + usNPreBits = ( USHORT )( usBitOffset - usByteOffset * BITS_UCHAR ); + + /* Move bit field into position over bits to set */ + usValue <<= usNPreBits; + + /* Prepare a mask for setting the new bits. */ + usMask = ( USHORT )( ( 1 << ( USHORT ) ucNBits ) - 1 ); + usMask <<= usBitOffset - usByteOffset * BITS_UCHAR; + + /* copy bits into temporary storage. */ + usWordBuf = ucByteBuf[usByteOffset]; + usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; + + /* Zero out bit field bits and then or value bits into them. */ + usWordBuf = ( USHORT )( ( usWordBuf & ( ~usMask ) ) | usValue ); + + /* move bits back into storage */ + ucByteBuf[usByteOffset] = ( UCHAR )( usWordBuf & 0xFF ); + ucByteBuf[usByteOffset + 1] = ( UCHAR )( usWordBuf >> BITS_UCHAR ); +} + +UCHAR +xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits ) +{ + USHORT usWordBuf; + USHORT usMask; + USHORT usByteOffset; + USHORT usNPreBits; + + /* Calculate byte offset for first byte containing the bit values starting + * at usBitOffset. */ + usByteOffset = ( USHORT )( ( usBitOffset ) / BITS_UCHAR ); + + /* How many bits precede our bits to set. */ + usNPreBits = ( USHORT )( usBitOffset - usByteOffset * BITS_UCHAR ); + + /* Prepare a mask for setting the new bits. */ + usMask = ( USHORT )( ( 1 << ( USHORT ) ucNBits ) - 1 ); + + /* copy bits into temporary storage. */ + usWordBuf = ucByteBuf[usByteOffset]; + usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; + + /* throw away unneeded bits. */ + usWordBuf >>= usNPreBits; + + /* mask away bits above the requested bitfield. */ + usWordBuf &= usMask; + + return ( UCHAR ) usWordBuf; +} + +eMBException +prveMBError2Exception( eMBErrorCode eErrorCode ) +{ + eMBException eStatus; + + switch ( eErrorCode ) + { + case MB_ENOERR: + eStatus = MB_EX_NONE; + break; + + case MB_ENOREG: + eStatus = MB_EX_ILLEGAL_DATA_ADDRESS; + break; + + case MB_ETIMEDOUT: + eStatus = MB_EX_SLAVE_BUSY; + break; + + default: + eStatus = MB_EX_SLAVE_DEVICE_FAILURE; + break; + } + + return eStatus; +} diff --git a/components/freemodbus/modbus/include/mb.h b/components/freemodbus/modbus/include/mb.h new file mode 100644 index 000000000..8d6be7b42 --- /dev/null +++ b/components/freemodbus/modbus/include/mb.h @@ -0,0 +1,417 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mb.h,v 1.17 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_H +#define _MB_H + +#include "port.h" + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#include "mbport.h" +#include "mbproto.h" + +/*! \defgroup modbus Modbus + * \code #include "mb.h" \endcode + * + * This module defines the interface for the application. It contains + * the basic functions and types required to use the Modbus protocol stack. + * A typical application will want to call eMBInit() first. If the device + * is ready to answer network requests it must then call eMBEnable() to activate + * the protocol stack. In the main loop the function eMBPoll() must be called + * periodically. The time interval between pooling depends on the configured + * Modbus timeout. If an RTOS is available a separate task should be created + * and the task should always call the function eMBPoll(). + * + * \code + * // Initialize protocol stack in RTU mode for a slave with address 10 = 0x0A + * eMBInit( MB_RTU, 0x0A, 38400, MB_PAR_EVEN ); + * // Enable the Modbus Protocol Stack. + * eMBEnable( ); + * for( ;; ) + * { + * // Call the main polling loop of the Modbus protocol stack. + * eMBPoll( ); + * ... + * } + * \endcode + */ + +/* ----------------------- Defines ------------------------------------------*/ + +/*! \ingroup modbus + * \brief Use the default Modbus TCP port (502) + */ +#define MB_TCP_PORT_USE_DEFAULT 0 + +/* ----------------------- Type definitions ---------------------------------*/ + +/*! \ingroup modbus + * \brief Modbus serial transmission modes (RTU/ASCII). + * + * Modbus serial supports two transmission modes. Either ASCII or RTU. RTU + * is faster but has more hardware requirements and requires a network with + * a low jitter. ASCII is slower and more reliable on slower links (E.g. modems) + */ + typedef enum +{ + MB_RTU, /*!< RTU transmission mode. */ + MB_ASCII, /*!< ASCII transmission mode. */ + MB_TCP /*!< TCP mode. */ +} eMBMode; + +/*! \ingroup modbus + * \brief If register should be written or read. + * + * This value is passed to the callback functions which support either + * reading or writing register values. Writing means that the application + * registers should be updated and reading means that the modbus protocol + * stack needs to know the current register values. + * + * \see eMBRegHoldingCB( ), eMBRegCoilsCB( ), eMBRegDiscreteCB( ) and + * eMBRegInputCB( ). + */ +typedef enum +{ + MB_REG_READ, /*!< Read register values and pass to protocol stack. */ + MB_REG_WRITE /*!< Update register values. */ +} eMBRegisterMode; + +/*! \ingroup modbus + * \brief Errorcodes used by all function in the protocol stack. + */ +typedef enum +{ + MB_ENOERR, /*!< no error. */ + MB_ENOREG, /*!< illegal register address. */ + MB_EINVAL, /*!< illegal argument. */ + MB_EPORTERR, /*!< porting layer error. */ + MB_ENORES, /*!< insufficient resources. */ + MB_EIO, /*!< I/O error. */ + MB_EILLSTATE, /*!< protocol stack in illegal state. */ + MB_ETIMEDOUT /*!< timeout error occurred. */ +} eMBErrorCode; + + +/* ----------------------- Function prototypes ------------------------------*/ +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack. + * + * This functions initializes the ASCII or RTU module and calls the + * init functions of the porting layer to prepare the hardware. Please + * note that the receiver is still disabled and no Modbus frames are + * processed until eMBEnable( ) has been called. + * + * \param eMode If ASCII or RTU mode should be used. + * \param ucSlaveAddress The slave address. Only frames sent to this + * address or to the broadcast address are processed. + * \param ucPort The port to use. E.g. 1 for COM1 on windows. This value + * is platform dependent and some ports simply choose to ignore it. + * \param ulBaudRate The baudrate. E.g. 19200. Supported baudrates depend + * on the porting layer. + * \param eParity Parity used for serial transmission. + * + * \return If no error occurs the function returns eMBErrorCode::MB_ENOERR. + * The protocol is then in the disabled state and ready for activation + * by calling eMBEnable( ). Otherwise one of the following error codes + * is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, + UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ); + +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack for Modbus TCP. + * + * This function initializes the Modbus TCP Module. Please note that + * frame processing is still disabled until eMBEnable( ) is called. + * + * \param usTCPPort The TCP port to listen on. + * \return If the protocol stack has been initialized correctly the function + * returns eMBErrorCode::MB_ENOERR. Otherwise one of the following error + * codes is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBTCPInit( USHORT usTCPPort ); + +/*! \ingroup modbus + * \brief Release resources used by the protocol stack. + * + * This function disables the Modbus protocol stack and release all + * hardware resources. It must only be called when the protocol stack + * is disabled. + * + * \note Note all ports implement this function. A port which wants to + * get an callback must define the macro MB_PORT_HAS_CLOSE to 1. + * + * \return If the resources where released it return eMBErrorCode::MB_ENOERR. + * If the protocol stack is not in the disabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBClose( void ); + +/*! \ingroup modbus + * \brief Enable the Modbus protocol stack. + * + * This function enables processing of Modbus frames. Enabling the protocol + * stack is only possible if it is in the disabled state. + * + * \return If the protocol stack is now in the state enabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the disabled state it + * return eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBEnable( void ); + +/*! \ingroup modbus + * \brief Disable the Modbus protocol stack. + * + * This function disables processing of Modbus frames. + * + * \return If the protocol stack has been disabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the enabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBDisable( void ); + +/*! \ingroup modbus + * \brief The main pooling loop of the Modbus protocol stack. + * + * This function must be called periodically. The timer interval required + * is given by the application dependent Modbus slave timeout. Internally the + * function calls xMBPortEventGet() and waits for an event from the receiver or + * transmitter state machines. + * + * \return If the protocol stack is not in the enabled state the function + * returns eMBErrorCode::MB_EILLSTATE. Otherwise it returns + * eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBPoll( void ); + +/*! \ingroup modbus + * \brief Configure the slave id of the device. + * + * This function should be called when the Modbus function Report Slave ID + * is enabled ( By defining MB_FUNC_OTHER_REP_SLAVEID_ENABLED in mbconfig.h ). + * + * \param ucSlaveID Values is returned in the Slave ID byte of the + * Report Slave ID response. + * \param xIsRunning If TRUE the Run Indicator Status byte is set to 0xFF. + * otherwise the Run Indicator Status is 0x00. + * \param pucAdditional Values which should be returned in the Additional + * bytes of the Report Slave ID response. + * \param usAdditionalLen Length of the buffer pucAdditonal. + * + * \return If the static buffer defined by MB_FUNC_OTHER_REP_SLAVEID_BUF in + * mbconfig.h is to small it returns eMBErrorCode::MB_ENORES. Otherwise + * it returns eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, + UCHAR const *pucAdditional, + USHORT usAdditionalLen ); + +/*! \ingroup modbus + * \brief Registers a callback handler for a given function code. + * + * This function registers a new callback handler for a given function code. + * The callback handler supplied is responsible for interpreting the Modbus PDU and + * the creation of an appropriate response. In case of an error it should return + * one of the possible Modbus exceptions which results in a Modbus exception frame + * sent by the protocol stack. + * + * \param ucFunctionCode The Modbus function code for which this handler should + * be registers. Valid function codes are in the range 1 to 127. + * \param pxHandler The function handler which should be called in case + * such a frame is received. If \c NULL a previously registered function handler + * for this function code is removed. + * + * \return eMBErrorCode::MB_ENOERR if the handler has been installed. If no + * more resources are available it returns eMBErrorCode::MB_ENORES. In this + * case the values in mbconfig.h should be adjusted. If the argument was not + * valid it returns eMBErrorCode::MB_EINVAL. + */ +eMBErrorCode eMBRegisterCB( UCHAR ucFunctionCode, + pxMBFunctionHandler pxHandler ); + +/* ----------------------- Callback -----------------------------------------*/ + +/*! \defgroup modbus_registers Modbus Registers + * \code #include "mb.h" \endcode + * The protocol stack does not internally allocate any memory for the + * registers. This makes the protocol stack very small and also usable on + * low end targets. In addition the values don't have to be in the memory + * and could for example be stored in a flash.
+ * Whenever the protocol stack requires a value it calls one of the callback + * function with the register address and the number of registers to read + * as an argument. The application should then read the actual register values + * (for example the ADC voltage) and should store the result in the supplied + * buffer.
+ * If the protocol stack wants to update a register value because a write + * register function was received a buffer with the new register values is + * passed to the callback function. The function should then use these values + * to update the application register values. + */ + +/*! \ingroup modbus_registers + * \brief Callback function used if the value of a Input Register + * is required by the protocol stack. The starting register address is given + * by \c usAddress and the last register is given by usAddress + + * usNRegs - 1. + * + * \param pucRegBuffer A buffer where the callback function should write + * the current value of the modbus registers to. + * \param usAddress The starting address of the register. Input registers + * are in the range 1 - 65535. + * \param usNRegs Number of registers the callback function must supply. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Holding Register value is + * read or written by the protocol stack. The starting register address + * is given by \c usAddress and the last register is given by + * usAddress + usNRegs - 1. + * + * \param pucRegBuffer If the application registers values should be updated the + * buffer points to the new registers values. If the protocol stack needs + * to now the current values the callback function should write them into + * this buffer. + * \param usAddress The starting address of the register. + * \param usNRegs Number of registers to read or write. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application register + * values should be updated from the values in the buffer. For example + * this would be the case when the Modbus master has issued an + * WRITE SINGLE REGISTER command. + * If the value eMBRegisterMode::MB_REG_READ the application should copy + * the current values into the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Coil Register value is + * read or written by the protocol stack. If you are going to use + * this function you might use the functions xMBUtilSetBits( ) and + * xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The bits are packed in bytes where the first coil + * starting at address \c usAddress is stored in the LSB of the + * first byte in the buffer pucRegBuffer. + * If the buffer should be written by the callback function unused + * coil values (I.e. if not a multiple of eight coils is used) should be set + * to zero. + * \param usAddress The first coil number. + * \param usNCoils Number of coil values requested. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application values should + * be updated from the values supplied in the buffer \c pucRegBuffer. + * If eMBRegisterMode::MB_REG_READ the application should store the current + * values in the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Input Discrete Register value is + * read by the protocol stack. + * + * If you are going to use his function you might use the functions + * xMBUtilSetBits( ) and xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The buffer should be updated with the current + * coil values. The first discrete input starting at \c usAddress must be + * stored at the LSB of the first byte in the buffer. If the requested number + * is not a multiple of eight the remaining bits should be set to zero. + * \param usAddress The starting address of the first discrete input. + * \param usNDiscrete Number of discrete input values. + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If no such discrete inputs exists. + * In this case a ILLEGAL DATA ADDRESS exception frame is sent + * as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbconfig.h b/components/freemodbus/modbus/include/mbconfig.h new file mode 100644 index 000000000..54194de26 --- /dev/null +++ b/components/freemodbus/modbus/include/mbconfig.h @@ -0,0 +1,132 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbconfig.h,v 1.15 2010/06/06 13:54:40 wolti Exp $ + */ + +#ifndef _MB_CONFIG_H +#define _MB_CONFIG_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +/*! \defgroup modbus_cfg Modbus Configuration + * + * Most modules in the protocol stack are completly optional and can be + * excluded. This is specially important if target resources are very small + * and program memory space should be saved.
+ * + * All of these settings are available in the file mbconfig.h + */ +/*! \addtogroup modbus_cfg + * @{ + */ +/*! \brief If Modbus ASCII support is enabled. */ +#define MB_ASCII_ENABLED ( 0 ) + +/*! \brief If Modbus RTU support is enabled. */ +#define MB_RTU_ENABLED ( 1 ) + +/*! \brief If Modbus TCP support is enabled. */ +#define MB_TCP_ENABLED ( 0 ) + +/*! \brief The character timeout value for Modbus ASCII. + * + * The character timeout value is not fixed for Modbus ASCII and is therefore + * a configuration option. It should be set to the maximum expected delay + * time of the network. + */ +#define MB_ASCII_TIMEOUT_SEC ( 1 ) + +/*! \brief Timeout to wait in ASCII prior to enabling transmitter. + * + * If defined the function calls vMBPortSerialDelay with the argument + * MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS to allow for a delay before + * the serial transmitter is enabled. This is required because some + * targets are so fast that there is no time between receiving and + * transmitting the frame. If the master is to slow with enabling its + * receiver then he will not receive the response correctly. + */ +#ifndef MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS +#define MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ( 0 ) +#endif + +/*! \brief Maximum number of Modbus functions codes the protocol stack + * should support. + * + * The maximum number of supported Modbus functions must be greater than + * the sum of all enabled functions in this file and custom function + * handlers. If set to small adding more functions will fail. + */ +#define MB_FUNC_HANDLERS_MAX ( 16 ) + +/*! \brief Number of bytes which should be allocated for the Report Slave ID + * command. + * + * This number limits the maximum size of the additional segment in the + * report slave id function. See eMBSetSlaveID( ) for more information on + * how to set this value. It is only used if MB_FUNC_OTHER_REP_SLAVEID_ENABLED + * is set to 1. + */ +#define MB_FUNC_OTHER_REP_SLAVEID_BUF ( 32 ) + +/*! \brief If the Report Slave ID function should be enabled. */ +#define MB_FUNC_OTHER_REP_SLAVEID_ENABLED ( CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT ) + +/*! \brief If the Read Input Registers function should be enabled. */ +#define MB_FUNC_READ_INPUT_ENABLED ( 1 ) + +/*! \brief If the Read Holding Registers function should be enabled. */ +#define MB_FUNC_READ_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Single Register function should be enabled. */ +#define MB_FUNC_WRITE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Multiple registers function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Read Coils function should be enabled. */ +#define MB_FUNC_READ_COILS_ENABLED ( 1 ) + +/*! \brief If the Write Coils function should be enabled. */ +#define MB_FUNC_WRITE_COIL_ENABLED ( 1 ) + +/*! \brief If the Write Multiple Coils function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED ( 1 ) + +/*! \brief If the Read Discrete Inputs function should be enabled. */ +#define MB_FUNC_READ_DISCRETE_INPUTS_ENABLED ( 1 ) + +/*! \brief If the Read/Write Multiple Registers function should be enabled. */ +#define MB_FUNC_READWRITE_HOLDING_ENABLED ( 1 ) + +/*! @} */ +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbframe.h b/components/freemodbus/modbus/include/mbframe.h new file mode 100644 index 000000000..99d59c613 --- /dev/null +++ b/components/freemodbus/modbus/include/mbframe.h @@ -0,0 +1,87 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbframe.h,v 1.9 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FRAME_H +#define _MB_FRAME_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/*! + * Constants which defines the format of a modbus frame. The example is + * shown for a Modbus RTU/ASCII frame. Note that the Modbus PDU is not + * dependent on the underlying transport. + * + * + * <------------------------ MODBUS SERIAL LINE PDU (1) -------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+----------------------------+-------------+ + * | Address | Function Code | Data | CRC/LRC | + * +-----------+---------------+----------------------------+-------------+ + * | | | | + * (2) (3/2') (3') (4) + * + * (1) ... MB_SER_PDU_SIZE_MAX = 256 + * (2) ... MB_SER_PDU_ADDR_OFF = 0 + * (3) ... MB_SER_PDU_PDU_OFF = 1 + * (4) ... MB_SER_PDU_SIZE_CRC = 2 + * + * (1') ... MB_PDU_SIZE_MAX = 253 + * (2') ... MB_PDU_FUNC_OFF = 0 + * (3') ... MB_PDU_DATA_OFF = 1 + * + */ + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_SIZE_MAX 253 /*!< Maximum size of a PDU. */ +#define MB_PDU_SIZE_MIN 1 /*!< Function Code */ +#define MB_PDU_FUNC_OFF 0 /*!< Offset of function code in PDU. */ +#define MB_PDU_DATA_OFF 1 /*!< Offset for response data in PDU. */ + +/* ----------------------- Prototypes 0-------------------------------------*/ +typedef void ( *pvMBFrameStart ) ( void ); + +typedef void ( *pvMBFrameStop ) ( void ); + +typedef eMBErrorCode( *peMBFrameReceive ) ( UCHAR * pucRcvAddress, + UCHAR ** pucFrame, + USHORT * pusLength ); + +typedef eMBErrorCode( *peMBFrameSend ) ( UCHAR slaveAddress, + const UCHAR * pucFrame, + USHORT usLength ); + +typedef void( *pvMBFrameClose ) ( void ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbfunc.h b/components/freemodbus/modbus/include/mbfunc.h new file mode 100644 index 000000000..aea14f759 --- /dev/null +++ b/components/freemodbus/modbus/include/mbfunc.h @@ -0,0 +1,80 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfunc.h,v 1.12 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FUNC_H +#define _MB_FUNC_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +#if MB_FUNC_OTHER_REP_SLAVEID_BUF > 0 + eMBException eMBFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_INPUT_ENABLED > 0 +eMBException eMBFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 +eMBException eMBFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_COILS_ENABLED > 0 +eMBException eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 +eMBException eMBFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +eMBException eMBFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 +eMBException eMBFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbport.h b/components/freemodbus/modbus/include/mbport.h new file mode 100644 index 000000000..8d334d0e0 --- /dev/null +++ b/components/freemodbus/modbus/include/mbport.h @@ -0,0 +1,130 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbport.h,v 1.19 2010/06/06 13:54:40 wolti Exp $ + */ + +#ifndef _MB_PORT_H +#define _MB_PORT_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Type definitions ---------------------------------*/ + +typedef enum +{ + EV_READY, /*!< Startup finished. */ + EV_FRAME_RECEIVED, /*!< Frame received. */ + EV_EXECUTE, /*!< Execute function. */ + EV_FRAME_SENT /*!< Frame sent. */ +} eMBEventType; + +/*! \ingroup modbus + * \brief Parity used for characters in serial mode. + * + * The parity which should be applied to the characters sent over the serial + * link. Please note that this values are actually passed to the porting + * layer and therefore not all parity modes might be available. + */ +typedef enum +{ + MB_PAR_NONE, /*!< No parity. */ + MB_PAR_ODD, /*!< Odd parity. */ + MB_PAR_EVEN /*!< Even parity. */ +} eMBParity; + +/* ----------------------- Supporting functions -----------------------------*/ +BOOL xMBPortEventInit( void ); + +BOOL xMBPortEventPost( eMBEventType eEvent ); + +BOOL xMBPortEventGet( /*@out@ */ eMBEventType * eEvent ); + +/* ----------------------- Serial port functions ----------------------------*/ + +BOOL xMBPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity ); + +void vMBPortClose( void ); + +void xMBPortSerialClose( void ); + +void vMBPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable ); + +BOOL xMBPortSerialGetByte( CHAR * pucByte ); + +BOOL xMBPortSerialPutByte( CHAR ucByte ); + +/* ----------------------- Timers functions ---------------------------------*/ +BOOL xMBPortTimersInit( USHORT usTimeOut50us ); + +void xMBPortTimersClose( void ); + +void vMBPortTimersEnable( void ); + +void vMBPortTimersDisable( void ); + +void vMBPortTimersDelay( USHORT usTimeOutMS ); + +/* ----------------------- Callback for the protocol stack ------------------*/ +/*! + * \brief Callback function for the porting layer when a new byte is + * available. + * + * Depending upon the mode this callback function is used by the RTU or + * ASCII transmission layers. In any case a call to xMBPortSerialGetByte() + * must immediately return a new character. + * + * \return TRUE if a event was posted to the queue because + * a new byte was received. The port implementation should wake up the + * tasks which are currently blocked on the eventqueue. + */ +extern BOOL( *pxMBFrameCBByteReceived ) ( void ); + +extern BOOL( *pxMBFrameCBTransmitterEmpty ) ( void ); + +extern BOOL( *pxMBPortCBTimerExpired ) ( void ); + +/* ----------------------- TCP port functions -------------------------------*/ +#if MB_TCP_ENABLED == 1 +BOOL xMBTCPPortInit( USHORT usTCPPort ); + +void vMBTCPPortClose( void ); + +void vMBTCPPortDisable( void ); + +BOOL xMBTCPPortGetRequest( UCHAR **ppucMBTCPFrame, USHORT * usTCPLength ); + +BOOL xMBTCPPortSendResponse( const UCHAR *pucMBTCPFrame, USHORT usTCPLength ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbproto.h b/components/freemodbus/modbus/include/mbproto.h new file mode 100644 index 000000000..786aaf403 --- /dev/null +++ b/components/freemodbus/modbus/include/mbproto.h @@ -0,0 +1,83 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbproto.h,v 1.14 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_PROTO_H +#define _MB_PROTO_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +#define MB_ADDRESS_BROADCAST ( 0 ) /*! Modbus broadcast address. */ +#define MB_ADDRESS_MIN ( 1 ) /*! Smallest possible slave address. */ +#define MB_ADDRESS_MAX ( 247 ) /*! Biggest possible slave address. */ +#define MB_FUNC_NONE ( 0 ) +#define MB_FUNC_READ_COILS ( 1 ) +#define MB_FUNC_READ_DISCRETE_INPUTS ( 2 ) +#define MB_FUNC_WRITE_SINGLE_COIL ( 5 ) +#define MB_FUNC_WRITE_MULTIPLE_COILS ( 15 ) +#define MB_FUNC_READ_HOLDING_REGISTER ( 3 ) +#define MB_FUNC_READ_INPUT_REGISTER ( 4 ) +#define MB_FUNC_WRITE_REGISTER ( 6 ) +#define MB_FUNC_WRITE_MULTIPLE_REGISTERS ( 16 ) +#define MB_FUNC_READWRITE_MULTIPLE_REGISTERS ( 23 ) +#define MB_FUNC_DIAG_READ_EXCEPTION ( 7 ) +#define MB_FUNC_DIAG_DIAGNOSTIC ( 8 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_CNT ( 11 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_LOG ( 12 ) +#define MB_FUNC_OTHER_REPORT_SLAVEID ( 17 ) +#define MB_FUNC_ERROR ( 128 ) +/* ----------------------- Type definitions ---------------------------------*/ + typedef enum +{ + MB_EX_NONE = 0x00, + MB_EX_ILLEGAL_FUNCTION = 0x01, + MB_EX_ILLEGAL_DATA_ADDRESS = 0x02, + MB_EX_ILLEGAL_DATA_VALUE = 0x03, + MB_EX_SLAVE_DEVICE_FAILURE = 0x04, + MB_EX_ACKNOWLEDGE = 0x05, + MB_EX_SLAVE_BUSY = 0x06, + MB_EX_MEMORY_PARITY_ERROR = 0x08, + MB_EX_GATEWAY_PATH_FAILED = 0x0A, + MB_EX_GATEWAY_TGT_FAILED = 0x0B +} eMBException; + +typedef eMBException( *pxMBFunctionHandler ) ( UCHAR * pucFrame, USHORT * pusLength ); + +typedef struct +{ + UCHAR ucFunctionCode; + pxMBFunctionHandler pxHandler; +} xMBFunctionHandler; + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbutils.h b/components/freemodbus/modbus/include/mbutils.h new file mode 100644 index 000000000..61495751d --- /dev/null +++ b/components/freemodbus/modbus/include/mbutils.h @@ -0,0 +1,108 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbutils.h,v 1.5 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_UTILS_H +#define _MB_UTILS_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/*! \defgroup modbus_utils Utilities + * + * This module contains some utility functions which can be used by + * the application. It includes some special functions for working with + * bitfields backed by a character array buffer. + * + */ +/*! \addtogroup modbus_utils + * @{ + */ +/*! \brief Function to set bits in a byte buffer. + * + * This function allows the efficient use of an array to implement bitfields. + * The array used for storing the bits must always be a multiple of two + * bytes. Up to eight bits can be set or cleared in one operation. + * + * \param ucByteBuf A buffer where the bit values are stored. Must be a + * multiple of 2 bytes. No length checking is performed and if + * usBitOffset / 8 is greater than the size of the buffer memory contents + * is overwritten. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * \param ucValues Thew new values for the bits. The value for the first bit + * starting at usBitOffset is the LSB of the value + * ucValues + * + * \code + * ucBits[2] = {0, 0}; + * + * // Set bit 4 to 1 (read: set 1 bit starting at bit offset 4 to value 1) + * xMBUtilSetBits( ucBits, 4, 1, 1 ); + * + * // Set bit 7 to 1 and bit 8 to 0. + * xMBUtilSetBits( ucBits, 7, 2, 0x01 ); + * + * // Set bits 8 - 11 to 0x05 and bits 12 - 15 to 0x0A; + * xMBUtilSetBits( ucBits, 8, 8, 0x5A); + * \endcode + */ +void xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits, UCHAR ucValues ); + +/*! \brief Function to read bits in a byte buffer. + * + * This function is used to extract up bit values from an array. Up to eight + * bit values can be extracted in one step. + * + * \param ucByteBuf A buffer where the bit values are stored. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * + * \code + * UCHAR ucBits[2] = {0, 0}; + * UCHAR ucResult; + * + * // Extract the bits 3 - 10. + * ucResult = xMBUtilGetBits( ucBits, 3, 8 ); + * \endcode + */ +UCHAR xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits ); + +/*! @} */ + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/mb.c b/components/freemodbus/modbus/mb.c new file mode 100644 index 000000000..2b23b32c9 --- /dev/null +++ b/components/freemodbus/modbus/mb.c @@ -0,0 +1,412 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mb.c,v 1.28 2010/06/06 13:54:40 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbfunc.h" + +#include "mbport.h" +#if MB_RTU_ENABLED == 1 +#include "mbrtu.h" +#endif +#if MB_ASCII_ENABLED == 1 +#include "mbascii.h" +#endif +#if MB_TCP_ENABLED == 1 +#include "mbtcp.h" +#endif + +#ifndef MB_PORT_HAS_CLOSE +#define MB_PORT_HAS_CLOSE 0 +#endif + +/* ----------------------- Static variables ---------------------------------*/ + +static UCHAR ucMBAddress; +static eMBMode eMBCurrentMode; + +static enum +{ + STATE_ENABLED, + STATE_DISABLED, + STATE_NOT_INITIALIZED +} eMBState = STATE_NOT_INITIALIZED; + +/* Functions pointer which are initialized in eMBInit( ). Depending on the + * mode (RTU or ASCII) the are set to the correct implementations. + */ +static peMBFrameSend peMBFrameSendCur; +static pvMBFrameStart pvMBFrameStartCur; +static pvMBFrameStop pvMBFrameStopCur; +static peMBFrameReceive peMBFrameReceiveCur; +static pvMBFrameClose pvMBFrameCloseCur; + +/* Callback functions required by the porting layer. They are called when + * an external event has happend which includes a timeout or the reception + * or transmission of a character. + */ +BOOL( *pxMBFrameCBByteReceived ) ( void ); +BOOL( *pxMBFrameCBTransmitterEmpty ) ( void ); +BOOL( *pxMBPortCBTimerExpired ) ( void ); + +BOOL( *pxMBFrameCBReceiveFSMCur ) ( void ); +BOOL( *pxMBFrameCBTransmitFSMCur ) ( void ); + +/* An array of Modbus functions handlers which associates Modbus function + * codes with implementing functions. + */ +static xMBFunctionHandler xFuncHandlers[MB_FUNC_HANDLERS_MAX] = { +#if MB_FUNC_OTHER_REP_SLAVEID_ENABLED > 0 + {MB_FUNC_OTHER_REPORT_SLAVEID, eMBFuncReportSlaveID}, +#endif +#if MB_FUNC_READ_INPUT_ENABLED > 0 + {MB_FUNC_READ_INPUT_REGISTER, eMBFuncReadInputRegister}, +#endif +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + {MB_FUNC_READ_HOLDING_REGISTER, eMBFuncReadHoldingRegister}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_REGISTERS, eMBFuncWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_REGISTER, eMBFuncWriteHoldingRegister}, +#endif +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + {MB_FUNC_READWRITE_MULTIPLE_REGISTERS, eMBFuncReadWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_READ_COILS_ENABLED > 0 + {MB_FUNC_READ_COILS, eMBFuncReadCoils}, +#endif +#if MB_FUNC_WRITE_COIL_ENABLED > 0 + {MB_FUNC_WRITE_SINGLE_COIL, eMBFuncWriteCoil}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_COILS, eMBFuncWriteMultipleCoils}, +#endif +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 + {MB_FUNC_READ_DISCRETE_INPUTS, eMBFuncReadDiscreteInputs}, +#endif +}; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + /* check preconditions */ + if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) || + ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) ) + { + eStatus = MB_EINVAL; + } + else + { + ucMBAddress = ucSlaveAddress; + + switch ( eMode ) + { +#if MB_RTU_ENABLED > 0 + case MB_RTU: + pvMBFrameStartCur = eMBRTUStart; + pvMBFrameStopCur = eMBRTUStop; + peMBFrameSendCur = eMBRTUSend; + peMBFrameReceiveCur = eMBRTUReceive; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL; + pxMBFrameCBByteReceived = xMBRTUReceiveFSM; + pxMBFrameCBTransmitterEmpty = xMBRTUTransmitFSM; + pxMBPortCBTimerExpired = xMBRTUTimerT35Expired; + + eStatus = eMBRTUInit( ucMBAddress, ucPort, ulBaudRate, eParity ); + break; +#endif +#if MB_ASCII_ENABLED > 0 + case MB_ASCII: + pvMBFrameStartCur = eMBASCIIStart; + pvMBFrameStopCur = eMBASCIIStop; + peMBFrameSendCur = eMBASCIISend; + peMBFrameReceiveCur = eMBASCIIReceive; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL; + pxMBFrameCBByteReceived = xMBASCIIReceiveFSM; + pxMBFrameCBTransmitterEmpty = xMBASCIITransmitFSM; + pxMBPortCBTimerExpired = xMBASCIITimerT1SExpired; + + eStatus = eMBASCIIInit( ucMBAddress, ucPort, ulBaudRate, eParity ); + break; +#endif + default: + eStatus = MB_EINVAL; + } + + if( eStatus == MB_ENOERR ) + { + if( !xMBPortEventInit( ) ) + { + /* port dependent event module initalization failed. */ + eStatus = MB_EPORTERR; + } + else + { + eMBCurrentMode = eMode; + eMBState = STATE_DISABLED; + } + } + } + return eStatus; +} + +#if MB_TCP_ENABLED > 0 +eMBErrorCode +eMBTCPInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( ( eStatus = eMBTCPDoInit( ucTCPPort ) ) != MB_ENOERR ) + { + eMBState = STATE_DISABLED; + } + else if( !xMBPortEventInit( ) ) + { + /* Port dependent event module initalization failed. */ + eStatus = MB_EPORTERR; + } + else + { + pvMBFrameStartCur = eMBTCPStart; + pvMBFrameStopCur = eMBTCPStop; + peMBFrameReceiveCur = eMBTCPReceive; + peMBFrameSendCur = eMBTCPSend; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBTCPPortClose : NULL; + ucMBAddress = MB_TCP_PSEUDO_ADDRESS; + eMBCurrentMode = MB_TCP; + eMBState = STATE_DISABLED; + } + return eStatus; +} +#endif + +eMBErrorCode +eMBRegisterCB( UCHAR ucFunctionCode, pxMBFunctionHandler pxHandler ) +{ + int i; + eMBErrorCode eStatus; + + if( ( 0 < ucFunctionCode ) && ( ucFunctionCode <= 127 ) ) + { + ENTER_CRITICAL_SECTION( ); + if( pxHandler != NULL ) + { + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + if( ( xFuncHandlers[i].pxHandler == NULL ) || + ( xFuncHandlers[i].pxHandler == pxHandler ) ) + { + xFuncHandlers[i].ucFunctionCode = ucFunctionCode; + xFuncHandlers[i].pxHandler = pxHandler; + break; + } + } + eStatus = ( i != MB_FUNC_HANDLERS_MAX ) ? MB_ENOERR : MB_ENORES; + } + else + { + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode ) + { + xFuncHandlers[i].ucFunctionCode = 0; + xFuncHandlers[i].pxHandler = NULL; + break; + } + } + /* Remove can't fail. */ + eStatus = MB_ENOERR; + } + EXIT_CRITICAL_SECTION( ); + } + else + { + eStatus = MB_EINVAL; + } + return eStatus; +} + + +eMBErrorCode +eMBClose( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + if( pvMBFrameCloseCur != NULL ) + { + pvMBFrameCloseCur( ); + } + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBEnable( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + /* Activate the protocol stack. */ + pvMBFrameStartCur( ); + eMBState = STATE_ENABLED; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBDisable( void ) +{ + eMBErrorCode eStatus; + + if( eMBState == STATE_ENABLED ) + { + pvMBFrameStopCur( ); + eMBState = STATE_DISABLED; + eStatus = MB_ENOERR; + } + else if( eMBState == STATE_DISABLED ) + { + eStatus = MB_ENOERR; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBPoll( void ) +{ + static UCHAR *ucMBFrame; + static UCHAR ucRcvAddress; + static UCHAR ucFunctionCode; + static USHORT usLength; + static eMBException eException; + + int i; + eMBErrorCode eStatus = MB_ENOERR; + eMBEventType eEvent; + + /* Check if the protocol stack is ready. */ + if( eMBState != STATE_ENABLED ) + { + return MB_EILLSTATE; + } + + /* Check if there is a event available. If not return control to caller. + * Otherwise we will handle the event. */ + if( xMBPortEventGet( &eEvent ) == TRUE ) + { + switch ( eEvent ) + { + case EV_READY: + break; + + case EV_FRAME_RECEIVED: + eStatus = peMBFrameReceiveCur( &ucRcvAddress, &ucMBFrame, &usLength ); + if( eStatus == MB_ENOERR ) + { + /* Check if the frame is for us. If not ignore the frame. */ + if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) ) + { + ( void )xMBPortEventPost( EV_EXECUTE ); + } + } + break; + + case EV_EXECUTE: + ucFunctionCode = ucMBFrame[MB_PDU_FUNC_OFF]; + eException = MB_EX_ILLEGAL_FUNCTION; + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + /* No more function handlers registered. Abort. */ + if( xFuncHandlers[i].ucFunctionCode == 0 ) + { + break; + } + else if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode ) + { + eException = xFuncHandlers[i].pxHandler( ucMBFrame, &usLength ); + break; + } + } + + /* If the request was not sent to the broadcast address we + * return a reply. */ + if( ucRcvAddress != MB_ADDRESS_BROADCAST ) + { + if( eException != MB_EX_NONE ) + { + /* An exception occurred. Build an error frame. */ + usLength = 0; + ucMBFrame[usLength++] = ( UCHAR )( ucFunctionCode | MB_FUNC_ERROR ); + ucMBFrame[usLength++] = eException; + } + if( ( eMBCurrentMode == MB_ASCII ) && MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ) + { + vMBPortTimersDelay( MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ); + } + eStatus = peMBFrameSendCur( ucMBAddress, ucMBFrame, usLength ); + } + break; + + case EV_FRAME_SENT: + break; + } + } + return MB_ENOERR; +} diff --git a/components/freemodbus/modbus/rtu/mbcrc.c b/components/freemodbus/modbus/rtu/mbcrc.c new file mode 100644 index 000000000..29b9ea765 --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbcrc.c @@ -0,0 +1,98 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbcrc.c,v 1.7 2007/02/18 23:50:27 wolti Exp $ + */ + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +static const UCHAR aucCRCHi[] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40 +}; + +static const UCHAR aucCRCLo[] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, + 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, + 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, + 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, + 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, + 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, + 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, + 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, + 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, + 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, + 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, + 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, + 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, + 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, + 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, + 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, + 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, + 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, + 0x41, 0x81, 0x80, 0x40 +}; + +USHORT +usMBCRC16( UCHAR * pucFrame, USHORT usLen ) +{ + UCHAR ucCRCHi = 0xFF; + UCHAR ucCRCLo = 0xFF; + int iIndex; + + while( usLen-- ) + { + iIndex = ucCRCLo ^ *( pucFrame++ ); + ucCRCLo = ( UCHAR )( ucCRCHi ^ aucCRCHi[iIndex] ); + ucCRCHi = aucCRCLo[iIndex]; + } + return ( USHORT )( ucCRCHi << 8 | ucCRCLo ); +} diff --git a/components/freemodbus/modbus/rtu/mbcrc.h b/components/freemodbus/modbus/rtu/mbcrc.h new file mode 100644 index 000000000..db227763f --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbcrc.h @@ -0,0 +1,36 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbcrc.h,v 1.5 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_CRC_H +#define _MB_CRC_H + +USHORT usMBCRC16( UCHAR * pucFrame, USHORT usLen ); + +#endif diff --git a/components/freemodbus/modbus/rtu/mbrtu.c b/components/freemodbus/modbus/rtu/mbrtu.c new file mode 100644 index 000000000..28bd29622 --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbrtu.c @@ -0,0 +1,360 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu.c,v 1.18 2007/09/12 10:15:56 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbrtu.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_SER_PDU_SIZE_MIN 4 /*!< Minimum size of a Modbus RTU frame. */ +#define MB_SER_PDU_SIZE_MAX 256 /*!< Maximum size of a Modbus RTU frame. */ +#define MB_SER_PDU_SIZE_CRC 2 /*!< Size of CRC field in PDU. */ +#define MB_SER_PDU_ADDR_OFF 0 /*!< Offset of slave address in Ser-PDU. */ +#define MB_SER_PDU_PDU_OFF 1 /*!< Offset of Modbus-PDU in Ser-PDU. */ + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_RX_INIT, /*!< Receiver is in initial state. */ + STATE_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_RX_RCV, /*!< Frame is beeing received. */ + STATE_RX_ERROR /*!< If the frame is invalid. */ +} eMBRcvState; + +typedef enum +{ + STATE_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_TX_XMIT /*!< Transmitter is in transfer state. */ +} eMBSndState; + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBSndState eSndState; +static volatile eMBRcvState eRcvState; + +volatile UCHAR ucRTUBuf[MB_SER_PDU_SIZE_MAX]; + +static volatile UCHAR *pucSndBufferCur; +static volatile USHORT usSndBufferCount; + +static volatile USHORT usRcvBufferPos; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBRTUInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + ULONG usTimerT35_50us; + + ( void )ucSlaveAddress; + ENTER_CRITICAL_SECTION( ); + + /* Modbus RTU uses 8 Databits. */ + if( xMBPortSerialInit( ucPort, ulBaudRate, 8, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else + { + /* If baudrate > 19200 then we should use the fixed timer values + * t35 = 1750us. Otherwise t35 must be 3.5 times the character time. + */ + if( ulBaudRate > 19200 ) + { + usTimerT35_50us = 35; /* 1800us. */ + } + else + { + /* The timer reload value for a character is given by: + * + * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 ) + * = 11 * Ticks_per_1s / Baudrate + * = 220000 / Baudrate + * The reload for t3.5 is 1.5 times this value and similary + * for t3.5. + */ + usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate ); + } + if( xMBPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + } + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBRTUStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + /* Initially the receiver is in the state STATE_RX_INIT. we start + * the timer and if no character is received within t3.5 we change + * to STATE_RX_IDLE. This makes sure that we delay startup of the + * modbus protocol stack until the bus is free. + */ + eRcvState = STATE_RX_INIT; + vMBPortSerialEnable( TRUE, FALSE ); + vMBPortTimersEnable( ); + + EXIT_CRITICAL_SECTION( ); +} + +void +eMBRTUStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( FALSE, FALSE ); + vMBPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +// The lines below are required to suppress GCC warnings about unused but set variable 'xFrameReceived' +// This warning is treated as error during compilation. +#pragma GCC diagnostic push // required for GCC +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +eMBErrorCode +eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + BOOL xFrameReceived = FALSE; + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN ) + && ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF]; + xFrameReceived = TRUE; + } + else + { + eStatus = MB_EIO; + } + + EXIT_CRITICAL_SECTION( ); + return eStatus; +} +#pragma GCC diagnostic pop // require GCC + +eMBErrorCode +eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + USHORT usCRC16; + + ENTER_CRITICAL_SECTION( ); + + /* Check if the receiver is still in idle state. If not we where to + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if( eRcvState == STATE_RX_IDLE ) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucSndBufferCur = ( UCHAR * ) pucFrame - 1; + usSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usSndBufferCount += usLength; + + /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */ + usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount ); + ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF ); + ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 ); + + /* Activate the transmitter. */ + eSndState = STATE_TX_XMIT; + vMBPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBRTUReceiveFSM( void ) +{ + BOOL xTaskNeedSwitch = FALSE; + UCHAR ucByte; + + assert( eSndState == STATE_TX_IDLE ); + + /* Always read the character. */ + ( void )xMBPortSerialGetByte( ( CHAR * ) & ucByte ); + + switch ( eRcvState ) + { + /* If we have received a character in the init state we have to + * wait until the frame is finished. + */ + case STATE_RX_INIT: + vMBPortTimersEnable( ); + break; + + /* In the error state we wait until all characters in the + * damaged frame are transmitted. + */ + case STATE_RX_ERROR: + vMBPortTimersEnable( ); + break; + + /* In the idle state we wait for a new character. If a character + * is received the t1.5 and t3.5 timers are started and the + * receiver is in the state STATE_RX_RECEIVCE. + */ + case STATE_RX_IDLE: + usRcvBufferPos = 0; + ucRTUBuf[usRcvBufferPos++] = ucByte; + eRcvState = STATE_RX_RCV; + + /* Enable t3.5 timers. */ + vMBPortTimersEnable( ); + break; + + /* We are currently receiving a frame. Reset the timer after + * every character received. If more than the maximum possible + * number of bytes in a modbus frame is received the frame is + * ignored. + */ + case STATE_RX_RCV: + if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + ucRTUBuf[usRcvBufferPos++] = ucByte; + } + else + { + eRcvState = STATE_RX_ERROR; + } + vMBPortTimersEnable( ); + break; + } + return xTaskNeedSwitch; +} + +BOOL +xMBRTUTransmitFSM( void ) +{ + BOOL xNeedPoll = FALSE; + + assert( eRcvState == STATE_RX_IDLE ); + + switch ( eSndState ) + { + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_TX_IDLE: + /* enable receiver/disable transmitter. */ + vMBPortSerialEnable( TRUE, FALSE ); + break; + + case STATE_TX_XMIT: + /* check if we are finished. */ + if( usSndBufferCount != 0 ) + { + xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur ); + pucSndBufferCur++; /* next byte in sendbuffer. */ + usSndBufferCount--; + } + else + { + xNeedPoll = xMBPortEventPost( EV_FRAME_SENT ); + /* Disable transmitter. This prevents another transmit buffer + * empty interrupt. */ + vMBPortSerialEnable( TRUE, FALSE ); + eSndState = STATE_TX_IDLE; + } + break; + } + + return xNeedPoll; +} + +BOOL +xMBRTUTimerT35Expired( void ) +{ + BOOL xNeedPoll = FALSE; + + switch ( eRcvState ) + { + /* Timer t35 expired. Startup phase is finished. */ + case STATE_RX_INIT: + xNeedPoll = xMBPortEventPost( EV_READY ); + break; + + /* A frame was received and t35 expired. Notify the listener that + * a new frame was received. */ + case STATE_RX_RCV: + xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED ); + break; + + /* An error occured while receiving the frame. */ + case STATE_RX_ERROR: + break; + + /* Function called in an illegal state. */ + default: + assert( ( eRcvState == STATE_RX_INIT ) || + ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_ERROR ) ); + } + + vMBPortTimersDisable( ); + eRcvState = STATE_RX_IDLE; + + return xNeedPoll; +} diff --git a/components/freemodbus/modbus/rtu/mbrtu.h b/components/freemodbus/modbus/rtu/mbrtu.h new file mode 100644 index 000000000..8d8bd1f0a --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbrtu.h @@ -0,0 +1,51 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu.h,v 1.9 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_RTU_H +#define _MB_RTU_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + eMBErrorCode eMBRTUInit( UCHAR slaveAddress, UCHAR ucPort, ULONG ulBaudRate, + eMBParity eParity ); +void eMBRTUStart( void ); +void eMBRTUStop( void ); +eMBErrorCode eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ); +eMBErrorCode eMBRTUSend( UCHAR slaveAddress, const UCHAR * pucFrame, USHORT usLength ); +BOOL xMBRTUReceiveFSM( void ); +BOOL xMBRTUTransmitFSM( void ); +BOOL xMBRTUTimerT15Expired( void ); +BOOL xMBRTUTimerT35Expired( void ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/tcp/mbtcp.c b/components/freemodbus/modbus/tcp/mbtcp.c new file mode 100644 index 000000000..fb06144ae --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp.c @@ -0,0 +1,158 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.c,v 1.3 2006/12/07 22:10:34 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbtcp.h" +#include "mbframe.h" +#include "mbport.h" + +#if MB_TCP_ENABLED > 0 + +/* ----------------------- Defines ------------------------------------------*/ + +/* ----------------------- MBAP Header --------------------------------------*/ +/* + * + * <------------------------ MODBUS TCP/IP ADU(1) -------------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+------------------------------------------+ + * | TID | PID | Length | UID |Code | Data | + * +-----------+---------------+------------------------------------------+ + * | | | | | + * (2) (3) (4) (5) (6) + * + * (2) ... MB_TCP_TID = 0 (Transaction Identifier - 2 Byte) + * (3) ... MB_TCP_PID = 2 (Protocol Identifier - 2 Byte) + * (4) ... MB_TCP_LEN = 4 (Number of bytes - 2 Byte) + * (5) ... MB_TCP_UID = 6 (Unit Identifier - 1 Byte) + * (6) ... MB_TCP_FUNC = 7 (Modbus Function Code) + * + * (1) ... Modbus TCP/IP Application Data Unit + * (1') ... Modbus Protocol Data Unit + */ + +#define MB_TCP_TID 0 +#define MB_TCP_PID 2 +#define MB_TCP_LEN 4 +#define MB_TCP_UID 6 +#define MB_TCP_FUNC 7 + +#define MB_TCP_PROTOCOL_ID 0 /* 0 = Modbus Protocol */ + + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBTCPDoInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( xMBTCPPortInit( ucTCPPort ) == FALSE ) + { + eStatus = MB_EPORTERR; + } + return eStatus; +} + +void +eMBTCPStart( void ) +{ +} + +void +eMBTCPStop( void ) +{ + /* Make sure that no more clients are connected. */ + vMBTCPPortDisable( ); +} + +eMBErrorCode +eMBTCPReceive( UCHAR * pucRcvAddress, UCHAR ** ppucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_EIO; + UCHAR *pucMBTCPFrame; + USHORT usLength; + USHORT usPID; + + if( xMBTCPPortGetRequest( &pucMBTCPFrame, &usLength ) != FALSE ) + { + usPID = pucMBTCPFrame[MB_TCP_PID] << 8U; + usPID |= pucMBTCPFrame[MB_TCP_PID + 1]; + + if( usPID == MB_TCP_PROTOCOL_ID ) + { + *ppucFrame = &pucMBTCPFrame[MB_TCP_FUNC]; + *pusLength = usLength - MB_TCP_FUNC; + eStatus = MB_ENOERR; + + /* Modbus TCP does not use any addresses. Fake the source address such + * that the processing part deals with this frame. + */ + *pucRcvAddress = MB_TCP_PSEUDO_ADDRESS; + } + } + else + { + eStatus = MB_EIO; + } + return eStatus; +} + +eMBErrorCode +eMBTCPSend( UCHAR _unused, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR *pucMBTCPFrame = ( UCHAR * ) pucFrame - MB_TCP_FUNC; + USHORT usTCPLength = usLength + MB_TCP_FUNC; + + /* The MBAP header is already initialized because the caller calls this + * function with the buffer returned by the previous call. Therefore we + * only have to update the length in the header. Note that the length + * header includes the size of the Modbus PDU and the UID Byte. Therefore + * the length is usLength plus one. + */ + pucMBTCPFrame[MB_TCP_LEN] = ( usLength + 1 ) >> 8U; + pucMBTCPFrame[MB_TCP_LEN + 1] = ( usLength + 1 ) & 0xFF; + if( xMBTCPPortSendResponse( pucMBTCPFrame, usTCPLength ) == FALSE ) + { + eStatus = MB_EIO; + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/tcp/mbtcp.h b/components/freemodbus/modbus/tcp/mbtcp.h new file mode 100644 index 000000000..f15b0fc0b --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp.h @@ -0,0 +1,53 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.h,v 1.2 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_TCP_H +#define _MB_TCP_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_TCP_PSEUDO_ADDRESS 255 + +/* ----------------------- Function prototypes ------------------------------*/ +eMBErrorCode eMBTCPDoInit( USHORT ucTCPPort ); +void eMBTCPStart( void ); +void eMBTCPStop( void ); +eMBErrorCode eMBTCPReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBTCPSend( UCHAR _unused, const UCHAR * pucFrame, + USHORT usLength ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus_controller/mbcontroller.c b/components/freemodbus/modbus_controller/mbcontroller.c new file mode 100644 index 000000000..2ca06bef9 --- /dev/null +++ b/components/freemodbus/modbus_controller/mbcontroller.c @@ -0,0 +1,492 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// mbcontroller.c +// Implementation of the modbus controller +// The modbus controller is responsible for processing of modbus packet and transfer data +// into parameter instance. + +#include // for calculation of time stamp in milliseconds +#include "esp_log.h" // for log_write +#include "freertos/FreeRTOS.h" // for task creation and queue access +#include "freertos/task.h" // for task api access +#include "freertos/event_groups.h" // for event groups +#include "freertos/queue.h" // for queue api access +#include "mb.h" // for mb types definition +#include "mbutils.h" // for mbutils functions definition for stack callback +#include "sdkconfig.h" // for KConfig values +#include "mbcontroller.h" + +static const char* TAG = "MB_CONTROLLER"; + +#define MB_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +// The Macros below handle the endianness while transfer N byte data into buffer +#define _XFER_4_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 0); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 3); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 2); \ + (src) += 4; \ +} + +#define _XFER_2_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 0); \ + (src) += 2; \ +} + +#define _XFER_4_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 3) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 2) = *(uint8_t *)(src)++ ; \ +} + +#define _XFER_2_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ +} + +#ifdef CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT + +#define MB_ID_BYTE0(id) ((uint8_t)(id)) +#define MB_ID_BYTE1(id) ((uint8_t)(((uint16_t)(id) >> 8) & 0xFF)) +#define MB_ID_BYTE2(id) ((uint8_t)(((uint32_t)(id) >> 16) & 0xFF)) +#define MB_ID_BYTE3(id) ((uint8_t)(((uint32_t)(id) >> 24) & 0xFF)) + +#define MB_CONTROLLER_SLAVE_ID (CONFIG_MB_CONTROLLER_SLAVE_ID) +#define MB_SLAVE_ID_SHORT (MB_ID_BYTE3(MB_CONTROLLER_SLAVE_ID)) + +// Slave ID constant +static uint8_t mb_slave_id[] = { MB_ID_BYTE0(MB_CONTROLLER_SLAVE_ID), + MB_ID_BYTE1(MB_CONTROLLER_SLAVE_ID), + MB_ID_BYTE2(MB_CONTROLLER_SLAVE_ID) }; + +#endif + +// Event group parameters +static TaskHandle_t mb_controller_task_handle = NULL; +static EventGroupHandle_t mb_controller_event_group = NULL; +static QueueHandle_t mb_controller_notification_queue_handle = NULL; + +static uint8_t mb_type = 0; +static uint8_t mb_address = 0; +static uint8_t mb_port = 0; +static uint32_t mb_speed = 0; +static uint16_t mb_parity = 0; + +// This is array of Modbus address area descriptors +static mb_register_area_descriptor_t mb_area_descriptors[MB_PARAM_COUNT] = { 0 }; + +// The helper function to get time stamp in microseconds +static uint64_t get_time_stamp() +{ + uint64_t time_stamp = esp_timer_get_time(); + return time_stamp; +} + +// Helper function to send parameter information to application task +static esp_err_t send_param_info(mb_event_group_t par_type, uint16_t mb_offset, + uint8_t* par_address, uint16_t par_size) +{ + esp_err_t error = ESP_FAIL; + mb_param_info_t par_info; + // Check if queue is not full the send parameter information + par_info.type = par_type; + par_info.size = par_size; + par_info.address = par_address; + par_info.time_stamp = get_time_stamp(); + par_info.mb_offset = mb_offset; + BaseType_t status = xQueueSend(mb_controller_notification_queue_handle, &par_info, MB_PAR_INFO_TOUT); + if (pdTRUE == status) { + ESP_LOGD(TAG, "Queue send parameter info (type, address, size): %d, 0x%.4x, %d", + par_type, (uint32_t)par_address, par_size); + error = ESP_OK; + } else if (errQUEUE_FULL == status) { + ESP_LOGD(TAG, "Parameter queue is overflowed."); + } + return error; +} + +static esp_err_t send_param_access_notification(mb_event_group_t event) +{ + esp_err_t err = ESP_FAIL; + mb_event_group_t bits = (mb_event_group_t)xEventGroupSetBits(mb_controller_event_group, (EventBits_t)event); + if (bits & event) { + ESP_LOGD(TAG, "The MB_REG_CHANGE_EVENT = 0x%.2x is set.", (uint8_t)event); + err = ESP_OK; + } + return err; +} + +// Modbus task function +static void modbus_task(void *pvParameters) { + // Main Modbus stack processing cycle + for (;;) { + BaseType_t status = xEventGroupWaitBits(mb_controller_event_group, + (BaseType_t)(MB_EVENT_STACK_STARTED), + pdFALSE, // do not clear bits + pdFALSE, + portMAX_DELAY); + // Check if stack started then poll for data + if (status & MB_EVENT_STACK_STARTED) { + (void)eMBPoll(); // allow stack to process data + (void)xMBPortSerialTxPoll(); // Send response buffer if ready + } + } +} + +// Blocking function to get event on parameter group change for application task +mb_event_group_t mbcontroller_check_event(mb_event_group_t group) +{ + assert(mb_controller_event_group != NULL); + BaseType_t status = xEventGroupWaitBits(mb_controller_event_group, (BaseType_t)group, + pdTRUE , pdFALSE, portMAX_DELAY); + return (mb_event_group_t)status; +} + +esp_err_t mbcontroller_set_descriptor(const mb_register_area_descriptor_t descr_info) +{ + MB_CHECK(((descr_info.type < MB_PARAM_COUNT) && (descr_info.type >= MB_PARAM_HOLDING)), + ESP_ERR_INVALID_ARG, "mb incorrect modbus instance type = (0x%x).", + (uint32_t)descr_info.type); + MB_CHECK((descr_info.address != NULL), + ESP_ERR_INVALID_ARG, "mb instance pointer is NULL."); + MB_CHECK((descr_info.size >= MB_INST_MIN_SIZE) && (descr_info.size < (MB_INST_MAX_SIZE)), + ESP_ERR_INVALID_ARG, "mb instance size is incorrect = (0x%x).", + (uint32_t)descr_info.size); + mb_area_descriptors[descr_info.type].type = descr_info.type; + mb_area_descriptors[descr_info.type].start_offset = descr_info.start_offset; + mb_area_descriptors[descr_info.type].address = (uint8_t*)descr_info.address; + mb_area_descriptors[descr_info.type].size = descr_info.size; + return ESP_OK; +} + +// Initialization of Modbus controller +esp_err_t mbcontroller_init(void) { + mb_type = MB_MODE_RTU; + mb_address = MB_DEVICE_ADDRESS; + mb_port = MB_UART_PORT; + mb_speed = MB_DEVICE_SPEED; + mb_parity = MB_PARITY_NONE; + + // Initialization of active context of the modbus controller + BaseType_t status = 0; + // Parameter change notification queue + mb_controller_event_group = xEventGroupCreate(); + MB_CHECK((mb_controller_event_group != NULL), + ESP_ERR_NO_MEM, "mb event group error."); + // Parameter change notification queue + mb_controller_notification_queue_handle = xQueueCreate( + MB_CONTROLLER_NOTIFY_QUEUE_SIZE, + sizeof(mb_param_info_t)); + MB_CHECK((mb_controller_notification_queue_handle != NULL), + ESP_ERR_NO_MEM, "mb notify queue creation error."); + // Create modbus controller task + status = xTaskCreate((void*)&modbus_task, + "modbus_task", + MB_CONTROLLER_STACK_SIZE, + NULL, + MB_CONTROLLER_PRIORITY, + &mb_controller_task_handle); + if (status != pdPASS) { + vTaskDelete(mb_controller_task_handle); + MB_CHECK((status == pdPASS), ESP_ERR_NO_MEM, + "mb controller task creation error, xTaskCreate() returns (0x%x).", + (uint32_t)status); + } + assert(mb_controller_task_handle != NULL); // The task is created but handle is incorrect + return ESP_OK; +} + +// Function to get notification about parameter change from application task +esp_err_t mbcontroller_get_param_info(mb_param_info_t* reg_info, uint32_t timeout) +{ + esp_err_t err = ESP_ERR_TIMEOUT; + MB_CHECK((mb_controller_notification_queue_handle != NULL), + ESP_ERR_INVALID_ARG, "mb queue handle is invalid."); + MB_CHECK((reg_info != NULL), ESP_ERR_INVALID_ARG, "mb register information is invalid."); + BaseType_t status = xQueueReceive(mb_controller_notification_queue_handle, + reg_info, pdMS_TO_TICKS(timeout)); + if (status == pdTRUE) { + err = ESP_OK; + } + return err; +} + +// Start Modbus controller start function +esp_err_t mbcontroller_start(void) +{ + eMBErrorCode status = MB_EIO; + // Initialize Modbus stack using mbcontroller parameters + status = eMBInit((eMBMode)mb_type, (UCHAR)mb_address, (UCHAR)mb_port, + (ULONG)mb_speed, (eMBParity)mb_parity); + MB_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack initialization failure, eMBInit() returns (0x%x).", status); +#ifdef CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT + status = eMBSetSlaveID(MB_SLAVE_ID_SHORT, TRUE, (UCHAR*)mb_slave_id, sizeof(mb_slave_id)); + MB_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack set slave ID failure."); +#endif + status = eMBEnable(); + MB_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack set slave ID failure, eMBEnable() returned (0x%x).", (uint32_t)status); + // Set the mbcontroller start flag + EventBits_t flag = xEventGroupSetBits(mb_controller_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack start event set error."); + return ESP_OK; +} + +// Modbus controller destroy function +esp_err_t mbcontroller_destroy(void) +{ + eMBErrorCode mb_error = MB_ENOERR; + // Stop polling by clearing correspondent bit in the event group + EventBits_t flag = xEventGroupClearBits(mb_controller_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack stop event failure."); + // Desable and then destroy the Modbus stack + mb_error = eMBDisable(); + MB_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack disable failure."); + (void)vTaskDelete(mb_controller_task_handle); + (void)vQueueDelete(mb_controller_notification_queue_handle); + (void)vEventGroupDelete(mb_controller_event_group); + mb_error = eMBClose(); + MB_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack close failure returned (0x%x).", (uint32_t)mb_error); + return ESP_OK; +} + +// Setup modbus controller parameters +esp_err_t mbcontroller_setup(const mb_communication_info_t comm_info) +{ + MB_CHECK(((comm_info.mode == MB_MODE_RTU) || (comm_info.mode == MB_MODE_ASCII)), + ESP_ERR_INVALID_ARG, "mb incorrect mode = (0x%x).", + (uint32_t)comm_info.mode); + MB_CHECK((comm_info.slave_addr <= MB_ADDRESS_MAX), + ESP_ERR_INVALID_ARG, "mb wrong slave address = (0x%x).", + (uint32_t)comm_info.slave_addr); + MB_CHECK((comm_info.port <= UART_NUM_2), ESP_ERR_INVALID_ARG, + "mb wrong port to set = (0x%x).", (uint32_t)comm_info.port); + MB_CHECK((comm_info.parity <= UART_PARITY_EVEN), ESP_ERR_INVALID_ARG, + "mb wrong parity option = (0x%x).", (uint32_t)comm_info.parity); + mb_type = (uint8_t)comm_info.mode; + mb_address = (uint8_t)comm_info.slave_addr; + mb_port = (uint8_t)comm_info.port; + mb_speed = (uint32_t)comm_info.baudrate; + mb_parity = (uint8_t)comm_info.parity; + return ESP_OK; +} + +/* ----------------------- Callback functions for Modbus stack ---------------------------------*/ +// These are executed by modbus stack to read appropriate type of registers. + +// This is required to suppress warning when register start address is zero +#pragma GCC diagnostic ignored "-Wtype-limits" + +// Callback function for reading of MB Input Registers +eMBErrorCode eMBRegInputCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + assert(pucRegBuffer != NULL); + USHORT usRegInputNregs = (USHORT)(mb_area_descriptors[MB_PARAM_INPUT].size >> 1); // Number of input registers + USHORT usInputRegStart = (USHORT)mb_area_descriptors[MB_PARAM_INPUT].start_offset; // Get Modbus start address + UCHAR* pucInputBuffer = (UCHAR*)mb_area_descriptors[MB_PARAM_INPUT].address; // Get instance address + USHORT usRegs = usNRegs; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + // If input or configuration parameters are incorrect then return an error to stack layer + if ((usAddress >= usInputRegStart) + && (pucInputBuffer != NULL) + && (usNRegs >= 1) + && ((usAddress + usRegs) <= (usInputRegStart + usRegInputNregs + 1)) + && (usRegInputNregs >= 1)) { + iRegIndex = (USHORT)(usAddress - usInputRegStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucInputBuffer += iRegIndex; + UCHAR* pucBufferStart = pucInputBuffer; + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucInputBuffer); + iRegIndex += 2; + usRegs -= 1; + } + // Send access notification + (void)send_param_access_notification(MB_EVENT_INPUT_REG_RD); + // Send parameter info to application task + (void)send_param_info(MB_EVENT_INPUT_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Holding Registers +// Executed by stack when request to read/write holding registers is received +eMBErrorCode eMBRegHoldingCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + assert(pucRegBuffer != NULL); + USHORT usRegHoldingNregs = (USHORT)(mb_area_descriptors[MB_PARAM_HOLDING].size >> 1); + USHORT usRegHoldingStart = (USHORT)mb_area_descriptors[MB_PARAM_HOLDING].start_offset; + UCHAR* pucHoldingBuffer = (UCHAR*)mb_area_descriptors[MB_PARAM_HOLDING].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usRegs = usNRegs; + // Check input and configuration parameters for correctness + if ((usAddress >= usRegHoldingStart) + && (pucHoldingBuffer != NULL) + && ((usAddress + usRegs) <= (usRegHoldingStart + usRegHoldingNregs + 1)) + && (usRegHoldingNregs >= 1) + && (usNRegs >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegHoldingStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucHoldingBuffer += iRegIndex; + UCHAR* pucBufferStart = pucHoldingBuffer; + switch (eMode) { + case MB_REG_READ: + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucHoldingBuffer); + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_RD); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + case MB_REG_WRITE: + while (usRegs > 0) { + _XFER_2_WR(pucHoldingBuffer, pucRegBuffer); + pucHoldingBuffer += 2; + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_WR); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_WR, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Coils Registers +eMBErrorCode eMBRegCoilsCB(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + assert(NULL != pucRegBuffer); + USHORT usRegCoilNregs = (USHORT)(mb_area_descriptors[MB_PARAM_COIL].size >> 1); // number of registers in storage area + USHORT usRegCoilsStart = (USHORT)mb_area_descriptors[MB_PARAM_COIL].start_offset; // MB offset of coils registers + UCHAR* pucRegCoilsBuf = (UCHAR*)mb_area_descriptors[MB_PARAM_COIL].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usCoils = usNCoils; + usAddress--; // The address is already +1 + if ((usAddress >= usRegCoilsStart) + && (usRegCoilNregs >= 1) + && ((usAddress + usCoils) <= (usRegCoilsStart + (usRegCoilNregs << 4) + 1)) + && (pucRegCoilsBuf != NULL) + && (usNCoils >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegCoilsStart); + CHAR* pucCoilsDataBuf = (CHAR*)(pucRegCoilsBuf + (iRegIndex >> 3)); + switch (eMode) { + case MB_REG_READ: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits((UCHAR*)pucRegCoilsBuf, iRegIndex, 1); + xMBUtilSetBits(pucRegBuffer, iRegIndex - (usAddress - usRegCoilsStart), 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_WR); + (void)send_param_info(MB_EVENT_COILS_WR, (uint16_t)usAddress, + (uint8_t*)(pucCoilsDataBuf), (uint16_t)usNCoils); + break; + case MB_REG_WRITE: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits(pucRegBuffer, + iRegIndex - (usAddress - usRegCoilsStart), 1); + xMBUtilSetBits((uint8_t*)pucRegCoilsBuf, iRegIndex, 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_WR); + (void)send_param_info(MB_EVENT_COILS_WR, (uint16_t)usAddress, + (uint8_t*)pucCoilsDataBuf, (uint16_t)usNCoils); + break; + } // switch ( eMode ) + } else { + // If the configuration or input parameters are incorrect then return error to stack + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Discrete Input Registers +eMBErrorCode eMBRegDiscreteCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + assert(pucRegBuffer != NULL); + USHORT usRegDiscreteNregs = (USHORT)(mb_area_descriptors[MB_PARAM_DISCRETE].size >> 1); // number of registers in storage area + USHORT usRegDiscreteStart = (USHORT)mb_area_descriptors[MB_PARAM_DISCRETE].start_offset; // MB offset of registers + UCHAR* pucRegDiscreteBuf = (UCHAR*)mb_area_descriptors[MB_PARAM_DISCRETE].address; // the storage address + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex, iRegBitIndex, iNReg; + UCHAR* pucDiscreteInputBuf; + iNReg = usNDiscrete / 8 + 1; + pucDiscreteInputBuf = (UCHAR*) pucRegDiscreteBuf; + // It already plus one in modbus function method. + usAddress--; + if ((usAddress >= usRegDiscreteStart) + && (usRegDiscreteNregs >= 1) + && (pucRegDiscreteBuf != NULL) + && ((usAddress + usNDiscrete) <= (usRegDiscreteStart + (usRegDiscreteNregs * 16))) + && (usNDiscrete >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegDiscreteStart) / 8; // Get register index in the buffer for bit number + iRegBitIndex = (USHORT)(usAddress - usRegDiscreteStart) % 8; // Get bit index + UCHAR* pucTempBuf = &pucDiscreteInputBuf[iRegIndex]; + while (iNReg > 0) { + *pucRegBuffer++ = xMBUtilGetBits(&pucDiscreteInputBuf[iRegIndex++], iRegBitIndex, 8); + iNReg--; + } + pucRegBuffer--; + // Last discrete + usNDiscrete = usNDiscrete % 8; + // Filling zero to high bit + *pucRegBuffer = *pucRegBuffer << (8 - usNDiscrete); + *pucRegBuffer = *pucRegBuffer >> (8 - usNDiscrete); + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_DISCRETE_RD); + (void)send_param_info(MB_EVENT_DISCRETE_RD, (uint16_t)usAddress, + (uint8_t*)pucTempBuf, (uint16_t)usNDiscrete); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} +#pragma GCC diagnostic pop // require GCC diff --git a/components/freemodbus/modbus_controller/mbcontroller.h b/components/freemodbus/modbus_controller/mbcontroller.h new file mode 100644 index 000000000..b6b206e2a --- /dev/null +++ b/components/freemodbus/modbus_controller/mbcontroller.h @@ -0,0 +1,186 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// mbcontroller.h +// Implementation of the MbController + +#ifndef _MODBUS_CONTROLLER +#define _MODBUS_CONTROLLER + +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "sdkconfig.h" // for KConfig options +#include "driver/uart.h" // for uart port number defines + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_INST_MIN_SIZE (2) // The minimal size of Modbus registers area in bytes +#define MB_INST_MAX_SIZE (2048) // The maximum size of Modbus area in bytes + +#define MB_CONTROLLER_STACK_SIZE (CONFIG_MB_CONTROLLER_STACK_SIZE) // Stack size for Modbus controller +#define MB_CONTROLLER_PRIORITY (CONFIG_MB_SERIAL_TASK_PRIO - 1) // priority of MB controller task +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +// Default port defines +#define MB_DEVICE_ADDRESS (1) // Default slave device address in Modbus +#define MB_DEVICE_SPEED (115200) // Default Modbus speed for now hard defined +#define MB_UART_PORT (UART_NUM_2) // Default UART port number +#define MB_PAR_INFO_TOUT (10) // Timeout for get parameter info +#define MB_PARITY_NONE (UART_PARITY_DISABLE) + +/** + * @brief Event group for parameters notification + */ +typedef enum +{ + MB_EVENT_NO_EVENTS = 0x00, + MB_EVENT_HOLDING_REG_WR = BIT0, /*!< Modbus Event Write Holding registers. */ + MB_EVENT_HOLDING_REG_RD = BIT1, /*!< Modbus Event Read Holding registers. */ + MB_EVENT_INPUT_REG_RD = BIT3, /*!< Modbus Event Read Input registers. */ + MB_EVENT_COILS_WR = BIT4, /*!< Modbus Event Write Coils. */ + MB_EVENT_COILS_RD = BIT5, /*!< Modbus Event Read Coils. */ + MB_EVENT_DISCRETE_RD = BIT6, /*!< Modbus Event Read Discrete bits. */ + MB_EVENT_STACK_STARTED = BIT7 /*!< Modbus Event Stack started */ +} mb_event_group_t; + +/** + * @brief Type of Modbus parameter + */ +typedef enum +{ + MB_PARAM_HOLDING, /*!< Modbus Holding register. */ + MB_PARAM_INPUT, /*!< Modbus Input register. */ + MB_PARAM_COIL, /*!< Modbus Coils. */ + MB_PARAM_DISCRETE, /*!< Modbus Discrete bits. */ + MB_PARAM_COUNT, + MB_PARAM_UNKNOWN = 0xFF +} mb_param_type_t; + +/*! + * \brief Modbus serial transmission modes (RTU/ASCII). + */ +typedef enum +{ + MB_MODE_RTU, /*!< RTU transmission mode. */ + MB_MODE_ASCII, /*!< ASCII transmission mode. */ + MB_MODE_TCP /*!< TCP mode. */ +} mb_mode_type_t; + +/** + * @brief Parameter access event information type + */ +typedef struct { + uint32_t time_stamp; /*!< Timestamp of Modbus Event (uS)*/ + uint16_t mb_offset; /*!< Modbus register offset */ + mb_event_group_t type; /*!< Modbus event type */ + uint8_t* address; /*!< Modbus data storage address */ + size_t size; /*!< Modbus event register size (number of registers)*/ +} mb_param_info_t; + +/** + * @brief Parameter storage area descriptor + */ +typedef struct { + uint16_t start_offset; /*!< Modbus start address for area descriptor */ + mb_param_type_t type; /*!< Type of storage area descriptor */ + void* address; /*!< Instance address for storage area descriptor */ + size_t size; /*!< Instance size for area descriptor (bytes) */ +} mb_register_area_descriptor_t; + +/** + * @brief Device communication parameters + */ +typedef struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t slave_addr; /*!< Modbus Slave Address */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ +} mb_communication_info_t; + +/** + * @brief Initialize modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t mbcontroller_init(void); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t mbcontroller_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbcontroller_start(void); + +/** + * @brief Set Modbus communication parameters for the controller + * + * @param comm_info Communication parameters structure. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Incorrect parameter data + */ +esp_err_t mbcontroller_setup(mb_communication_info_t comm_info); + +/** + * @brief Wait for specific event on parameter change. + * + * @param group Group event bit mask to wait for change + * + * @return + * - mb_event_group_t event bits triggered + */ +mb_event_group_t mbcontroller_check_event(mb_event_group_t group); + +/** + * @brief Get parameter information + * + * @param[out] reg_info parameter info structure + * @param timeout Timeout in milliseconds to read information from + * parameter queue + * @return + * - ESP_OK Success + * - ESP_ERR_TIMEOUT Can not get data from parameter queue + * or queue overflow + */ +esp_err_t mbcontroller_get_param_info(mb_param_info_t* reg_info, uint32_t timeout); + +/** + * @brief Set Modbus area descriptor + * + * @param descr_data Modbus registers area descriptor structure + * + * @return + * - ESP_OK: The appropriate descriptor is set + * - ESP_ERR_INVALID_ARG: The argument is incorrect + */ +esp_err_t mbcontroller_set_descriptor(mb_register_area_descriptor_t descr_data); + +#endif + diff --git a/components/freemodbus/port/port.h b/components/freemodbus/port/port.h new file mode 100644 index 000000000..c7965a1f2 --- /dev/null +++ b/components/freemodbus/port/port.h @@ -0,0 +1,98 @@ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +#ifndef _PORT_H +#define _PORT_H +/* ----------------------- Platform includes --------------------------------*/ +#include "driver/uart.h" +#include "driver/timer.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/xtensa_api.h" +#include "freertos/portmacro.h" +#include "sdkconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +#define MB_PORT_TAG "MB_PORT" + +#define MB_PORT_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MB_PORT_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +#define INLINE inline +#define PR_BEGIN_EXTERN_C extern "C" { +#define PR_END_EXTERN_C } + +#define MB_ENTER_CRITICAL_ISR(mux) portENTER_CRITICAL_ISR(mux) +#define MB_EXIT_CRITICAL_ISR(mux) portEXIT_CRITICAL_ISR(mux) +#define MB_ENTER_CRITICAL(mux) portENTER_CRITICAL(mux) +#define MB_EXIT_CRITICAL(mux) portEXIT_CRITICAL(mux) + +#define ENTER_CRITICAL_SECTION( ) ( vMBPortEnterCritical() ) +#define EXIT_CRITICAL_SECTION( ) ( vMBPortExitCritical() ) + +typedef char BOOL; + +typedef unsigned char UCHAR; +typedef char CHAR; + +typedef unsigned short USHORT; +typedef short SHORT; + +typedef unsigned long ULONG; +typedef long LONG; + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +void vMBPortSetWithinException( BOOL bInException ); + +void vMBPortEnterCritical(void); + +void vMBPortExitCritical(void); + +BOOL xMBPortSerialTxPoll(); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif diff --git a/components/freemodbus/port/portevent.c b/components/freemodbus/port/portevent.c new file mode 100644 index 000000000..dcb577da6 --- /dev/null +++ b/components/freemodbus/port/portevent.c @@ -0,0 +1,110 @@ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portevent.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "port.h" +#include "sdkconfig.h" +/* ----------------------- Variables ----------------------------------------*/ +static xQueueHandle xQueueHdl; + +#define MB_EVENT_QUEUE_SIZE (1) +#define MB_EVENT_QUEUE_TIMEOUT (pdMS_TO_TICKS(CONFIG_MB_EVENT_QUEUE_TIMEOUT)) + +BOOL bMBPortIsWithinException(void); + +/* ----------------------- Start implementation -----------------------------*/ +BOOL +xMBPortEventInit( void ) +{ + BOOL bStatus = FALSE; + if((xQueueHdl = xQueueCreate(MB_EVENT_QUEUE_SIZE, sizeof(eMBEventType))) != NULL) + { + vQueueAddToRegistry(xQueueHdl, "MbPortEventQueue"); + bStatus = TRUE; + } + return bStatus; +} + +void +vMBPortEventClose( void ) +{ + if(xQueueHdl != NULL) + { + vQueueDelete(xQueueHdl); + xQueueHdl = NULL; + } +} + +BOOL +xMBPortEventPost( eMBEventType eEvent ) +{ + BOOL bStatus = TRUE; + assert(xQueueHdl != NULL); + + if(bMBPortIsWithinException()) + { + xQueueSendFromISR(xQueueHdl, (const void*)&eEvent, pdFALSE); + } + else + { + xQueueSend(xQueueHdl, (const void*)&eEvent, MB_EVENT_QUEUE_TIMEOUT); + } + return bStatus; +} + +BOOL +xMBPortEventGet(eMBEventType * peEvent) +{ + assert(xQueueHdl != NULL); + BOOL xEventHappened = FALSE; + + if (xQueueReceive(xQueueHdl, peEvent, portMAX_DELAY) == pdTRUE) { + xEventHappened = TRUE; + } + return xEventHappened; +} + +xQueueHandle +xMBPortEventGetHandle(void) +{ + if(xQueueHdl != NULL) // + { + return xQueueHdl; + } + return NULL; +} + diff --git a/components/freemodbus/port/portother.c b/components/freemodbus/port/portother.c new file mode 100644 index 000000000..e4b90e64c --- /dev/null +++ b/components/freemodbus/port/portother.c @@ -0,0 +1,76 @@ +/* + * FreeModbus Libary: ESP32 Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include +#include + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" + +/* ----------------------- Modbus includes ----------------------------------*/ + +/* ----------------------- Variables ----------------------------------------*/ +static portMUX_TYPE mb_mutex = portMUX_INITIALIZER_UNLOCKED; + +/* ----------------------- Start implementation -----------------------------*/ + +BOOL +bMBPortIsWithinException( void ) +{ + BOOL bIsWithinException = xPortInIsrContext(); + return bIsWithinException; +} + +void +vMBPortEnterCritical( void ) +{ + portENTER_CRITICAL(&mb_mutex); +} + +void +vMBPortExitCritical( void ) +{ + portEXIT_CRITICAL(&mb_mutex); +} + +void +vMBPortClose( void ) +{ + extern void vMBPortSerialClose( void ); + extern void vMBPortTimerClose( void ); + extern void vMBPortEventClose( void ); + vMBPortSerialClose( ); + vMBPortTimerClose( ); + vMBPortEventClose( ); +} diff --git a/components/freemodbus/port/portserial.c b/components/freemodbus/port/portserial.c new file mode 100644 index 000000000..e9103d0b7 --- /dev/null +++ b/components/freemodbus/port/portserial.c @@ -0,0 +1,294 @@ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +#include "port.h" +#include "driver/uart.h" +#include "freertos/queue.h" // for queue support +#include "soc/uart_reg.h" +#include "driver/gpio.h" +#include "esp_log.h" // for esp_log +#include "esp_err.h" // for ESP_ERROR_CHECK macro + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "sdkconfig.h" // for KConfig options + +// Definitions of UART default pin numbers +#define MB_UART_RXD (CONFIG_MB_UART_RXD) +#define MB_UART_TXD (CONFIG_MB_UART_TXD) +#define MB_UART_RTS (CONFIG_MB_UART_RTS) + +#define MB_BAUD_RATE_DEFAULT (115200) +#define MB_QUEUE_LENGTH (CONFIG_MB_QUEUE_LENGTH) + +#define MB_SERIAL_TASK_PRIO (CONFIG_MB_SERIAL_TASK_PRIO) +#define MB_SERIAL_TASK_STACK_SIZE (CONFIG_MB_SERIAL_TASK_STACK_SIZE) +#define MB_SERIAL_TOUT (3) // 3.5*8 = 28 ticks, TOUT=3 -> ~24..33 ticks + +// Set buffer size for transmission +#define MB_SERIAL_BUF_SIZE (CONFIG_MB_SERIAL_BUF_SIZE) + +// Note: This code uses mixed coding standard from legacy IDF code and used freemodbus stack + +// A queue to handle UART event. +static QueueHandle_t xMbUartQueue; +static TaskHandle_t xMbTaskHandle; +static const CHAR *TAG = "MB_SERIAL"; + +// The UART hardware port number +static UCHAR ucUartNumber = UART_NUM_2; + +static BOOL bRxStateEnabled = FALSE; // Receiver enabled flag +static BOOL bTxStateEnabled = FALSE; // Transmitter enabled flag + +static UCHAR ucBuffer[MB_SERIAL_BUF_SIZE]; // Temporary buffer to transfer received data to modbus stack +static USHORT uiRxBufferPos = 0; // position in the receiver buffer + +void vMBPortSerialEnable(BOOL bRxEnable, BOOL bTxEnable) +{ + // This function can be called from xMBRTUTransmitFSM() of different task + ENTER_CRITICAL_SECTION(); + if (bRxEnable) { + //uart_enable_rx_intr(ucUartNumber); + bRxStateEnabled = TRUE; + vTaskResume(xMbTaskHandle); // Resume receiver task + } else { + vTaskSuspend(xMbTaskHandle); // Block receiver task + bRxStateEnabled = FALSE; + } + if (bTxEnable) { + bTxStateEnabled = TRUE; + } else { + bTxStateEnabled = FALSE; + } + EXIT_CRITICAL_SECTION(); +} + +static void vMBPortSerialRxPoll(size_t xEventSize) +{ + USHORT usLength; + + if (bRxStateEnabled) { + if (xEventSize > 0) { + xEventSize = (xEventSize > MB_SERIAL_BUF_SIZE) ? MB_SERIAL_BUF_SIZE : xEventSize; + uiRxBufferPos = ((uiRxBufferPos + xEventSize) >= MB_SERIAL_BUF_SIZE) ? 0 : uiRxBufferPos; + // Get received packet into Rx buffer + usLength = uart_read_bytes(ucUartNumber, &ucBuffer[uiRxBufferPos], xEventSize, portMAX_DELAY); + for(USHORT usCnt = 0; usCnt < usLength; usCnt++ ) { + // Call the Modbus stack callback function and let it fill the buffers. + ( void )pxMBFrameCBByteReceived(); // calls callback xMBRTUReceiveFSM() to execute MB state machine + } + // The buffer is transferred into Modbus stack and is not needed here any more + uart_flush_input(ucUartNumber); + // Send event EV_FRAME_RECEIVED to allow stack process packet +#ifndef MB_TIMER_PORT_ENABLED + // Let the stack know that T3.5 time is expired and data is received + (void)pxMBPortCBTimerExpired(); // calls callback xMBRTUTimerT35Expired(); +#endif + ESP_LOGD(TAG, "RX_T35_timeout: %d(bytes in buffer)\n", (uint32_t)usLength); + } + } +} + +BOOL xMBPortSerialTxPoll() +{ + BOOL bStatus = FALSE; + USHORT usCount = 0; + BOOL bNeedPoll = FALSE; + + if( bTxStateEnabled ) { + // Continue while all response bytes put in buffer or out of buffer + while((bNeedPoll == FALSE) && (usCount++ < MB_SERIAL_BUF_SIZE)) { + // Calls the modbus stack callback function to let it fill the UART transmit buffer. + bNeedPoll = pxMBFrameCBTransmitterEmpty( ); // calls callback xMBRTUTransmitFSM(); + } + ESP_LOGD(TAG, "MB_TX_buffer sent: (%d) bytes\n", (uint16_t)usCount); + bStatus = TRUE; + } + return bStatus; +} + +static void vUartTask(void *pvParameters) +{ + uart_event_t xEvent; + for(;;) { + if (xQueueReceive(xMbUartQueue, (void*)&xEvent, portMAX_DELAY) == pdTRUE) { + ESP_LOGD(TAG, "MB_uart[%d] event:", ucUartNumber); + //vMBPortTimersEnable(); + switch(xEvent.type) { + //Event of UART receving data + case UART_DATA: + ESP_LOGD(TAG,"Receive data, len: %d", xEvent.size); + // Read received data and send it to modbus stack + vMBPortSerialRxPoll(xEvent.size); + break; + //Event of HW FIFO overflow detected + case UART_FIFO_OVF: + ESP_LOGD(TAG, "hw fifo overflow\n"); + xQueueReset(xMbUartQueue); + break; + //Event of UART ring buffer full + case UART_BUFFER_FULL: + ESP_LOGD(TAG, "ring buffer full\n"); + xQueueReset(xMbUartQueue); + uart_flush_input(ucUartNumber); + break; + //Event of UART RX break detected + case UART_BREAK: + ESP_LOGD(TAG, "uart rx break\n"); + break; + //Event of UART parity check error + case UART_PARITY_ERR: + ESP_LOGD(TAG, "uart parity error\n"); + break; + //Event of UART frame error + case UART_FRAME_ERR: + ESP_LOGD(TAG, "uart frame error\n"); + break; + default: + ESP_LOGD(TAG, "uart event type: %d\n", xEvent.type); + break; + } + } + } + vTaskDelete(NULL); +} + +BOOL xMBPortSerialInit(UCHAR ucPORT, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity) +{ + esp_err_t xErr = ESP_OK; + MB_PORT_CHECK((eParity <= MB_PAR_EVEN), FALSE, "mb serial set parity failure."); + // Set communication port number + ucUartNumber = ucPORT; + // Configure serial communication parameters + UCHAR ucParity = UART_PARITY_DISABLE; + UCHAR ucData = UART_DATA_8_BITS; + switch(eParity){ + case MB_PAR_NONE: + ucParity = UART_PARITY_DISABLE; + break; + case MB_PAR_ODD: + ucParity = UART_PARITY_ODD; + break; + case MB_PAR_EVEN: + ucParity = UART_PARITY_EVEN; + break; + } + switch(ucDataBits){ + case 5: + ucData = UART_DATA_5_BITS; + break; + case 6: + ucData = UART_DATA_6_BITS; + break; + case 7: + ucData = UART_DATA_7_BITS; + break; + case 8: + ucData = UART_DATA_8_BITS; + break; + default: + ucData = UART_DATA_8_BITS; + break; + } + uart_config_t xUartConfig = { + .baud_rate = ulBaudRate, + .data_bits = ucData, + .parity = ucParity, + .stop_bits = UART_STOP_BITS_1, + .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, + .rx_flow_ctrl_thresh = 2, + }; + // Set UART config + xErr = uart_param_config(ucUartNumber, &xUartConfig); + MB_PORT_CHECK((xErr == ESP_OK), + FALSE, "mb config failure, uart_param_config() returned (0x%x).", (uint32_t)xErr); + // Set UART pin numbers + xErr = uart_set_pin(ucUartNumber, MB_UART_TXD, MB_UART_RXD, MB_UART_RTS, UART_PIN_NO_CHANGE); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb set pin failure, uart_set_pin() returned (0x%x).", (uint32_t)xErr); + // Install UART driver, and get the queue. + xErr = uart_driver_install(ucUartNumber, MB_SERIAL_BUF_SIZE, MB_SERIAL_BUF_SIZE, + MB_QUEUE_LENGTH, &xMbUartQueue, ESP_INTR_FLAG_LOWMED); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial driver failure, uart_driver_install() returned (0x%x).", (uint32_t)xErr); + // Set driver mode to Half Duplex + xErr = uart_set_mode(ucUartNumber, UART_MODE_RS485_HALF_DUPLEX); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial set mode failure, uart_set_mode() returned (0x%x).", (uint32_t)xErr); +#ifndef MB_TIMER_PORT_ENABLED + // Set timeout for TOUT interrupt (T3.5 modbus time) + xErr = uart_set_rx_timeout(ucUartNumber, MB_SERIAL_TOUT); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial set rx timeout failure, uart_set_rx_timeout() returned (0x%x).", (uint32_t)xErr); +#endif + // Create a task to handle UART events + BaseType_t xStatus = xTaskCreate(vUartTask, "uart_queue_task", MB_SERIAL_TASK_STACK_SIZE, + NULL, MB_SERIAL_TASK_PRIO, &xMbTaskHandle); + if (xStatus != pdPASS) { + vTaskDelete(xMbTaskHandle); + // Force exit from function with failure + MB_PORT_CHECK(FALSE, FALSE, + "mb stack serial task creation error. xTaskCreate() returned (0x%x).", + (uint32_t)xStatus); + } else { + vTaskSuspend(xMbTaskHandle); // Suspend serial task while stack is not started + } + uiRxBufferPos = 0; + return TRUE; +} + +void vMBPortSerialClose() +{ + (void)vTaskSuspend(xMbTaskHandle); + (void)vTaskDelete(xMbTaskHandle); + ESP_ERROR_CHECK(uart_driver_delete(ucUartNumber)); +} + +BOOL xMBPortSerialPutByte(CHAR ucByte) +{ + // Send one byte to UART transmission buffer + // This function is called by Modbus stack + UCHAR ucLength = uart_write_bytes(ucUartNumber, &ucByte, 1); + return (ucLength == 1); +} + +// Get one byte from intermediate RX buffer +BOOL xMBPortSerialGetByte(CHAR* pucByte) +{ + assert(pucByte != NULL); + MB_PORT_CHECK((uiRxBufferPos < MB_SERIAL_BUF_SIZE), + FALSE, "mb stack serial get byte failure."); + *pucByte = ucBuffer[uiRxBufferPos]; + uiRxBufferPos++; + return TRUE; +} + diff --git a/components/freemodbus/port/porttimer.c b/components/freemodbus/port/porttimer.c new file mode 100644 index 000000000..c4e5d02a1 --- /dev/null +++ b/components/freemodbus/port/porttimer.c @@ -0,0 +1,136 @@ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "driver/timer.h" +#include "sdkconfig.h" + +#ifdef CONFIG_MB_TIMER_PORT_ENABLED + +#define MB_US50_FREQ (20000) // 20kHz 1/20000 = 50mks +#define MB_DISCR_TIME_US (50) // 50uS = one discreet for timer + +#define MB_TIMER_PRESCALLER ((TIMER_BASE_CLK / MB_US50_FREQ) - 1); +#define MB_TIMER_SCALE (TIMER_BASE_CLK / TIMER_DIVIDER) // convert counter value to seconds +#define MB_TIMER_DIVIDER ((TIMER_BASE_CLK / 1000000UL) * MB_DISCR_TIME_US - 1) // divider for 50uS +#define MB_TIMER_WITH_RELOAD (1) + +static const USHORT usTimerIndex = CONFIG_MB_TIMER_INDEX; // Modbus Timer index used by stack +static const USHORT usTimerGroupIndex = CONFIG_MB_TIMER_GROUP; // Modbus Timer group index used by stack + +static timg_dev_t *MB_TG[2] = {&TIMERG0, &TIMERG1}; + +/* ----------------------- Start implementation -----------------------------*/ +static void IRAM_ATTR vTimerGroupIsr(void *param) +{ + // Retrieve the interrupt status and the counter value + // from the timer that reported the interrupt + uint32_t intr_status = MB_TG[usTimerGroupIndex]->int_st_timers.val; + if (intr_status & BIT(usTimerIndex)) { + MB_TG[usTimerGroupIndex]->int_clr_timers.val |= BIT(usTimerIndex); + (void)pxMBPortCBTimerExpired(); // Timer callback function + MB_TG[usTimerGroupIndex]->hw_timer[usTimerIndex].config.alarm_en = TIMER_ALARM_EN; + } +} +#endif + +BOOL xMBPortTimersInit(USHORT usTim1Timerout50us) +{ +#ifdef CONFIG_MB_TIMER_PORT_ENABLED + MB_PORT_CHECK((usTim1Timerout50us > 0), FALSE, + "Modbus timeout discreet is incorrect."); + esp_err_t xErr; + timer_config_t config; + config.alarm_en = TIMER_ALARM_EN; + config.auto_reload = MB_TIMER_WITH_RELOAD; + config.counter_dir = TIMER_COUNT_UP; + config.divider = MB_TIMER_PRESCALLER; + config.intr_type = TIMER_INTR_LEVEL; + config.counter_en = TIMER_PAUSE; + // Configure timer + xErr = timer_init(usTimerGroupIndex, usTimerIndex, &config); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer init failure, timer_init() returned (0x%x).", (uint32_t)xErr); + // Stop timer counter + xErr = timer_pause(usTimerGroupIndex, usTimerIndex); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "stop timer failure, timer_pause() returned (0x%x).", (uint32_t)xErr); + // Reset counter value + xErr = timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0x00000000ULL); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_set_counter_value() returned (0x%x).", + (uint32_t)xErr); + // wait3T5_us = 35 * 11 * 100000 / baud; // the 3.5T symbol time for baudrate + // Set alarm value for usTim1Timerout50us * 50uS + xErr = timer_set_alarm_value(usTimerGroupIndex, usTimerIndex, (uint32_t)(usTim1Timerout50us)); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "failure to set alarm failure, timer_set_alarm_value() returned (0x%x).", + (uint32_t)xErr); + // Register ISR for timer + xErr = timer_isr_register(usTimerGroupIndex, usTimerIndex, vTimerGroupIsr, NULL, ESP_INTR_FLAG_IRAM, NULL); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_isr_register() returned (0x%x).", + (uint32_t)xErr); +#endif + return TRUE; +} + +void vMBPortTimersEnable() +{ +#ifdef CONFIG_MB_TIMER_PORT_ENABLED + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL)); + ESP_ERROR_CHECK(timer_enable_intr(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_start(usTimerGroupIndex, usTimerIndex)); +#endif +} + +void vMBPortTimersDisable() +{ +#ifdef CONFIG_MB_TIMER_PORT_ENABLED + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL)); + // Disable timer interrupt + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); +#endif +} + +void vMBPortTimerClose() +{ +#ifdef CONFIG_MB_TIMER_PORT_ENABLED + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); +#endif +} + diff --git a/docs/Doxyfile b/docs/Doxyfile index 3820e35c5..9fc3e28c1 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -199,9 +199,9 @@ INPUT = \ ### Helper functions for error codes ../../components/esp32/include/esp_err.h \ ### System APIs - ../../components/esp32/include/esp_system.h - - + ../../components/esp32/include/esp_system.h \ + ### Modbus controller component header file + ../../components/freemodbus/modbus_controller/mbcontroller.h ## Get warnings for functions that have no documentation for their parameters or return value ## diff --git a/docs/en/api-reference/protocols/index.rst b/docs/en/api-reference/protocols/index.rst index 96a5825f4..73bb441c4 100644 --- a/docs/en/api-reference/protocols/index.rst +++ b/docs/en/api-reference/protocols/index.rst @@ -10,5 +10,6 @@ Protocols API HTTP Server ASIO ESP-MQTT + Modbus slave Example code for this API section is provided in :example:`protocols` directory of ESP-IDF examples. diff --git a/docs/en/api-reference/protocols/modbus.rst b/docs/en/api-reference/protocols/modbus.rst new file mode 100644 index 000000000..3c93bae6c --- /dev/null +++ b/docs/en/api-reference/protocols/modbus.rst @@ -0,0 +1,62 @@ +ESP-Modbus +========== + +Overview +-------- + + +The Modbus serial communication protocol is de facto standard protocol widely used to connect industrial electronic devices. Modbus allows communication among many devices connected to the same network, for example, a system that measures temperature and humidity and communicates the results to a computer. The Modbus protocol uses several types of data: Holding Registers, Input Registers, Coils (single bit output), Discrete Inputs. Versions of the Modbus protocol exist for serial port and for Ethernet and other protocols that support the Internet protocol suite. +There are many variants of Modbus protocols, some of them are: + + + * ``Modbus RTU`` — This is used in serial communication and makes use of a compact, binary representation of the data for protocol communication. The RTU format follows the commands/data with a cyclic redundancy check checksum as an error check mechanism to ensure the reliability of data. Modbus RTU is the most common implementation available for Modbus. A Modbus RTU message must be transmitted continuously without inter-character hesitations. Modbus messages are framed (separated) by idle (silent) periods. The RS-485 interface communication is usually used for this type. + * ``Modbus ASCII`` — This is used in serial communication and makes use of ASCII characters for protocol communication. The ASCII format uses a longitudinal redundancy check checksum. Modbus ASCII messages are framed by leading colon (":") and trailing newline (CR/LF). + * ``Modbus TCP/IP or Modbus TCP`` — This is a Modbus variant used for communications over TCP/IP networks, connecting over port 502. It does not require a checksum calculation, as lower layers already provide checksum protection. + + +Modbus slave interface API overview +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +ISP-IDF supports Modbus slave protocol and provides modbus_controller interface API to interact with user application. The interface API functions below are used to setup and use Modbus slave stack from application and could be executed in next order: + + +The files deviceparams.c/h contain the user structures which represent Modbus parameters accessed by stack. These parameters should be prepared by user and be assigned to the modbus_controller interface using :cpp:func:`mbcontroller_set_descriptor()` API call before start of communication. + +.. doxygenfunction:: mbcontroller_init + +The function initializes the Modbus controller interface and its active context (tasks, RTOS objects and other resources). + +.. doxygenfunction:: mbcontroller_setup + +The function is used to setup communication parameters of the Modbus stack. See the Modbus controller API documentation for more information. + +.. doxygenfunction:: mbcontroller_set_descriptor + +The function initializes Modbus communication descriptors for each type of Modbus register area (Holding Registers, Input Registers, Coils (single bit output), Discrete Inputs). Once areas are initialized and the :cpp:func:`mbcontroller_start()` API is called the Modbus stack can access the data in user data structures by request from master. See the :cpp:type:`mb_register_area_descriptor_t` for more information. + +.. doxygenfunction:: mbcontroller_start + +Modbus controller start function. Starts stack and interface and allows communication. + +.. doxygenfunction:: mbcontroller_check_event + +The blocking call to function waits for event specified in the input parameter as event mask. Once master access the parameter and event mask matches the parameter the application task will be unblocked and function will return ESP_OK. See the :cpp:type:`mb_event_group_t` for more information about Modbus event masks. + +.. doxygenfunction:: mbcontroller_get_param_info + +The function gets information about accessed parameters from modbus controller event queue. The KConfig 'CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE' key can be used to configure the notification queue size. The timeout parameter allows to specify timeout for waiting notification. The :cpp:type:`mb_param_info_t` structure contain information about accessed parameter. + +.. doxygenfunction:: mbcontroller_destroy + +This function stops Modbus communication stack and destroys controller interface. + +There are some configuration parameters modbus_controller interface and Modbus stack can be configured using KConfig values in "Modbus configuration" menu. See the example application for more information about how to use these API functions. + + +Application Example +------------------- +The example uses the FreeModbus library port for slave implementation: + +:example:`protocols/modbus_slave` + diff --git a/docs/zh_CN/api-reference/protocols/modbus.rst b/docs/zh_CN/api-reference/protocols/modbus.rst new file mode 100644 index 000000000..40d403bcf --- /dev/null +++ b/docs/zh_CN/api-reference/protocols/modbus.rst @@ -0,0 +1 @@ +.. include:: ../../../en/api-reference/protocols/modbus.rst \ No newline at end of file diff --git a/examples/protocols/modbus_slave/CMakeLists.txt b/examples/protocols/modbus_slave/CMakeLists.txt new file mode 100644 index 000000000..cd3b88919 --- /dev/null +++ b/examples/protocols/modbus_slave/CMakeLists.txt @@ -0,0 +1,6 @@ +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.5) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(modbus_slave) diff --git a/examples/protocols/modbus_slave/Makefile b/examples/protocols/modbus_slave/Makefile new file mode 100644 index 000000000..7239baca7 --- /dev/null +++ b/examples/protocols/modbus_slave/Makefile @@ -0,0 +1,9 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := modbus_slave + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/modbus_slave/README.md b/examples/protocols/modbus_slave/README.md new file mode 100644 index 000000000..6ef854836 --- /dev/null +++ b/examples/protocols/modbus_slave/README.md @@ -0,0 +1,73 @@ +# Modbus Slave Example + +This example demonstrates using of FreeModbus stack port implementation for ESP32. The external Modbus host is able to read/write device parameters using Modbus protocol transport. The parameters accessible thorough Modbus are located in deviceparams.h/c files and can be updated by user. +These are represented in structures holding_reg_params, input_reg_params, coil_reg_params, discrete_reg_params for holding registers, input parameters, coils and discrete inputs accordingly. The app_main application demonstrates how to setup Modbus stack and use notifications about parameters change from host system. +The FreeModbus stack located in components\freemodbus\ folder and contain \port folder inside which contains FreeModbus stack port for ESP32. There are some parameters that can be configured in KConfig file to start stack correctly (See description below for more information). + +## Hardware required : +PC + USB Serial adapter connected to USB port + RS485 line drivers + ESP32 WROVER-KIT board. +The MAX485 line driver is used as an example below but other similar chips can be used as well. + +RS485 example circuit schematic: +``` + VCC ---------------+ +--------------- VCC + | | + +-------x-------+ +-------x-------+ + RXD <------| RO | DIFFERENTIAL | RO|-----> RXD + | B|---------------|B | + TXD ------>| DI MAX485 | \ / | MAX485 DI|<----- TXD +ESP32 WROVER KIT 1 | | RS-485 side | | Modbus master + RTS --+--->| DE | / \ | DE|---+ + | | A|---------------|A | | + +----| /RE | PAIR | /RE|---+-- RTS + +-------x--------+ +-------x-------+ + | | + --- --- +``` + +## How to setup and use an example: + +### Configure the application +Configure the UART pins used for modbus communication using command and table below. +``` +make menuconfig +``` + +``` + ----------------------------------------------------------------------------------- + | ESP32 Interface | #define | Default ESP32 Pin | External RS485 | + | ----------------------|--------------------|-------------------| Driver Pin | + | Transmit Data (TxD) | CONFIG_MB_UART_TXD | GPIO23 | DI | + | Receive Data (RxD) | CONFIG_MB_UART_RXD | GPIO22 | RO | + | Request To Send (RTS) | CONFIG_MB_UART_RTS | GPIO18 | ~RE/DE | + | Ground | n/a | GND | GND | + ----------------------------------------------------------------------------------- +``` +The communication parameters below allow to configure freemodbus stack appropriately but usually it is enough to use default settings. +See the help string of parameters for more information. + +### Setup external Modbus master software +Configure the external Modbus master software according to port configuration parameters used in application. +As an example the Modbus Poll application can be used with this example. + +### Build and flash software +Build the project and flash it to the board, then run monitor tool to view serial output: +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output +Example output of the application: +``` +INPUT READ: time_stamp(us):565240387, mb_addr:1, type:8, st_address:0x3ffb385c, size:8 + +HOLDING READ/WRITE: time_stamp(us):12104081, mb_addr:1, type:2, st_address:0x3ffb386c, size:8 +``` +The output lines describe type of operation, its timestamp, modbus address, access type, storage address in parameter structure and number of registers accordingly. + + + diff --git a/examples/protocols/modbus_slave/main/CMakeLists.txt b/examples/protocols/modbus_slave/main/CMakeLists.txt new file mode 100644 index 000000000..96b08bdc5 --- /dev/null +++ b/examples/protocols/modbus_slave/main/CMakeLists.txt @@ -0,0 +1,5 @@ +set(COMPONENT_SRCS "freemodbus.c" + "deviceparams.c") +set(COMPONENT_ADD_INCLUDEDIRS ".") + +register_component() \ No newline at end of file diff --git a/examples/protocols/modbus_slave/main/component.mk b/examples/protocols/modbus_slave/main/component.mk new file mode 100644 index 000000000..a98f634ea --- /dev/null +++ b/examples/protocols/modbus_slave/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/protocols/modbus_slave/main/deviceparams.c b/examples/protocols/modbus_slave/main/deviceparams.c new file mode 100644 index 000000000..1ce7e41c6 --- /dev/null +++ b/examples/protocols/modbus_slave/main/deviceparams.c @@ -0,0 +1,17 @@ +/*===================================================================================== + * Description: + * C file to define parameter storage instances + *====================================================================================*/ +#include +#include "deviceparams.h" + +// Here are the user defined instances for device parameters packed by 1 byte +// These are keep the values that can be accessed from Modbus master +holding_reg_params_t holding_reg_params = { 0 }; + +input_reg_params_t input_reg_params = { 0 }; + +coil_reg_params_t coil_reg_params = { 0 }; + +discrete_reg_params_t discrete_reg_params = { 0 }; + diff --git a/examples/protocols/modbus_slave/main/deviceparams.h b/examples/protocols/modbus_slave/main/deviceparams.h new file mode 100644 index 000000000..18ecd8d93 --- /dev/null +++ b/examples/protocols/modbus_slave/main/deviceparams.h @@ -0,0 +1,131 @@ +/*===================================================================================== + * Description: + * The Modbus parameter structures used to define Modbus instances that + * can be addressed by Modbus protocol. Define these structures per your needs in + * your application. Below is just an example of possible parameters. + *====================================================================================*/ +#ifndef _DEVICE_PARAMS +#define _DEVICE_PARAMS + +#define A24_ARR_SIZE 24 + +// This file defines structure of modbus parameters which reflect correspond modbus address space +// for each modbus register type (coils, discreet inputs, holding registers, input registers) +#pragma pack(push, 1) +typedef struct +{ + // Parameter: discrete_input0 + uint8_t discrete_input0:1; + // Parameter: discrete_input1 + uint8_t discrete_input1:1; + // Parameter: discrete_input2 + uint8_t discrete_input2:1; + // Parameter: discrete_input3 + uint8_t discrete_input3:1; + // Parameter: discrete_input4 + uint8_t discrete_input4:1; + // Parameter: discrete_input5 + uint8_t discrete_input5:1; + // Parameter: discrete_input6 + uint8_t discrete_input6:1; + // Parameter: discrete_input7 + uint8_t discrete_input7:1; + uint8_t discrete_input_port1:8; +} discrete_reg_params_t; +#pragma pack(pop) + +#pragma pack(push, 1) +typedef struct +{ + // Parameter: Coil 0 : Coil0 + uint8_t coil0:1; + // Parameter: Coil 1 : Coil1 + uint8_t coil1:1; + // Parameter: Coil 2 : Coil2 + uint8_t coil2:1; + // Parameter: Coil 3 : Coil3 + uint8_t coil3:1; + // Parameter: Coil 4 : Coil4 + uint8_t coil4:1; + // Parameter: Coil 5 : Coil5 + uint8_t coil5:1; + // Parameter: Coil 6 : Coil6 + uint8_t coil6:1; + // Parameter: Coil 7 : Coil7 + uint8_t coil7:1; + // Coils port 1 + uint8_t coil_port1:8; +} coil_reg_params_t; +#pragma pack(pop) + +#pragma pack(push, 1) +typedef struct +{ + // Parameter: Data channel 0 : data_chan0 : NV Address: 0 + float data_chan0; + // Parameter: Data channel 1 : data_chan1 : NV Address: 0 + float data_chan1; + // Parameter: Data channel 2 : data_chan2 : NV Address: 0 + float data_chan2; + // Parameter: Data channel 3 : data_chan3 : NV Address: 0 + float data_chan3; +} input_reg_params_t; +#pragma pack(pop) + +//See register map for more information. +#pragma pack(push, 1) +typedef struct +{ + // Parameter: Data channel 0 : DataChan0 + float data_chan0; + // Parameter: Data channel 1 : DataChan1 + float data_chan1; + // Parameter: Data channel 2 : DataChan2 + float data_chan2; + // Parameter: Data channel 3 : DataChan3 + float data_chan3; + // Parameter: Protocol version : protocol_version + uint16_t protocol_version; + // Parameter: Hardware version : hardware_version + uint16_t hardware_version; + // Parameter: Software Version : software_version + uint16_t software_version; + // Parameter: Software Revision : software_revision + uint16_t software_revision; + // Parameter: Device Type : deviceType : + uint16_t deviceType; + // Parameter: Modbus Network Address : modbus_address + uint16_t modbus_address; + // Parameter: Modbus Baudrate : modbus_baud + uint16_t modbus_baud; + // Parameter: Modbus parity : modbus_parity + uint16_t modbus_parity; + // Parameter: Modbus stopbit : modbus_stop_bits + uint16_t modbus_stop_bits; + // Parameter: Brace control : modbus_brace_ctrl + uint16_t modbus_brace_ctrl; + // Parameter: Serial number : serial_number + uint32_t serial_number; + // Parameter: Up time : up_time + uint32_t up_time; + // Parameter: Device state : device_state + uint16_t device_state; + // Parameter: Test Float0 : test_float0 + float test_float0; + // Parameter: Test Float1 : test_float1 + float test_float1; + // Parameter: Test Float2 : test_float2 + float test_float2; + // Parameter: Test Float3 : test_float3 + float test_float3; + // Parameter: Test String : string_test + uint8_t string_test[A24_ARR_SIZE]; +} holding_reg_params_t; +#pragma pack(pop) + +extern holding_reg_params_t holding_reg_params; +extern input_reg_params_t input_reg_params; +extern coil_reg_params_t coil_reg_params; +extern discrete_reg_params_t discrete_reg_params; + +#endif // !defined(_DEVICE_PARAMS) diff --git a/examples/protocols/modbus_slave/main/freemodbus.c b/examples/protocols/modbus_slave/main/freemodbus.c new file mode 100644 index 000000000..19e18f350 --- /dev/null +++ b/examples/protocols/modbus_slave/main/freemodbus.c @@ -0,0 +1,168 @@ +/* FreeModbus Slave Example ESP32 + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#include "esp_err.h" +#include "sdkconfig.h" +#include "mbcontroller.h" // for mbcontroller defines and api +#include "deviceparams.h" // for device parameters structures +#include "esp_log.h" // for log_write + +#define MB_PORT_NUM (2) // Number of UART port used for Modbus connection +#define MB_DEV_ADDR (1) // The address of device in Modbus network +#define MB_DEV_SPEED (115200) // The communication speed of the UART + +// Defines below are used to define register start address for each type of Modbus registers +#define MB_REG_DISCRETE_INPUT_START (0x0000) +#define MB_REG_INPUT_START (0x0000) +#define MB_REG_HOLDING_START (0x0000) +#define MB_REG_COILS_START (0x0000) + +#define MB_PAR_INFO_GET_TOUT (10) // Timeout for get parameter info +#define MB_CHAN_DATA_MAX_VAL (10) +#define MB_CHAN_DATA_OFFSET (0.01f) + +static const char *TAG = "MODBUS_SLAVE_APP"; + +// Set register values into known state +static void setup_reg_data() +{ + // Define initial state of parameters + discrete_reg_params.discrete_input1 = 1; + discrete_reg_params.discrete_input3 = 1; + discrete_reg_params.discrete_input5 = 1; + discrete_reg_params.discrete_input7 = 1; + + holding_reg_params.data_chan0 = 1.34; + holding_reg_params.data_chan1 = 2.56; + holding_reg_params.data_chan2 = 3.78; + holding_reg_params.data_chan3 = 4.90; + + coil_reg_params.coil0 = 1; + coil_reg_params.coil2 = 1; + coil_reg_params.coil4 = 1; + coil_reg_params.coil6 = 1; + coil_reg_params.coil7 = 1; + + input_reg_params.data_chan0 = 1.34; + input_reg_params.data_chan1 = 2.56; + input_reg_params.data_chan2 = 3.78; + input_reg_params.data_chan3 = 4.90; +} + +// An example application of Modbus slave. It is based on freemodbus stack. +// See deviceparams.h file for more information about assigned Modbus parameters. +// These parameters can be accessed from main application and also can be changed +// by external Modbus master host. +void app_main() +{ + mb_param_info_t reg_info; // keeps the Modbus registers access information + mb_communication_info_t comm_info; // Modbus communication parameters + mb_register_area_descriptor_t reg_area; // Modbus register area descriptor structure + + // Set UART log level + esp_log_level_set(TAG, ESP_LOG_INFO); + + mbcontroller_init(); // Initialization of Modbus controller + + // Setup communication parameters and start stack + comm_info.mode = MB_MODE_RTU; + comm_info.slave_addr = MB_DEV_ADDR; + comm_info.port = MB_PORT_NUM; + comm_info.baudrate = MB_DEV_SPEED; + comm_info.parity = MB_PARITY_NONE; + ESP_ERROR_CHECK(mbcontroller_setup(comm_info)); + + // The code below initializes Modbus register area descriptors + // for Modbus Holding Registers, Input Registers, Coils and Discrete Inputs + // Initialization should be done for each supported Modbus register area according to register map. + // When external master trying to access the register in the area that is not initialized + // by mbcontroller_set_descriptor() API call then Modbus stack + // will send exception response for this register area. + reg_area.type = MB_PARAM_HOLDING; // Set type of register area + reg_area.start_offset = MB_REG_HOLDING_START; // Offset of register area in Modbus protocol + reg_area.address = (void*)&holding_reg_params; // Set pointer to storage instance + reg_area.size = sizeof(holding_reg_params); // Set the size of register storage instance + ESP_ERROR_CHECK(mbcontroller_set_descriptor(reg_area)); + + // Initialization of Input Registers area + reg_area.type = MB_PARAM_INPUT; + reg_area.start_offset = MB_REG_INPUT_START; + reg_area.address = (void*)&input_reg_params; + reg_area.size = sizeof(input_reg_params); + ESP_ERROR_CHECK(mbcontroller_set_descriptor(reg_area)); + + // Initialization of Coils register area + reg_area.type = MB_PARAM_COIL; + reg_area.start_offset = MB_REG_COILS_START; + reg_area.address = (void*)&coil_reg_params; + reg_area.size = sizeof(coil_reg_params); + ESP_ERROR_CHECK(mbcontroller_set_descriptor(reg_area)); + + // Initialization of Discrete Inputs register area + reg_area.type = MB_PARAM_DISCRETE; + reg_area.start_offset = MB_REG_DISCRETE_INPUT_START; + reg_area.address = (void*)&discrete_reg_params; + reg_area.size = sizeof(discrete_reg_params); + ESP_ERROR_CHECK(mbcontroller_set_descriptor(reg_area)); + + setup_reg_data(); // Set values into known state + + // Starts of modbus controller and stack + ESP_ERROR_CHECK(mbcontroller_start()); + + // The cycle below will be terminated when parameter holdingRegParams.dataChan0 + // incremented each access cycle reaches the CHAN_DATA_MAX_VAL value. + for(;holding_reg_params.data_chan0 < MB_CHAN_DATA_MAX_VAL;){ + // Check for read/write events of Modbus master for certain events + mb_event_group_t event = mbcontroller_check_event((MB_EVENT_HOLDING_REG_WR + | MB_EVENT_INPUT_REG_RD + | MB_EVENT_HOLDING_REG_RD + | MB_EVENT_DISCRETE_RD)); + // Filter events and process them accordingly + if((event & MB_EVENT_HOLDING_REG_WR) || (event & MB_EVENT_HOLDING_REG_RD)) { + // Get parameter information from parameter queue + ESP_ERROR_CHECK(mbcontroller_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + printf("HOLDING READ/WRITE: time_stamp(us):%u, mb_addr:%u, type:%u, st_address:0x%.4x, size:%u\r\n", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + if (reg_info.address == (uint8_t*)&holding_reg_params.data_chan0) + { + holding_reg_params.data_chan0 += MB_CHAN_DATA_OFFSET; + } + } else if (event & MB_EVENT_INPUT_REG_RD) { + ESP_ERROR_CHECK(mbcontroller_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + printf("INPUT READ: time_stamp(us):%u, mb_addr:%u, type:%u, st_address:0x%.4x, size:%u\r\n", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & MB_EVENT_DISCRETE_RD) { + ESP_ERROR_CHECK(mbcontroller_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + printf("DISCRETE READ: time_stamp(us):%u, mb_addr:%u, type:%u, st_address:0x%.4x, size:%u\r\n", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & MB_EVENT_COILS_RD) { + ESP_ERROR_CHECK(mbcontroller_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + printf("COILS READ: time_stamp(us):%u, mb_addr:%u, type:%u, st_address:0x%.4x, size:%u\r\n", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } + } + // Destroy of Modbus controller once get maximum value of data_chan0 + printf("Modbus controller destroyed."); + ESP_ERROR_CHECK(mbcontroller_destroy()); +}