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.h,v 1.17 2006/12/07 22:10:34 wolti Exp $
29  */
30 
31 #ifndef _MB_H
32 #define _MB_H
33 
34 #include "port.h"
35 
36 #ifdef __cplusplus
37 PR_BEGIN_EXTERN_C
38 #endif
39 
40 #include "mbport.h"
41 #include "mbproto.h"
42 
43 /*! \defgroup modbus Modbus
44  * \code #include "mb.h" \endcode
45  *
46  * This module defines the interface for the application. It contains
47  * the basic functions and types required to use the Modbus protocol stack.
48  * A typical application will want to call eMBInit() first. If the device
49  * is ready to answer network requests it must then call eMBEnable() to activate
50  * the protocol stack. In the main loop the function eMBPoll() must be called
51  * periodically. The time interval between pooling depends on the configured
52  * Modbus timeout. If an RTOS is available a separate task should be created
53  * and the task should always call the function eMBPoll().
54  *
55  * \code
56  * // Initialize protocol stack in RTU mode for a slave with address 10 = 0x0A
57  * eMBInit( MB_RTU, 0x0A, 38400, MB_PAR_EVEN );
58  * // Enable the Modbus Protocol Stack.
59  * eMBEnable(  );
60  * for( ;; )
61  * {
62  *     // Call the main polling loop of the Modbus protocol stack.
63  *     eMBPoll(  );
64  *     ...
65  * }
66  * \endcode
67  */
68 
69 /* ----------------------- Defines ------------------------------------------*/
70 
71 /*! \ingroup modbus
72  * \brief Use the default Modbus TCP port (502)
73  */
74 #define MB_TCP_PORT_USE_DEFAULT 0
75 
76 #define MB_FUNC_CODE_MAX 127
77 
78 /* ----------------------- Type definitions ---------------------------------*/
79 /*! \ingroup modbus
80  * \brief Modbus serial transmission modes (RTU/ASCII).
81  *
82  * Modbus serial supports two transmission modes. Either ASCII or RTU. RTU
83  * is faster but has more hardware requirements and requires a network with
84  * a low jitter. ASCII is slower and more reliable on slower links (E.g. modems)
85  */
86 typedef enum
87 {
88     MB_RTU,                     /*!< RTU transmission mode. */
89     MB_ASCII,                   /*!< ASCII transmission mode. */
90     MB_TCP                      /*!< TCP mode. */
91 } eMBMode;
92 
93 /*! \ingroup modbus
94  * \brief If register should be written or read.
95  *
96  * This value is passed to the callback functions which support either
97  * reading or writing register values. Writing means that the application
98  * registers should be updated and reading means that the modbus protocol
99  * stack needs to know the current register values.
100  *
101  * \see eMBRegHoldingCB( ), eMBRegCoilsCB( ), eMBRegDiscreteCB( ) and
102  *   eMBRegInputCB( ).
103  */
104 typedef enum
105 {
106     MB_REG_READ,                /*!< Read register values and pass to protocol stack. */
107     MB_REG_WRITE                /*!< Update register values. */
108 } eMBRegisterMode;
109 
110 /*! \ingroup modbus
111  * \brief Errorcodes used by all function in the protocol stack.
112  */
113 typedef enum
114 {
115     MB_ENOERR,                  /*!< no error. */
116     MB_ENOREG,                  /*!< illegal register address. */
117     MB_EINVAL,                  /*!< illegal argument. */
118     MB_EPORTERR,                /*!< porting layer error. */
119     MB_ENORES,                  /*!< insufficient resources. */
120     MB_EIO,                     /*!< I/O error. */
121     MB_EILLSTATE,               /*!< protocol stack in illegal state. */
122     MB_ETIMEDOUT                /*!< timeout error occurred. */
123 } eMBErrorCode;
124 
125 /* ----------------------- Function prototypes ------------------------------*/
126 /*! \ingroup modbus
127  * \brief Initialize the Modbus protocol stack.
128  *
129  * This functions initializes the ASCII or RTU module and calls the
130  * init functions of the porting layer to prepare the hardware. Please
131  * note that the receiver is still disabled and no Modbus frames are
132  * processed until eMBEnable( ) has been called.
133  *
134  * \param eMode If ASCII or RTU mode should be used.
135  * \param ucSlaveAddress The slave address. Only frames sent to this
136  *   address or to the broadcast address are processed.
137  * \param ucPort The port to use. E.g. 1 for COM1 on windows. This value
138  *   is platform dependent and some ports simply choose to ignore it.
139  * \param ulBaudRate The baudrate. E.g. 19200. Supported baudrates depend
140  *   on the porting layer.
141  * \param eParity Parity used for serial transmission.
142  *
143  * \return If no error occurs the function returns eMBErrorCode::MB_ENOERR.
144  *   The protocol is then in the disabled state and ready for activation
145  *   by calling eMBEnable( ). Otherwise one of the following error codes
146  *   is returned:
147  *    - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid
148  *        slave addresses are in the range 1 - 247.
149  *    - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error.
150  */
151 eMBErrorCode    eMBInit( eMBMode eMode, UCHAR ucSlaveAddress,
152                          UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity );
153 
154 /*! \ingroup modbus
155  * \brief Initialize the Modbus protocol stack for Modbus TCP.
156  *
157  * This function initializes the Modbus TCP Module. Please note that
158  * frame processing is still disabled until eMBEnable( ) is called.
159  *
160  * \param usTCPPort The TCP port to listen on.
161  * \return If the protocol stack has been initialized correctly the function
162  *   returns eMBErrorCode::MB_ENOERR. Otherwise one of the following error
163  *   codes is returned:
164  *    - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid
165  *        slave addresses are in the range 1 - 247.
166  *    - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error.
167  */
168 eMBErrorCode    eMBTCPInit( USHORT usTCPPort );
169 
170 /*! \ingroup modbus
171  * \brief Release resources used by the protocol stack.
172  *
173  * This function disables the Modbus protocol stack and release all
174  * hardware resources. It must only be called when the protocol stack
175  * is disabled.
176  *
177  * \note Note all ports implement this function. A port which wants to
178  *   get an callback must define the macro MB_PORT_HAS_CLOSE to 1.
179  *
180  * \return If the resources where released it return eMBErrorCode::MB_ENOERR.
181  *   If the protocol stack is not in the disabled state it returns
182  *   eMBErrorCode::MB_EILLSTATE.
183  */
184 eMBErrorCode    eMBClose( void );
185 
186 /*! \ingroup modbus
187  * \brief Enable the Modbus protocol stack.
188  *
189  * This function enables processing of Modbus frames. Enabling the protocol
190  * stack is only possible if it is in the disabled state.
191  *
192  * \return If the protocol stack is now in the state enabled it returns
193  *   eMBErrorCode::MB_ENOERR. If it was not in the disabled state it
194  *   return eMBErrorCode::MB_EILLSTATE.
195  */
196 eMBErrorCode    eMBEnable( void );
197 
198 /*! \ingroup modbus
199  * \brief Disable the Modbus protocol stack.
200  *
201  * This function disables processing of Modbus frames.
202  *
203  * \return If the protocol stack has been disabled it returns
204  *  eMBErrorCode::MB_ENOERR. If it was not in the enabled state it returns
205  *  eMBErrorCode::MB_EILLSTATE.
206  */
207 eMBErrorCode    eMBDisable( void );
208 
209 /*! \ingroup modbus
210  * \brief The main pooling loop of the Modbus protocol stack.
211  *
212  * This function must be called periodically. The timer interval required
213  * is given by the application dependent Modbus slave timeout. Internally the
214  * function calls xMBPortEventGet() and waits for an event from the receiver or
215  * transmitter state machines.
216  *
217  * \return If the protocol stack is not in the enabled state the function
218  *   returns eMBErrorCode::MB_EILLSTATE. Otherwise it returns
219  *   eMBErrorCode::MB_ENOERR.
220  */
221 eMBErrorCode    eMBPoll( void );
222 
223 /*! \ingroup modbus
224  * \brief Configure the slave id of the device.
225  *
226  * This function should be called when the Modbus function <em>Report Slave ID</em>
227  * is enabled ( By defining MB_FUNC_OTHER_REP_SLAVEID_ENABLED in mbconfig.h ).
228  *
229  * \param ucSlaveID Values is returned in the <em>Slave ID</em> byte of the
230  *   <em>Report Slave ID</em> response.
231  * \param xIsRunning If TRUE the <em>Run Indicator Status</em> byte is set to 0xFF.
232  *   otherwise the <em>Run Indicator Status</em> is 0x00.
233  * \param pucAdditional Values which should be returned in the <em>Additional</em>
234  *   bytes of the <em> Report Slave ID</em> response.
235  * \param usAdditionalLen Length of the buffer <code>pucAdditonal</code>.
236  *
237  * \return If the static buffer defined by MB_FUNC_OTHER_REP_SLAVEID_BUF in
238  *   mbconfig.h is to small it returns eMBErrorCode::MB_ENORES. Otherwise
239  *   it returns eMBErrorCode::MB_ENOERR.
240  */
241 eMBErrorCode    eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning,
242                                UCHAR const *pucAdditional,
243                                USHORT usAdditionalLen );
244 
245 /*! \ingroup modbus
246  * \brief Registers a callback handler for a given function code.
247  *
248  * This function registers a new callback handler for a given function code.
249  * The callback handler supplied is responsible for interpreting the Modbus PDU and
250  * the creation of an appropriate response. In case of an error it should return
251  * one of the possible Modbus exceptions which results in a Modbus exception frame
252  * sent by the protocol stack.
253  *
254  * \param ucFunctionCode The Modbus function code for which this handler should
255  *   be registers. Valid function codes are in the range 1 to 127.
256  * \param pxHandler The function handler which should be called in case
257  *   such a frame is received. If \c NULL a previously registered function handler
258  *   for this function code is removed.
259  *
260  * \return eMBErrorCode::MB_ENOERR if the handler has been installed. If no
261  *   more resources are available it returns eMBErrorCode::MB_ENORES. In this
262  *   case the values in mbconfig.h should be adjusted. If the argument was not
263  *   valid it returns eMBErrorCode::MB_EINVAL.
264  */
265 eMBErrorCode    eMBRegisterCB( UCHAR ucFunctionCode,
266                                pxMBFunctionHandler pxHandler );
267 
268 /* ----------------------- Callback -----------------------------------------*/
269 
270 /*! \defgroup modbus_registers Modbus Registers
271  * \code #include "mb.h" \endcode
272  * The protocol stack does not internally allocate any memory for the
273  * registers. This makes the protocol stack very small and also usable on
274  * low end targets. In addition the values don't have to be in the memory
275  * and could for example be stored in a flash.<br>
276  * Whenever the protocol stack requires a value it calls one of the callback
277  * function with the register address and the number of registers to read
278  * as an argument. The application should then read the actual register values
279  * (for example the ADC voltage) and should store the result in the supplied
280  * buffer.<br>
281  * If the protocol stack wants to update a register value because a write
282  * register function was received a buffer with the new register values is
283  * passed to the callback function. The function should then use these values
284  * to update the application register values.
285  */
286 
287 /*! \ingroup modbus_registers
288  * \brief Callback function used if the value of a <em>Input Register</em>
289  *   is required by the protocol stack. The starting register address is given
290  *   by \c usAddress and the last register is given by <tt>usAddress +
291  *   usNRegs - 1</tt>.
292  *
293  * \param pucRegBuffer A buffer where the callback function should write
294  *   the current value of the modbus registers to.
295  * \param usAddress The starting address of the register. Input registers
296  *   are in the range 1 - 65535.
297  * \param usNRegs Number of registers the callback function must supply.
298  *
299  * \return The function must return one of the following error codes:
300  *   - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal
301  *       Modbus response is sent.
302  *   - eMBErrorCode::MB_ENOREG If the application can not supply values
303  *       for registers within this range. In this case a
304  *       <b>ILLEGAL DATA ADDRESS</b> exception frame is sent as a response.
305  *   - eMBErrorCode::MB_ETIMEDOUT If the requested register block is
306  *       currently not available and the application dependent response
307  *       timeout would be violated. In this case a <b>SLAVE DEVICE BUSY</b>
308  *       exception is sent as a response.
309  *   - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case
310  *       a <b>SLAVE DEVICE FAILURE</b> exception is sent as a response.
311  */
312 eMBErrorCode    eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress,
313                                USHORT usNRegs );
314 
315 /*! \ingroup modbus_registers
316  * \brief Callback function used if a <em>Holding Register</em> value is
317  *   read or written by the protocol stack. The starting register address
318  *   is given by \c usAddress and the last register is given by
319  *   <tt>usAddress + usNRegs - 1</tt>.
320  *
321  * \param pucRegBuffer If the application registers values should be updated the
322  *   buffer points to the new registers values. If the protocol stack needs
323  *   to now the current values the callback function should write them into
324  *   this buffer.
325  * \param usAddress The starting address of the register.
326  * \param usNRegs Number of registers to read or write.
327  * \param eMode If eMBRegisterMode::MB_REG_WRITE the application register
328  *   values should be updated from the values in the buffer. For example
329  *   this would be the case when the Modbus master has issued an
330  *   <b>WRITE SINGLE REGISTER</b> command.
331  *   If the value eMBRegisterMode::MB_REG_READ the application should copy
332  *   the current values into the buffer \c pucRegBuffer.
333  *
334  * \return The function must return one of the following error codes:
335  *   - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal
336  *       Modbus response is sent.
337  *   - eMBErrorCode::MB_ENOREG If the application can not supply values
338  *       for registers within this range. In this case a
339  *       <b>ILLEGAL DATA ADDRESS</b> exception frame is sent as a response.
340  *   - eMBErrorCode::MB_ETIMEDOUT If the requested register block is
341  *       currently not available and the application dependent response
342  *       timeout would be violated. In this case a <b>SLAVE DEVICE BUSY</b>
343  *       exception is sent as a response.
344  *   - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case
345  *       a <b>SLAVE DEVICE FAILURE</b> exception is sent as a response.
346  */
347 eMBErrorCode    eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress,
348                                  USHORT usNRegs, eMBRegisterMode eMode );
349 
350 /*! \ingroup modbus_registers
351  * \brief Callback function used if a <em>Coil Register</em> value is
352  *   read or written by the protocol stack. If you are going to use
353  *   this function you might use the functions xMBUtilSetBits(  ) and
354  *   xMBUtilGetBits(  ) for working with bitfields.
355  *
356  * \param pucRegBuffer The bits are packed in bytes where the first coil
357  *   starting at address \c usAddress is stored in the LSB of the
358  *   first byte in the buffer <code>pucRegBuffer</code>.
359  *   If the buffer should be written by the callback function unused
360  *   coil values (I.e. if not a multiple of eight coils is used) should be set
361  *   to zero.
362  * \param usAddress The first coil number.
363  * \param usNCoils Number of coil values requested.
364  * \param eMode If eMBRegisterMode::MB_REG_WRITE the application values should
365  *   be updated from the values supplied in the buffer \c pucRegBuffer.
366  *   If eMBRegisterMode::MB_REG_READ the application should store the current
367  *   values in the buffer \c pucRegBuffer.
368  *
369  * \return The function must return one of the following error codes:
370  *   - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal
371  *       Modbus response is sent.
372  *   - eMBErrorCode::MB_ENOREG If the application does not map an coils
373  *       within the requested address range. In this case a
374  *       <b>ILLEGAL DATA ADDRESS</b> is sent as a response.
375  *   - eMBErrorCode::MB_ETIMEDOUT If the requested register block is
376  *       currently not available and the application dependent response
377  *       timeout would be violated. In this case a <b>SLAVE DEVICE BUSY</b>
378  *       exception is sent as a response.
379  *   - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case
380  *       a <b>SLAVE DEVICE FAILURE</b> exception is sent as a response.
381  */
382 eMBErrorCode    eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress,
383                                USHORT usNCoils, eMBRegisterMode eMode );
384 
385 /*! \ingroup modbus_registers
386  * \brief Callback function used if a <em>Input Discrete Register</em> value is
387  *   read by the protocol stack.
388  *
389  * If you are going to use his function you might use the functions
390  * xMBUtilSetBits(  ) and xMBUtilGetBits(  ) for working with bitfields.
391  *
392  * \param pucRegBuffer The buffer should be updated with the current
393  *   coil values. The first discrete input starting at \c usAddress must be
394  *   stored at the LSB of the first byte in the buffer. If the requested number
395  *   is not a multiple of eight the remaining bits should be set to zero.
396  * \param usAddress The starting address of the first discrete input.
397  * \param usNDiscrete Number of discrete input values.
398  * \return The function must return one of the following error codes:
399  *   - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal
400  *       Modbus response is sent.
401  *   - eMBErrorCode::MB_ENOREG If no such discrete inputs exists.
402  *       In this case a <b>ILLEGAL DATA ADDRESS</b> exception frame is sent
403  *       as a response.
404  *   - eMBErrorCode::MB_ETIMEDOUT If the requested register block is
405  *       currently not available and the application dependent response
406  *       timeout would be violated. In this case a <b>SLAVE DEVICE BUSY</b>
407  *       exception is sent as a response.
408  *   - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case
409  *       a <b>SLAVE DEVICE FAILURE</b> exception is sent as a response.
410  */
411 eMBErrorCode    eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress,
412                                   USHORT usNDiscrete );
413 
414 #ifdef __cplusplus
415 PR_END_EXTERN_C
416 #endif
417 #endif
418