mb.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 "mbconfig.h"
  37. #include "mbframe.h"
  38. #include "mbproto.h"
  39. #include "mbfunc.h"
  40. #include "mbport.h"
  41. #if MB_RTU_ENABLED == 1
  42. #include "mbrtu.h"
  43. #endif
  44. #if MB_ASCII_ENABLED == 1
  45. #include "mbascii.h"
  46. #endif
  47. #if MB_TCP_ENABLED == 1
  48. #include "mbtcp.h"
  49. #endif
  50. #ifndef MB_PORT_HAS_CLOSE
  51. #define MB_PORT_HAS_CLOSE 0
  52. #endif
  53. //#include "tinystdio.h"
  54. UCHAR rcvAddress;
  55. /* ----------------------- Static variables ---------------------------------*/
  56. static UCHAR ucMBAddress;
  57. static eMBMode eMBCurrentMode;
  58. static enum
  59. {
  60. STATE_ENABLED,
  61. STATE_DISABLED,
  62. STATE_NOT_INITIALIZED
  63. } eMBState = STATE_NOT_INITIALIZED;
  64. /* Functions pointer which are initialized in eMBInit( ). Depending on the
  65. * mode (RTU or ASCII) the are set to the correct implementations.
  66. */
  67. static peMBFrameSend peMBFrameSendCur;
  68. static pvMBFrameStart pvMBFrameStartCur;
  69. static pvMBFrameStop pvMBFrameStopCur;
  70. static peMBFrameReceive peMBFrameReceiveCur;
  71. static pvMBFrameClose pvMBFrameCloseCur;
  72. /* Callback functions required by the porting layer. They are called when
  73. * an external event has happend which includes a timeout or the reception
  74. * or transmission of a character.
  75. */
  76. BOOL( *pxMBFrameCBByteReceived ) ( void );
  77. BOOL( *pxMBFrameCBTransmitterEmpty ) ( void );
  78. BOOL( *pxMBPortCBTimerExpired ) ( void );
  79. BOOL( *pxMBFrameCBReceiveFSMCur ) ( void );
  80. BOOL( *pxMBFrameCBTransmitFSMCur ) ( void );
  81. /* An array of Modbus functions handlers which associates Modbus function
  82. * codes with implementing functions.
  83. */
  84. static xMBFunctionHandler xFuncHandlers[MB_FUNC_HANDLERS_MAX] = {
  85. #if MB_FUNC_OTHER_REP_SLAVEID_ENABLED > 0
  86. {MB_FUNC_OTHER_REPORT_SLAVEID, eMBFuncReportSlaveID},
  87. #endif
  88. #if MB_FUNC_READ_INPUT_ENABLED > 0
  89. {MB_FUNC_READ_INPUT_REGISTER, eMBFuncReadInputRegister},
  90. #endif
  91. #if MB_FUNC_READ_HOLDING_ENABLED > 0
  92. {MB_FUNC_READ_HOLDING_REGISTER, eMBFuncReadHoldingRegister},
  93. #endif
  94. #if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0
  95. {MB_FUNC_WRITE_MULTIPLE_REGISTERS, eMBFuncWriteMultipleHoldingRegister},
  96. #endif
  97. #if MB_FUNC_WRITE_HOLDING_ENABLED > 0
  98. {MB_FUNC_WRITE_REGISTER, eMBFuncWriteHoldingRegister},
  99. #endif
  100. #if MB_FUNC_READWRITE_HOLDING_ENABLED > 0
  101. {MB_FUNC_READWRITE_MULTIPLE_REGISTERS, eMBFuncReadWriteMultipleHoldingRegister},
  102. #endif
  103. #if MB_FUNC_READ_COILS_ENABLED > 0
  104. {MB_FUNC_READ_COILS, eMBFuncReadCoils},
  105. #endif
  106. #if MB_FUNC_WRITE_COIL_ENABLED > 0
  107. {MB_FUNC_WRITE_SINGLE_COIL, eMBFuncWriteCoil},
  108. #endif
  109. #if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0
  110. {MB_FUNC_WRITE_MULTIPLE_COILS, eMBFuncWriteMultipleCoils},
  111. #endif
  112. #if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0
  113. {MB_FUNC_READ_DISCRETE_INPUTS, eMBFuncReadDiscreteInputs},
  114. #endif
  115. #if MB_FUNC_UPDATE_ENABLED > 0
  116. {MB_FUNC_UPDATE, eMBFuncUpdate},
  117. #endif
  118. #if MB_FUNC_SET_ADDR_ID_ENABLED > 0
  119. {MB_FUNC_SET_ADDR_ID, eMBFuncSetAddrId},
  120. #endif
  121. #if MB_FUNC_SET_ADDR_SERIAL_ENABLED > 0
  122. {MB_FUNC_SET_ADDR_SERIAL, eMBFuncSetAddrSerial}
  123. #endif
  124. };
  125. /* ----------------------- Start implementation -----------------------------*/
  126. eMBErrorCode
  127. eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate,
  128. eMBParity eParity, unsigned int stop_bit )
  129. {
  130. eMBErrorCode eStatus = MB_ENOERR;
  131. /* check preconditions */
  132. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  133. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  134. {
  135. eStatus = MB_EINVAL;
  136. }
  137. else
  138. {
  139. ucMBAddress = ucSlaveAddress;
  140. switch ( eMode )
  141. {
  142. #if MB_RTU_ENABLED > 0
  143. case MB_RTU:
  144. pvMBFrameStartCur = eMBRTUStart;
  145. pvMBFrameStopCur = eMBRTUStop;
  146. peMBFrameSendCur = eMBRTUSend;
  147. peMBFrameReceiveCur = eMBRTUReceive;
  148. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
  149. pxMBFrameCBByteReceived = xMBRTUReceiveFSM;
  150. pxMBFrameCBTransmitterEmpty = xMBRTUTransmitFSM;
  151. pxMBPortCBTimerExpired = xMBRTUTimerT35Expired;
  152. eStatus = eMBRTUInit( ucMBAddress, ucPort, ulBaudRate, eParity, stop_bit );
  153. break;
  154. #endif
  155. #if MB_ASCII_ENABLED > 0
  156. case MB_ASCII:
  157. pvMBFrameStartCur = eMBASCIIStart;
  158. pvMBFrameStopCur = eMBASCIIStop;
  159. peMBFrameSendCur = eMBASCIISend;
  160. peMBFrameReceiveCur = eMBASCIIReceive;
  161. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
  162. pxMBFrameCBByteReceived = xMBASCIIReceiveFSM;
  163. pxMBFrameCBTransmitterEmpty = xMBASCIITransmitFSM;
  164. pxMBPortCBTimerExpired = xMBASCIITimerT1SExpired;
  165. eStatus = eMBASCIIInit( ucMBAddress, ucPort, ulBaudRate, eParity );
  166. break;
  167. #endif
  168. default:
  169. eStatus = MB_EINVAL;
  170. }
  171. if( eStatus == MB_ENOERR )
  172. {
  173. if( !xMBPortEventInit( ) )
  174. {
  175. /* port dependent event module initalization failed. */
  176. eStatus = MB_EPORTERR;
  177. }
  178. else
  179. {
  180. eMBCurrentMode = eMode;
  181. eMBState = STATE_DISABLED;
  182. }
  183. }
  184. }
  185. return eStatus;
  186. }
  187. #if MB_TCP_ENABLED > 0
  188. eMBErrorCode
  189. eMBTCPInit( USHORT ucTCPPort )
  190. {
  191. eMBErrorCode eStatus = MB_ENOERR;
  192. if( ( eStatus = eMBTCPDoInit( ucTCPPort ) ) != MB_ENOERR )
  193. {
  194. eMBState = STATE_DISABLED;
  195. }
  196. else if( !xMBPortEventInit( ) )
  197. {
  198. /* Port dependent event module initalization failed. */
  199. eStatus = MB_EPORTERR;
  200. }
  201. else
  202. {
  203. pvMBFrameStartCur = eMBTCPStart;
  204. pvMBFrameStopCur = eMBTCPStop;
  205. peMBFrameReceiveCur = eMBTCPReceive;
  206. peMBFrameSendCur = eMBTCPSend;
  207. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBTCPPortClose : NULL;
  208. ucMBAddress = MB_TCP_PSEUDO_ADDRESS;
  209. eMBCurrentMode = MB_TCP;
  210. eMBState = STATE_DISABLED;
  211. }
  212. return eStatus;
  213. }
  214. #endif
  215. eMBErrorCode
  216. eMBRegisterCB( UCHAR ucFunctionCode, pxMBFunctionHandler pxHandler )
  217. {
  218. int i;
  219. eMBErrorCode eStatus;
  220. if( ( 0 < ucFunctionCode ) && ( ucFunctionCode <= 127 ) )
  221. {
  222. ENTER_CRITICAL_SECTION( );
  223. if( pxHandler != NULL )
  224. {
  225. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  226. {
  227. if( ( xFuncHandlers[i].pxHandler == NULL ) ||
  228. ( xFuncHandlers[i].pxHandler == pxHandler ) )
  229. {
  230. xFuncHandlers[i].ucFunctionCode = ucFunctionCode;
  231. xFuncHandlers[i].pxHandler = pxHandler;
  232. break;
  233. }
  234. }
  235. eStatus = ( i != MB_FUNC_HANDLERS_MAX ) ? MB_ENOERR : MB_ENORES;
  236. }
  237. else
  238. {
  239. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  240. {
  241. if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode )
  242. {
  243. xFuncHandlers[i].ucFunctionCode = 0;
  244. xFuncHandlers[i].pxHandler = NULL;
  245. break;
  246. }
  247. }
  248. /* Remove can't fail. */
  249. eStatus = MB_ENOERR;
  250. }
  251. EXIT_CRITICAL_SECTION( );
  252. }
  253. else
  254. {
  255. eStatus = MB_EINVAL;
  256. }
  257. return eStatus;
  258. }
  259. eMBErrorCode
  260. eMBClose( void )
  261. {
  262. eMBErrorCode eStatus = MB_ENOERR;
  263. if( eMBState == STATE_DISABLED )
  264. {
  265. if( pvMBFrameCloseCur != NULL )
  266. {
  267. pvMBFrameCloseCur( );
  268. }
  269. }
  270. else
  271. {
  272. eStatus = MB_EILLSTATE;
  273. }
  274. return eStatus;
  275. }
  276. eMBErrorCode
  277. eMBEnable( void )
  278. {
  279. eMBErrorCode eStatus = MB_ENOERR;
  280. if( eMBState == STATE_DISABLED )
  281. {
  282. /* Activate the protocol stack. */
  283. pvMBFrameStartCur( );
  284. eMBState = STATE_ENABLED;
  285. }
  286. else
  287. {
  288. eStatus = MB_EILLSTATE;
  289. }
  290. return eStatus;
  291. }
  292. eMBErrorCode
  293. eMBDisable( void )
  294. {
  295. eMBErrorCode eStatus;
  296. if( eMBState == STATE_ENABLED )
  297. {
  298. pvMBFrameStopCur( );
  299. eMBState = STATE_DISABLED;
  300. eStatus = MB_ENOERR;
  301. }
  302. else if( eMBState == STATE_DISABLED )
  303. {
  304. eStatus = MB_ENOERR;
  305. }
  306. else
  307. {
  308. eStatus = MB_EILLSTATE;
  309. }
  310. return eStatus;
  311. }
  312. eMBErrorCode
  313. eMBPoll( void )
  314. {
  315. static UCHAR *ucMBFrame;
  316. static UCHAR ucRcvAddress;
  317. static UCHAR ucFunctionCode;
  318. static USHORT usLength;
  319. static eMBException eException;
  320. int i;
  321. eMBErrorCode eStatus = MB_ENOERR;
  322. eMBEventType eEvent;
  323. /* Check if the protocol stack is ready. */
  324. if( eMBState != STATE_ENABLED )
  325. {
  326. return MB_EILLSTATE;
  327. }
  328. /* Check if there is a event available. If not return control to caller.
  329. * Otherwise we will handle the event. */
  330. if( xMBPortEventGet( &eEvent ) == TRUE )
  331. {
  332. switch ( eEvent )
  333. {
  334. case EV_READY:
  335. break;
  336. case EV_FRAME_RECEIVED:
  337. eStatus = peMBFrameReceiveCur( &ucRcvAddress, &ucMBFrame, &usLength );
  338. if( eStatus == MB_ENOERR )
  339. {
  340. /* Check if the frame is for us. If not ignore the frame. */
  341. if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) )
  342. {
  343. rcvAddress = ucRcvAddress;
  344. ( void )xMBPortEventPost( EV_EXECUTE );
  345. //printf("mb_event: EV_EXECUTE\r\n");
  346. }
  347. }
  348. break;
  349. case EV_EXECUTE:
  350. ucFunctionCode = ucMBFrame[MB_PDU_FUNC_OFF];
  351. eException = MB_EX_ILLEGAL_FUNCTION;
  352. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  353. {
  354. /* No more function handlers registered. Abort. */
  355. if( xFuncHandlers[i].ucFunctionCode == 0 )
  356. {
  357. break;
  358. }
  359. else if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode )
  360. {
  361. eException = xFuncHandlers[i].pxHandler( ucMBFrame, &usLength );
  362. break;
  363. }
  364. }
  365. /* If the request was not sent to the broadcast address we
  366. * return a reply. */
  367. if( ucRcvAddress != MB_ADDRESS_BROADCAST )
  368. {
  369. if( eException != MB_EX_NONE )
  370. {
  371. /* An exception occured. Build an error frame. */
  372. usLength = 0;
  373. ucMBFrame[usLength++] = ( UCHAR )( ucFunctionCode | MB_FUNC_ERROR );
  374. ucMBFrame[usLength++] = eException;
  375. }
  376. if( ( eMBCurrentMode == MB_ASCII ) && MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS )
  377. {
  378. vMBPortTimersDelay( MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS );
  379. }
  380. eStatus = peMBFrameSendCur( ucMBAddress, ucMBFrame, usLength );
  381. }
  382. break;
  383. case EV_FRAME_SENT:
  384. //printf("recv event: EV_FRAME_SENT\r\n");
  385. break;
  386. }
  387. }
  388. return MB_ENOERR;
  389. }
  390. //
  391. eMBErrorCode
  392. eMBCheckSlaveAddr(UCHAR ucSlaveAddress)
  393. {
  394. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  395. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  396. {
  397. return MB_EINVAL;
  398. }
  399. else
  400. {
  401. return MB_ENOERR;
  402. }
  403. }
  404. //
  405. eMBErrorCode
  406. eMBSetSlaveAddr(UCHAR ucSlaveAddress)
  407. {
  408. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  409. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  410. {
  411. return MB_EINVAL;
  412. }
  413. else
  414. {
  415. ucMBAddress = ucSlaveAddress;
  416. }
  417. return MB_ENOERR;
  418. }