mbrtu.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. */
  29. /* ----------------------- System includes ----------------------------------*/
  30. #include "stdlib.h"
  31. #include "string.h"
  32. /* ----------------------- Platform includes --------------------------------*/
  33. #include "port.h"
  34. /* ----------------------- Modbus includes ----------------------------------*/
  35. #include "mb.h"
  36. #include "mbrtu.h"
  37. #include "mbframe.h"
  38. #include "mbcrc.h"
  39. #include "mbport.h"
  40. //#include "tinystdio.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,
  70. eMBParity eParity, unsigned int stop_bit )
  71. {
  72. eMBErrorCode eStatus = MB_ENOERR;
  73. ULONG usTimerT35_50us;
  74. ( void )ucSlaveAddress;
  75. ENTER_CRITICAL_SECTION( );
  76. /* Modbus RTU uses 8 Databits. */
  77. if( xMBPortSerialInit( ucPort, ulBaudRate, 8, eParity, stop_bit ) != TRUE )
  78. {
  79. eStatus = MB_EPORTERR;
  80. }
  81. else
  82. {
  83. /* If baudrate > 19200 then we should use the fixed timer values
  84. * t35 = 1750us. Otherwise t35 must be 3.5 times the character time.
  85. */
  86. if( ulBaudRate > 19200 )
  87. {
  88. usTimerT35_50us = 35; /* 1800us. */
  89. }
  90. else
  91. {
  92. /* The timer reload value for a character is given by:
  93. *
  94. * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 )
  95. * = 11 * Ticks_per_1s / Baudrate
  96. * = 220000 / Baudrate
  97. * The reload for t3.5 is 1.5 times this value and similary
  98. * for t3.5.
  99. */
  100. usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate );
  101. }
  102. if( xMBPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE )
  103. {
  104. eStatus = MB_EPORTERR;
  105. }
  106. }
  107. EXIT_CRITICAL_SECTION( );
  108. return eStatus;
  109. }
  110. void
  111. eMBRTUStart( void )
  112. {
  113. ENTER_CRITICAL_SECTION( );
  114. /* Initially the receiver is in the state STATE_RX_INIT. we start
  115. * the timer and if no character is received within t3.5 we change
  116. * to STATE_RX_IDLE. This makes sure that we delay startup of the
  117. * modbus protocol stack until the bus is free.
  118. */
  119. eRcvState = STATE_RX_INIT;
  120. vMBPortSerialEnable( TRUE, FALSE );
  121. vMBPortTimersEnable( );
  122. EXIT_CRITICAL_SECTION( );
  123. }
  124. void
  125. eMBRTUStop( void )
  126. {
  127. ENTER_CRITICAL_SECTION( );
  128. vMBPortSerialEnable( FALSE, FALSE );
  129. vMBPortTimersDisable( );
  130. EXIT_CRITICAL_SECTION( );
  131. }
  132. eMBErrorCode
  133. eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength )
  134. {
  135. BOOL xFrameReceived = FALSE;
  136. eMBErrorCode eStatus = MB_ENOERR;
  137. ENTER_CRITICAL_SECTION( );
  138. assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX );
  139. /* Length and CRC check */
  140. if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN )
  141. && ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) )
  142. {
  143. /* Save the address field. All frames are passed to the upper layed
  144. * and the decision if a frame is used is done there.
  145. */
  146. *pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF];
  147. /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus
  148. * size of address field and CRC checksum.
  149. */
  150. *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC );
  151. /* Return the start of the Modbus PDU to the caller. */
  152. *pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF];
  153. xFrameReceived = TRUE;
  154. }
  155. else
  156. {
  157. eStatus = MB_EIO;
  158. }
  159. EXIT_CRITICAL_SECTION( );
  160. return eStatus;
  161. }
  162. eMBErrorCode
  163. eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength )
  164. {
  165. eMBErrorCode eStatus = MB_ENOERR;
  166. USHORT usCRC16;
  167. ENTER_CRITICAL_SECTION( );
  168. /* Check if the receiver is still in idle state. If not we where to
  169. * slow with processing the received frame and the master sent another
  170. * frame on the network. We have to abort sending the frame.
  171. */
  172. if( eRcvState == STATE_RX_IDLE )
  173. {
  174. /* First byte before the Modbus-PDU is the slave address. */
  175. pucSndBufferCur = ( UCHAR * ) pucFrame - 1;
  176. usSndBufferCount = 1;
  177. /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */
  178. pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress;
  179. usSndBufferCount += usLength;
  180. /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */
  181. usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount );
  182. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF );
  183. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 );
  184. //usSndBufferCount++;
  185. /* Activate the transmitter. */
  186. eSndState = STATE_TX_XMIT;
  187. vMBPortSerialEnable( FALSE, TRUE );
  188. }
  189. else
  190. {
  191. eStatus = MB_EIO;
  192. }
  193. EXIT_CRITICAL_SECTION( );
  194. return eStatus;
  195. }
  196. BOOL
  197. xMBRTUReceiveFSM( void )
  198. {
  199. BOOL xTaskNeedSwitch = FALSE;
  200. UCHAR ucByte;
  201. assert( eSndState == STATE_TX_IDLE );
  202. /* Always read the character. */
  203. ( void )xMBPortSerialGetByte( ( CHAR * ) & ucByte );
  204. switch ( eRcvState )
  205. {
  206. /* If we have received a character in the init state we have to
  207. * wait until the frame is finished.
  208. */
  209. case STATE_RX_INIT:
  210. vMBPortTimersEnable( );
  211. break;
  212. /* In the error state we wait until all characters in the
  213. * damaged frame are transmitted.
  214. */
  215. case STATE_RX_ERROR:
  216. vMBPortTimersEnable( );
  217. break;
  218. /* In the idle state we wait for a new character. If a character
  219. * is received the t1.5 and t3.5 timers are started and the
  220. * receiver is in the state STATE_RX_RECEIVCE.
  221. */
  222. case STATE_RX_IDLE:
  223. usRcvBufferPos = 0;
  224. ucRTUBuf[usRcvBufferPos++] = ucByte;
  225. eRcvState = STATE_RX_RCV;
  226. /* Enable t3.5 timers. */
  227. vMBPortTimersEnable( );
  228. break;
  229. /* We are currently receiving a frame. Reset the timer after
  230. * every character received. If more than the maximum possible
  231. * number of bytes in a modbus frame is received the frame is
  232. * ignored.
  233. */
  234. case STATE_RX_RCV:
  235. if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX )
  236. {
  237. ucRTUBuf[usRcvBufferPos++] = ucByte;
  238. }
  239. else
  240. {
  241. eRcvState = STATE_RX_ERROR;
  242. }
  243. vMBPortTimersEnable( );
  244. break;
  245. }
  246. return xTaskNeedSwitch;
  247. }
  248. BOOL
  249. xMBRTUTransmitFSM( void )
  250. {
  251. BOOL xNeedPoll = FALSE;
  252. assert( eRcvState == STATE_RX_IDLE );
  253. switch ( eSndState )
  254. {
  255. /* We should not get a transmitter event if the transmitter is in
  256. * idle state. */
  257. case STATE_TX_IDLE:
  258. /* enable receiver/disable transmitter. */
  259. vMBPortSerialEnable( TRUE, FALSE );
  260. break;
  261. case STATE_TX_XMIT:
  262. /* check if we are finished. */
  263. if( usSndBufferCount != 0 )
  264. {
  265. xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur );
  266. //printf("%X\r\n", *pucSndBufferCur);
  267. pucSndBufferCur++; /* next byte in sendbuffer. */
  268. usSndBufferCount--;
  269. }
  270. else
  271. {
  272. xNeedPoll = xMBPortEventPost( EV_FRAME_SENT );
  273. //printf("mb_event: EV_FRAME_SENT\r\n");
  274. /* Disable transmitter. This prevents another transmit buffer
  275. * empty interrupt. */
  276. vMBPortSerialEnable( TRUE, FALSE );
  277. eSndState = STATE_TX_IDLE;
  278. }
  279. break;
  280. }
  281. return xNeedPoll;
  282. }
  283. BOOL
  284. xMBRTUTimerT35Expired( void )
  285. {
  286. BOOL xNeedPoll = FALSE;
  287. switch ( eRcvState )
  288. {
  289. /* Timer t35 expired. Startup phase is finished. */
  290. case STATE_RX_INIT:
  291. xNeedPoll = xMBPortEventPost( EV_READY );
  292. //printf("mb_event: EV_READY\r\n");
  293. break;
  294. /* A frame was received and t35 expired. Notify the listener that
  295. * a new frame was received. */
  296. case STATE_RX_RCV:
  297. xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED );
  298. //printf("mb_event: EV_FRAME_RECEIVED\r\n");
  299. break;
  300. /* An error occured while receiving the frame. */
  301. case STATE_RX_ERROR:
  302. break;
  303. /* Function called in an illegal state. */
  304. default:
  305. assert( ( eRcvState == STATE_RX_INIT ) ||
  306. ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_ERROR ) );
  307. }
  308. vMBPortTimersDisable( );
  309. eRcvState = STATE_RX_IDLE;
  310. return xNeedPoll;
  311. }