mbrtu.c 11 KB

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