mb.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. #if MB_FUNC_READ_FILE_RECORD_ENABLED > 0
  125. {MB_FUNC_READ_FILE_RECORD, eMBFuncReadFileRecord}
  126. #endif
  127. };
  128. /* ----------------------- Start implementation -----------------------------*/
  129. eMBErrorCode
  130. eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate,
  131. eMBParity eParity, unsigned int stop_bit )
  132. {
  133. eMBErrorCode eStatus = MB_ENOERR;
  134. /* check preconditions */
  135. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  136. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  137. {
  138. eStatus = MB_EINVAL;
  139. }
  140. else
  141. {
  142. ucMBAddress = ucSlaveAddress;
  143. switch ( eMode )
  144. {
  145. #if MB_RTU_ENABLED > 0
  146. case MB_RTU:
  147. pvMBFrameStartCur = eMBRTUStart;
  148. pvMBFrameStopCur = eMBRTUStop;
  149. peMBFrameSendCur = eMBRTUSend;
  150. peMBFrameReceiveCur = eMBRTUReceive;
  151. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
  152. pxMBFrameCBByteReceived = xMBRTUReceiveFSM;
  153. pxMBFrameCBTransmitterEmpty = xMBRTUTransmitFSM;
  154. pxMBPortCBTimerExpired = xMBRTUTimerT35Expired;
  155. eStatus = eMBRTUInit( ucMBAddress, ucPort, ulBaudRate, eParity, stop_bit );
  156. break;
  157. #endif
  158. #if MB_ASCII_ENABLED > 0
  159. case MB_ASCII:
  160. pvMBFrameStartCur = eMBASCIIStart;
  161. pvMBFrameStopCur = eMBASCIIStop;
  162. peMBFrameSendCur = eMBASCIISend;
  163. peMBFrameReceiveCur = eMBASCIIReceive;
  164. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL;
  165. pxMBFrameCBByteReceived = xMBASCIIReceiveFSM;
  166. pxMBFrameCBTransmitterEmpty = xMBASCIITransmitFSM;
  167. pxMBPortCBTimerExpired = xMBASCIITimerT1SExpired;
  168. eStatus = eMBASCIIInit( ucMBAddress, ucPort, ulBaudRate, eParity );
  169. break;
  170. #endif
  171. default:
  172. eStatus = MB_EINVAL;
  173. }
  174. if( eStatus == MB_ENOERR )
  175. {
  176. if( !xMBPortEventInit( ) )
  177. {
  178. /* port dependent event module initalization failed. */
  179. eStatus = MB_EPORTERR;
  180. }
  181. else
  182. {
  183. eMBCurrentMode = eMode;
  184. eMBState = STATE_DISABLED;
  185. }
  186. }
  187. }
  188. return eStatus;
  189. }
  190. #if MB_TCP_ENABLED > 0
  191. eMBErrorCode
  192. eMBTCPInit( USHORT ucTCPPort )
  193. {
  194. eMBErrorCode eStatus = MB_ENOERR;
  195. if( ( eStatus = eMBTCPDoInit( ucTCPPort ) ) != MB_ENOERR )
  196. {
  197. eMBState = STATE_DISABLED;
  198. }
  199. else if( !xMBPortEventInit( ) )
  200. {
  201. /* Port dependent event module initalization failed. */
  202. eStatus = MB_EPORTERR;
  203. }
  204. else
  205. {
  206. pvMBFrameStartCur = eMBTCPStart;
  207. pvMBFrameStopCur = eMBTCPStop;
  208. peMBFrameReceiveCur = eMBTCPReceive;
  209. peMBFrameSendCur = eMBTCPSend;
  210. pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBTCPPortClose : NULL;
  211. ucMBAddress = MB_TCP_PSEUDO_ADDRESS;
  212. eMBCurrentMode = MB_TCP;
  213. eMBState = STATE_DISABLED;
  214. }
  215. return eStatus;
  216. }
  217. #endif
  218. eMBErrorCode
  219. eMBRegisterCB( UCHAR ucFunctionCode, pxMBFunctionHandler pxHandler )
  220. {
  221. int i;
  222. eMBErrorCode eStatus;
  223. if( ( 0 < ucFunctionCode ) && ( ucFunctionCode <= 127 ) )
  224. {
  225. ENTER_CRITICAL_SECTION( );
  226. if( pxHandler != NULL )
  227. {
  228. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  229. {
  230. if( ( xFuncHandlers[i].pxHandler == NULL ) ||
  231. ( xFuncHandlers[i].pxHandler == pxHandler ) )
  232. {
  233. xFuncHandlers[i].ucFunctionCode = ucFunctionCode;
  234. xFuncHandlers[i].pxHandler = pxHandler;
  235. break;
  236. }
  237. }
  238. eStatus = ( i != MB_FUNC_HANDLERS_MAX ) ? MB_ENOERR : MB_ENORES;
  239. }
  240. else
  241. {
  242. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  243. {
  244. if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode )
  245. {
  246. xFuncHandlers[i].ucFunctionCode = 0;
  247. xFuncHandlers[i].pxHandler = NULL;
  248. break;
  249. }
  250. }
  251. /* Remove can't fail. */
  252. eStatus = MB_ENOERR;
  253. }
  254. EXIT_CRITICAL_SECTION( );
  255. }
  256. else
  257. {
  258. eStatus = MB_EINVAL;
  259. }
  260. return eStatus;
  261. }
  262. eMBErrorCode
  263. eMBClose( void )
  264. {
  265. eMBErrorCode eStatus = MB_ENOERR;
  266. if( eMBState == STATE_DISABLED )
  267. {
  268. if( pvMBFrameCloseCur != NULL )
  269. {
  270. pvMBFrameCloseCur( );
  271. }
  272. }
  273. else
  274. {
  275. eStatus = MB_EILLSTATE;
  276. }
  277. return eStatus;
  278. }
  279. eMBErrorCode
  280. eMBEnable( void )
  281. {
  282. eMBErrorCode eStatus = MB_ENOERR;
  283. if( eMBState == STATE_DISABLED )
  284. {
  285. /* Activate the protocol stack. */
  286. pvMBFrameStartCur( );
  287. eMBState = STATE_ENABLED;
  288. }
  289. else
  290. {
  291. eStatus = MB_EILLSTATE;
  292. }
  293. return eStatus;
  294. }
  295. eMBErrorCode
  296. eMBDisable( void )
  297. {
  298. eMBErrorCode eStatus;
  299. if( eMBState == STATE_ENABLED )
  300. {
  301. pvMBFrameStopCur( );
  302. eMBState = STATE_DISABLED;
  303. eStatus = MB_ENOERR;
  304. }
  305. else if( eMBState == STATE_DISABLED )
  306. {
  307. eStatus = MB_ENOERR;
  308. }
  309. else
  310. {
  311. eStatus = MB_EILLSTATE;
  312. }
  313. return eStatus;
  314. }
  315. eMBErrorCode
  316. eMBPoll( void )
  317. {
  318. static UCHAR *ucMBFrame;
  319. static UCHAR ucRcvAddress;
  320. static UCHAR ucFunctionCode;
  321. static USHORT usLength;
  322. static eMBException eException;
  323. int i;
  324. eMBErrorCode eStatus = MB_ENOERR;
  325. eMBEventType eEvent;
  326. /* Check if the protocol stack is ready. */
  327. if( eMBState != STATE_ENABLED )
  328. {
  329. return MB_EILLSTATE;
  330. }
  331. /* Check if there is a event available. If not return control to caller.
  332. * Otherwise we will handle the event. */
  333. if( xMBPortEventGet( &eEvent ) == TRUE )
  334. {
  335. switch ( eEvent )
  336. {
  337. case EV_READY:
  338. break;
  339. case EV_FRAME_RECEIVED:
  340. eStatus = peMBFrameReceiveCur( &ucRcvAddress, &ucMBFrame, &usLength );
  341. if( eStatus == MB_ENOERR )
  342. {
  343. /* Check if the frame is for us. If not ignore the frame. */
  344. if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) )
  345. {
  346. rcvAddress = ucRcvAddress;
  347. ( void )xMBPortEventPost( EV_EXECUTE );
  348. //printf("mb_event: EV_EXECUTE\r\n");
  349. }
  350. }
  351. break;
  352. case EV_EXECUTE:
  353. ucFunctionCode = ucMBFrame[MB_PDU_FUNC_OFF];
  354. eException = MB_EX_ILLEGAL_FUNCTION;
  355. for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ )
  356. {
  357. /* No more function handlers registered. Abort. */
  358. if( xFuncHandlers[i].ucFunctionCode == 0 )
  359. {
  360. break;
  361. }
  362. else if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode )
  363. {
  364. eException = xFuncHandlers[i].pxHandler( ucMBFrame, &usLength );
  365. break;
  366. }
  367. }
  368. /* If the request was not sent to the broadcast address we
  369. * return a reply. */
  370. if( ucRcvAddress != MB_ADDRESS_BROADCAST )
  371. {
  372. if( eException != MB_EX_NONE )
  373. {
  374. /* An exception occured. Build an error frame. */
  375. usLength = 0;
  376. ucMBFrame[usLength++] = ( UCHAR )( ucFunctionCode | MB_FUNC_ERROR );
  377. ucMBFrame[usLength++] = eException;
  378. }
  379. if( ( eMBCurrentMode == MB_ASCII ) && MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS )
  380. {
  381. vMBPortTimersDelay( MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS );
  382. }
  383. eStatus = peMBFrameSendCur( ucMBAddress, ucMBFrame, usLength );
  384. }
  385. break;
  386. case EV_FRAME_SENT:
  387. //printf("recv event: EV_FRAME_SENT\r\n");
  388. break;
  389. }
  390. }
  391. return MB_ENOERR;
  392. }
  393. //
  394. eMBErrorCode
  395. eMBCheckSlaveAddr(UCHAR ucSlaveAddress)
  396. {
  397. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  398. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  399. {
  400. return MB_EINVAL;
  401. }
  402. else
  403. {
  404. return MB_ENOERR;
  405. }
  406. }
  407. //
  408. eMBErrorCode
  409. eMBSetSlaveAddr(UCHAR ucSlaveAddress)
  410. {
  411. if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) ||
  412. ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) )
  413. {
  414. return MB_EINVAL;
  415. }
  416. else
  417. {
  418. ucMBAddress = ucSlaveAddress;
  419. }
  420. return MB_ENOERR;
  421. }