mbrtu.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU.
  3. * Copyright (c) 2006-2018 Christian Walter <cwalter@embedded-solutions.at>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * File: $Id: mbrtu.c,v 1.18 2007/09/12 10:15:56 wolti Exp $
  29. */
  30. /* ----------------------- System includes ----------------------------------*/
  31. #include "stdlib.h"
  32. #include "string.h"
  33. /* ----------------------- Platform includes --------------------------------*/
  34. #include "port.h"
  35. /* ----------------------- Modbus includes ----------------------------------*/
  36. #include "mb.h"
  37. #include "mbrtu.h"
  38. #include "mbframe.h"
  39. #include "mbcrc.h"
  40. #include "mbport.h"
  41. /* ----------------------- Defines ------------------------------------------*/
  42. #define MB_SER_PDU_SIZE_MIN 4 /*!< Minimum size of a Modbus RTU frame. */
  43. #define MB_SER_PDU_SIZE_MAX 256 /*!< Maximum size of a Modbus RTU frame. */
  44. #define MB_SER_PDU_SIZE_CRC 2 /*!< Size of CRC field in PDU. */
  45. #define MB_SER_PDU_ADDR_OFF 0 /*!< Offset of slave address in Ser-PDU. */
  46. #define MB_SER_PDU_PDU_OFF 1 /*!< Offset of Modbus-PDU in Ser-PDU. */
  47. /* ----------------------- Type definitions ---------------------------------*/
  48. typedef enum
  49. {
  50. STATE_RX_INIT, /*!< Receiver is in initial state. */
  51. STATE_RX_IDLE, /*!< Receiver is in idle state. */
  52. STATE_RX_RCV, /*!< Frame is beeing received. */
  53. STATE_RX_ERROR /*!< If the frame is invalid. */
  54. } eMBRcvState;
  55. typedef enum
  56. {
  57. STATE_TX_IDLE, /*!< Transmitter is in idle state. */
  58. STATE_TX_XMIT /*!< Transmitter is in transfer state. */
  59. } eMBSndState;
  60. /* ----------------------- Static variables ---------------------------------*/
  61. static volatile eMBSndState eSndState;
  62. static volatile eMBRcvState eRcvState;
  63. volatile UCHAR ucRTUBuf[MB_SER_PDU_SIZE_MAX];
  64. static volatile UCHAR *pucSndBufferCur;
  65. static volatile USHORT usSndBufferCount;
  66. static volatile USHORT usRcvBufferPos;
  67. /* ----------------------- Start implementation -----------------------------*/
  68. eMBErrorCode
  69. eMBRTUInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity )
  70. {
  71. eMBErrorCode eStatus = MB_ENOERR;
  72. ULONG usTimerT35_50us;
  73. ( void )ucSlaveAddress;
  74. ENTER_CRITICAL_SECTION( );
  75. /* Modbus RTU uses 8 Databits. */
  76. /* If baudrate > 19200 then we should use the fixed timer values
  77. * t35 = 1750us. Otherwise t35 must be 3.5 times the character time.
  78. */
  79. if( ulBaudRate > 19200 )
  80. {
  81. usTimerT35_50us = 35; /* 1800us. */
  82. }
  83. else
  84. {
  85. /* The timer reload value for a character is given by:
  86. *
  87. * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 )
  88. * = 11 * Ticks_per_1s / Baudrate
  89. * = 220000 / Baudrate
  90. * The reload for t3.5 is 1.5 times this value and similary
  91. * for t3.5.
  92. */
  93. usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate );
  94. }
  95. if( xMBPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE )
  96. {
  97. eStatus = MB_EPORTERR;
  98. }
  99. else if( xMBPortSerialInit( ucPort, ulBaudRate, 8, eParity ) != TRUE )
  100. {
  101. eStatus = MB_EPORTERR;
  102. }
  103. EXIT_CRITICAL_SECTION( );
  104. return eStatus;
  105. }
  106. void
  107. eMBRTUStart( void )
  108. {
  109. ENTER_CRITICAL_SECTION( );
  110. /* Initially the receiver is in the state STATE_RX_INIT. we start
  111. * the timer and if no character is received within t3.5 we change
  112. * to STATE_RX_IDLE. This makes sure that we delay startup of the
  113. * modbus protocol stack until the bus is free.
  114. */
  115. eRcvState = STATE_RX_INIT;
  116. vMBPortSerialEnable( TRUE, FALSE );
  117. vMBPortTimersEnable( );
  118. EXIT_CRITICAL_SECTION( );
  119. }
  120. void
  121. eMBRTUStop( void )
  122. {
  123. ENTER_CRITICAL_SECTION( );
  124. vMBPortSerialEnable( FALSE, FALSE );
  125. vMBPortTimersDisable( );
  126. EXIT_CRITICAL_SECTION( );
  127. }
  128. eMBErrorCode
  129. eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength )
  130. {
  131. eMBErrorCode eStatus = MB_ENOERR;
  132. ENTER_CRITICAL_SECTION( );
  133. RT_ASSERT( usRcvBufferPos <= MB_SER_PDU_SIZE_MAX );
  134. /* Length and CRC check */
  135. if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN )
  136. && ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) )
  137. {
  138. /* Save the address field. All frames are passed to the upper layed
  139. * and the decision if a frame is used is done there.
  140. */
  141. *pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF];
  142. /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus
  143. * size of address field and CRC checksum.
  144. */
  145. *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC );
  146. /* Return the start of the Modbus PDU to the caller. */
  147. *pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF];
  148. }
  149. else
  150. {
  151. eStatus = MB_EIO;
  152. }
  153. EXIT_CRITICAL_SECTION( );
  154. return eStatus;
  155. }
  156. eMBErrorCode
  157. eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength )
  158. {
  159. eMBErrorCode eStatus = MB_ENOERR;
  160. USHORT usCRC16;
  161. ENTER_CRITICAL_SECTION( );
  162. /* Check if the receiver is still in idle state. If not we where to
  163. * slow with processing the received frame and the master sent another
  164. * frame on the network. We have to abort sending the frame.
  165. */
  166. if( eRcvState == STATE_RX_IDLE )
  167. {
  168. /* First byte before the Modbus-PDU is the slave address. */
  169. pucSndBufferCur = ( UCHAR * ) pucFrame - 1;
  170. usSndBufferCount = 1;
  171. /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */
  172. pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress;
  173. usSndBufferCount += usLength;
  174. /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */
  175. usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount );
  176. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF );
  177. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 );
  178. /* Activate the transmitter. */
  179. eSndState = STATE_TX_XMIT;
  180. vMBPortSerialEnable( FALSE, TRUE );
  181. }
  182. else
  183. {
  184. eStatus = MB_EIO;
  185. }
  186. EXIT_CRITICAL_SECTION( );
  187. return eStatus;
  188. }
  189. BOOL
  190. xMBRTUReceiveFSM( void )
  191. {
  192. BOOL xTaskNeedSwitch = FALSE;
  193. UCHAR ucByte;
  194. RT_ASSERT( eSndState == STATE_TX_IDLE );
  195. /* Always read the character. */
  196. ( void )xMBPortSerialGetByte( ( CHAR * ) & ucByte );
  197. switch ( eRcvState )
  198. {
  199. /* If we have received a character in the init state we have to
  200. * wait until the frame is finished.
  201. */
  202. case STATE_RX_INIT:
  203. vMBPortTimersEnable( );
  204. break;
  205. /* In the error state we wait until all characters in the
  206. * damaged frame are transmitted.
  207. */
  208. case STATE_RX_ERROR:
  209. vMBPortTimersEnable( );
  210. break;
  211. /* In the idle state we wait for a new character. If a character
  212. * is received the t1.5 and t3.5 timers are started and the
  213. * receiver is in the state STATE_RX_RECEIVCE.
  214. */
  215. case STATE_RX_IDLE:
  216. usRcvBufferPos = 0;
  217. ucRTUBuf[usRcvBufferPos++] = ucByte;
  218. eRcvState = STATE_RX_RCV;
  219. /* Enable t3.5 timers. */
  220. vMBPortTimersEnable( );
  221. break;
  222. /* We are currently receiving a frame. Reset the timer after
  223. * every character received. If more than the maximum possible
  224. * number of bytes in a modbus frame is received the frame is
  225. * ignored.
  226. */
  227. case STATE_RX_RCV:
  228. if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX )
  229. {
  230. ucRTUBuf[usRcvBufferPos++] = ucByte;
  231. }
  232. else
  233. {
  234. eRcvState = STATE_RX_ERROR;
  235. }
  236. vMBPortTimersEnable();
  237. break;
  238. }
  239. return xTaskNeedSwitch;
  240. }
  241. BOOL
  242. xMBRTUTransmitFSM( void )
  243. {
  244. BOOL xNeedPoll = FALSE;
  245. RT_ASSERT( eRcvState == STATE_RX_IDLE );
  246. switch ( eSndState )
  247. {
  248. /* We should not get a transmitter event if the transmitter is in
  249. * idle state. */
  250. case STATE_TX_IDLE:
  251. /* enable receiver/disable transmitter. */
  252. vMBPortSerialEnable( TRUE, FALSE );
  253. break;
  254. case STATE_TX_XMIT:
  255. /* check if we are finished. */
  256. if( usSndBufferCount != 0 )
  257. {
  258. xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur );
  259. pucSndBufferCur++; /* next byte in sendbuffer. */
  260. usSndBufferCount--;
  261. }
  262. else
  263. {
  264. xNeedPoll = xMBPortEventPost( EV_FRAME_SENT );
  265. /* Disable transmitter. This prevents another transmit buffer
  266. * empty interrupt. */
  267. eSndState = STATE_TX_IDLE;
  268. vMBPortSerialEnable( TRUE, FALSE );
  269. }
  270. break;
  271. }
  272. return xNeedPoll;
  273. }
  274. BOOL
  275. xMBRTUTimerT35Expired( void )
  276. {
  277. BOOL xNeedPoll = FALSE;
  278. switch ( eRcvState )
  279. {
  280. /* Timer t35 expired. Startup phase is finished. */
  281. case STATE_RX_INIT:
  282. xNeedPoll = xMBPortEventPost( EV_READY );
  283. break;
  284. /* A frame was received and t35 expired. Notify the listener that
  285. * a new frame was received. */
  286. case STATE_RX_RCV:
  287. xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED );
  288. break;
  289. /* An error occured while receiving the frame. */
  290. case STATE_RX_ERROR:
  291. break;
  292. /* Function called in an illegal state. */
  293. default:
  294. RT_ASSERT( ( eRcvState == STATE_RX_INIT ) ||
  295. ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_ERROR ) );
  296. break;
  297. }
  298. vMBPortTimersDisable( );
  299. eRcvState = STATE_RX_IDLE;
  300. return xNeedPoll;
  301. }