mbrtu.c 11 KB

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