mbrtu.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. /* ----------------------- Defines ------------------------------------------*/
  41. #define MB_SER_PDU_SIZE_MIN 4 /*!< Minimum size of a Modbus RTU frame. */
  42. #define MB_SER_PDU_SIZE_MAX 256 /*!< Maximum size of a Modbus RTU frame. */
  43. #define MB_SER_PDU_SIZE_CRC 2 /*!< Size of CRC field in PDU. */
  44. #define MB_SER_PDU_ADDR_OFF 0 /*!< Offset of slave address in Ser-PDU. */
  45. #define MB_SER_PDU_PDU_OFF 1 /*!< Offset of Modbus-PDU in Ser-PDU. */
  46. /* ----------------------- Type definitions ---------------------------------*/
  47. typedef enum
  48. {
  49. STATE_RX_INIT, /*!< Receiver is in initial state. */
  50. STATE_RX_IDLE, /*!< Receiver is in idle state. */
  51. STATE_RX_RCV, /*!< Frame is beeing received. */
  52. STATE_RX_ERROR /*!< If the frame is invalid. */
  53. } eMBRcvState;
  54. typedef enum
  55. {
  56. STATE_TX_IDLE, /*!< Transmitter is in idle state. */
  57. STATE_TX_XMIT /*!< Transmitter is in transfer state. */
  58. } eMBSndState;
  59. /* ----------------------- Static variables ---------------------------------*/
  60. static volatile eMBSndState eSndState;
  61. static volatile eMBRcvState eRcvState;
  62. volatile UCHAR ucRTUBuf[MB_SER_PDU_SIZE_MAX];
  63. static volatile UCHAR *pucSndBufferCur;
  64. static volatile USHORT usSndBufferCount;
  65. static volatile USHORT usRcvBufferPos;
  66. /* ----------------------- Start implementation -----------------------------*/
  67. eMBErrorCode
  68. eMBRTUInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity )
  69. {
  70. eMBErrorCode eStatus = MB_ENOERR;
  71. ULONG usTimerT35_50us;
  72. ( void )ucSlaveAddress;
  73. ENTER_CRITICAL_SECTION( );
  74. /* Modbus RTU uses 8 Databits. */
  75. if( xMBPortSerialInit( ucPort, ulBaudRate, 8, eParity ) != TRUE )
  76. {
  77. eStatus = MB_EPORTERR;
  78. }
  79. else
  80. {
  81. /* If baudrate > 19200 then we should use the fixed timer values
  82. * t35 = 1750us. Otherwise t35 must be 3.5 times the character time.
  83. */
  84. if( ulBaudRate > 19200 )
  85. {
  86. usTimerT35_50us = 35; /* 1800us. */
  87. }
  88. else
  89. {
  90. /* The timer reload value for a character is given by:
  91. *
  92. * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 )
  93. * = 11 * Ticks_per_1s / Baudrate
  94. * = 220000 / Baudrate
  95. * The reload for t3.5 is 1.5 times this value and similary
  96. * for t3.5.
  97. */
  98. usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate );
  99. }
  100. if( xMBPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE )
  101. {
  102. eStatus = MB_EPORTERR;
  103. }
  104. }
  105. EXIT_CRITICAL_SECTION( );
  106. return eStatus;
  107. }
  108. void
  109. eMBRTUStart( void )
  110. {
  111. ENTER_CRITICAL_SECTION( );
  112. /* Initially the receiver is in the state STATE_RX_INIT. we start
  113. * the timer and if no character is received within t3.5 we change
  114. * to STATE_RX_IDLE. This makes sure that we delay startup of the
  115. * modbus protocol stack until the bus is free.
  116. */
  117. eRcvState = STATE_RX_INIT;
  118. vMBPortSerialEnable( TRUE, FALSE );
  119. vMBPortTimersEnable( );
  120. EXIT_CRITICAL_SECTION( );
  121. }
  122. void
  123. eMBRTUStop( void )
  124. {
  125. ENTER_CRITICAL_SECTION( );
  126. vMBPortSerialEnable( FALSE, FALSE );
  127. vMBPortTimersDisable( );
  128. EXIT_CRITICAL_SECTION( );
  129. }
  130. eMBErrorCode
  131. eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength )
  132. {
  133. BOOL xFrameReceived = FALSE;
  134. eMBErrorCode eStatus = MB_ENOERR;
  135. ENTER_CRITICAL_SECTION( );
  136. //assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX );
  137. if(usRcvBufferPos >= MB_SER_PDU_SIZE_MAX)
  138. {
  139. eMBDisable();
  140. EXIT_CRITICAL_SECTION( );
  141. return eStatus;
  142. }
  143. /* Length and CRC check */
  144. if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN )
  145. && ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) )
  146. {
  147. /* Save the address field. All frames are passed to the upper layed
  148. * and the decision if a frame is used is done there.
  149. */
  150. *pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF];
  151. /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus
  152. * size of address field and CRC checksum.
  153. */
  154. *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC );
  155. /* Return the start of the Modbus PDU to the caller. */
  156. *pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF];
  157. xFrameReceived = TRUE;
  158. }
  159. else
  160. {
  161. eStatus = MB_EIO;
  162. }
  163. EXIT_CRITICAL_SECTION( );
  164. return eStatus;
  165. }
  166. eMBErrorCode
  167. eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength )
  168. {
  169. eMBErrorCode eStatus = MB_ENOERR;
  170. USHORT usCRC16;
  171. ENTER_CRITICAL_SECTION( );
  172. /* Check if the receiver is still in idle state. If not we where to
  173. * slow with processing the received frame and the master sent another
  174. * frame on the network. We have to abort sending the frame.
  175. */
  176. if( eRcvState == STATE_RX_IDLE )
  177. {
  178. /* First byte before the Modbus-PDU is the slave address. */
  179. pucSndBufferCur = ( UCHAR * ) pucFrame - 1;
  180. usSndBufferCount = 1;
  181. /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */
  182. pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress;
  183. usSndBufferCount += usLength;
  184. /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */
  185. usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount );
  186. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF );
  187. ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 );
  188. //
  189. //插入以下代码完成一次发送,启动发送完成中断
  190. //
  191. xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur );
  192. pucSndBufferCur++;
  193. usSndBufferCount--;
  194. //
  195. //结束
  196. //
  197. /* Activate the transmitter. */
  198. eSndState = STATE_TX_XMIT;
  199. vMBPortSerialEnable( FALSE, TRUE );
  200. }
  201. else
  202. {
  203. eStatus = MB_EIO;
  204. }
  205. EXIT_CRITICAL_SECTION( );
  206. return eStatus;
  207. }
  208. BOOL
  209. xMBRTUReceiveFSM( void )
  210. {
  211. BOOL xTaskNeedSwitch = FALSE;
  212. UCHAR ucByte;
  213. //assert( eSndState == STATE_TX_IDLE );
  214. if(eSndState != STATE_TX_IDLE)
  215. {
  216. eMBDisable();
  217. return xTaskNeedSwitch;
  218. }
  219. /* Always read the character. */
  220. ( void )xMBPortSerialGetByte( ( CHAR * ) & ucByte );
  221. switch ( eRcvState )
  222. {
  223. /* If we have received a character in the init state we have to
  224. * wait until the frame is finished.
  225. */
  226. case STATE_RX_INIT:
  227. vMBPortTimersEnable( );
  228. break;
  229. /* In the error state we wait until all characters in the
  230. * damaged frame are transmitted.
  231. */
  232. case STATE_RX_ERROR:
  233. vMBPortTimersEnable( );
  234. break;
  235. /* In the idle state we wait for a new character. If a character
  236. * is received the t1.5 and t3.5 timers are started and the
  237. * receiver is in the state STATE_RX_RECEIVCE.
  238. */
  239. case STATE_RX_IDLE:
  240. usRcvBufferPos = 0;
  241. ucRTUBuf[usRcvBufferPos++] = ucByte;
  242. eRcvState = STATE_RX_RCV;
  243. /* Enable t3.5 timers. */
  244. vMBPortTimersEnable( );
  245. break;
  246. /* We are currently receiving a frame. Reset the timer after
  247. * every character received. If more than the maximum possible
  248. * number of bytes in a modbus frame is received the frame is
  249. * ignored.
  250. */
  251. case STATE_RX_RCV:
  252. if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX )
  253. {
  254. ucRTUBuf[usRcvBufferPos++] = ucByte;
  255. }
  256. else
  257. {
  258. eRcvState = STATE_RX_ERROR;
  259. }
  260. vMBPortTimersEnable( );
  261. break;
  262. }
  263. return xTaskNeedSwitch;
  264. }
  265. BOOL
  266. xMBRTUTransmitFSM( void )
  267. {
  268. BOOL xNeedPoll = FALSE;
  269. //assert( eRcvState == STATE_RX_IDLE );
  270. if(eRcvState != STATE_RX_IDLE)
  271. {
  272. eMBDisable();
  273. return xNeedPoll;
  274. }
  275. // if(eRcvState != STATE_RX_IDLE)
  276. // {
  277. // eMBDisable();
  278. // eMBRTUStart();
  279. // return xNeedPoll;
  280. // }
  281. switch ( eSndState )
  282. {
  283. /* We should not get a transmitter event if the transmitter is in
  284. * idle state. */
  285. case STATE_TX_IDLE:
  286. /* enable receiver/disable transmitter. */
  287. vMBPortSerialEnable( TRUE, FALSE );
  288. break;
  289. case STATE_TX_XMIT:
  290. /* check if we are finished. */
  291. if( usSndBufferCount != 0 )
  292. {
  293. xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur );
  294. pucSndBufferCur++; /* next byte in sendbuffer. */
  295. usSndBufferCount--;
  296. }
  297. else
  298. {
  299. xNeedPoll = xMBPortEventPost( EV_FRAME_SENT );
  300. /* Disable transmitter. This prevents another transmit buffer
  301. * empty interrupt. */
  302. eSndState = STATE_TX_IDLE;
  303. vMBPortSerialEnable( TRUE, FALSE );
  304. //eSndState = STATE_TX_IDLE;
  305. }
  306. break;
  307. }
  308. return xNeedPoll;
  309. }
  310. BOOL
  311. xMBRTUTimerT35Expired( void )
  312. {
  313. BOOL xNeedPoll = FALSE;
  314. switch ( eRcvState )
  315. {
  316. /* Timer t35 expired. Startup phase is finished. */
  317. case STATE_RX_INIT:
  318. xNeedPoll = xMBPortEventPost( EV_READY );
  319. break;
  320. /* A frame was received and t35 expired. Notify the listener that
  321. * a new frame was received. */
  322. case STATE_RX_RCV:
  323. xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED );
  324. break;
  325. /* An error occured while receiving the frame. */
  326. case STATE_RX_ERROR:
  327. break;
  328. /* Function called in an illegal state. */
  329. default:
  330. {
  331. eMBDisable();
  332. eRcvState = STATE_RX_IDLE;
  333. return xNeedPoll;
  334. // assert( ( eRcvState == STATE_RX_INIT ) ||
  335. // ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_ERROR ) );
  336. }
  337. }
  338. vMBPortTimersDisable( );
  339. eRcvState = STATE_RX_IDLE;
  340. return xNeedPoll;
  341. }