mb.c 14 KB

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