mb_master.c
changeset 0 ae252e0fd9b8
child 1 59783e8ee3d2
equal deleted inserted replaced
-1:000000000000 0:ae252e0fd9b8
       
     1 /*
       
     2  * Copyright (c) 2001-2003,2016 Mario de Sousa (msousa@fe.up.pt)
       
     3  *
       
     4  * This file is part of the Modbus library for Beremiz and matiec.
       
     5  *
       
     6  * This Modbus library is free software: you can redistribute it and/or modify
       
     7  * it under the terms of the GNU Lesser General Public License as published by
       
     8  * the Free Software Foundation, either version 3 of the License, or
       
     9  * (at your option) any later version.
       
    10  *
       
    11  * This program is distributed in the hope that it will be useful, but
       
    12  * WITHOUT ANY WARRANTY; without even the implied warranty of
       
    13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
       
    14  * General Public License for more details.
       
    15  *
       
    16  * You should have received a copy of the GNU Lesser General Public License
       
    17  * along with this Modbus library.  If not, see <http://www.gnu.org/licenses/>.
       
    18  *
       
    19  * This code is made available on the understanding that it will not be
       
    20  * used in safety-critical situations without a full and competent review.
       
    21  */
       
    22 
       
    23 
       
    24 /* mb_master.c */
       
    25 
       
    26 
       
    27 #include <fcntl.h>	/* File control definitions */
       
    28 #include <stdio.h>	/* Standard input/output */
       
    29 #include <string.h>
       
    30 #include <stdlib.h>
       
    31 #include <termio.h>	/* POSIX terminal control definitions */
       
    32 #include <sys/time.h>	/* Time structures for select() */
       
    33 #include <unistd.h>	/* POSIX Symbolic Constants */
       
    34 #include <errno.h>	/* Error definitions */
       
    35 
       
    36 #include <pthread.h>    /* pthread_mutex_[un]lock() */
       
    37 
       
    38 #include <netinet/in.h> /* required for htons() and ntohs() */
       
    39 #include "mb_layer1.h"
       
    40 #include "mb_master.h"
       
    41 #include "mb_master_private.h"
       
    42 
       
    43 /* #define DEBUG */		/* uncomment to see the data sent and received */
       
    44 
       
    45 #define modbus_write             fptr_[layer1_fin].modbus_write           
       
    46 #define modbus_read              fptr_[layer1_fin].modbus_read            
       
    47 #define modbus_init              fptr_[layer1_fin].modbus_init            
       
    48 #define modbus_done              fptr_[layer1_fin].modbus_done            
       
    49 #define modbus_connect           fptr_[layer1_fin].modbus_connect         
       
    50 #define modbus_listen            fptr_[layer1_fin].modbus_listen          
       
    51 #define modbus_close             fptr_[layer1_fin].modbus_close           
       
    52 #define modbus_silence_init      fptr_[layer1_fin].modbus_silence_init    
       
    53 #define modbus_get_min_timeout   fptr_[layer1_fin].modbus_get_min_timeout 
       
    54 
       
    55 /* the lower two bits of ttyfd are used to store the index to layer1 function pointers */
       
    56 /* layer1_fin index to fptr_[] is in lowest 2 bits of fd */
       
    57 #define get_ttyfd()     int layer1_fin = fd & 3; int ttyfd = fd / 4;
       
    58 
       
    59 
       
    60 
       
    61 /******************************************/
       
    62 /******************************************/
       
    63 /**                                      **/
       
    64 /**         Global Variables...          **/
       
    65 /**                                      **/
       
    66 /******************************************/
       
    67 /******************************************/
       
    68    /* The layer 1 (RTU, ASCII, TCP) implementation will be adding some headers and CRC (at the end)
       
    69     *  of the packet we build here (actually currently it is only at the end). Since we want to 
       
    70     *  re-use the same buffer so as not to continuosly copy the same info from buffer to buffer,
       
    71     *  we need tp allocate more bytes than the ones we need for this layer. Therefore, the
       
    72     *  extra_bytes parameter.
       
    73     *
       
    74     *  Note that we add one more extra byte. This is because some packets will not be 
       
    75     *  starting off at byte 0, but rather at byte 1 of the buffer. This is in order to guarantee
       
    76     *  that the data that is sent on the buffer is aligned on even bytes (the 16 bit words!).
       
    77     *  This will allow us to reference this memory as an u16 *, without producing 'bus error'
       
    78     *  messages in some embedded devices that do not allow acessing u16 on odd numbered addresses.
       
    79     */ 
       
    80 static int buff_extra_bytes_;
       
    81 #define QUERY_BUFFER_SIZE       (MAX_L2_FRAME_LENGTH + buff_extra_bytes_ + 1)
       
    82 
       
    83 
       
    84 /******************************************/
       
    85 /******************************************/
       
    86 /**                                      **/
       
    87 /**       Local Utility functions...     **/
       
    88 /**                                      **/
       
    89 /******************************************/
       
    90 /******************************************/
       
    91 
       
    92 
       
    93 /*
       
    94  * Function to determine next transaction id.
       
    95  *
       
    96  * We use a library wide transaction id, which means that we
       
    97  * use a new transaction id no matter what slave to which we will
       
    98  * be sending the request...
       
    99  */
       
   100 static inline u16 next_transaction_id(void) {
       
   101   static u16 next_id = 0;
       
   102   return next_id++;
       
   103 }
       
   104 
       
   105 
       
   106 /*
       
   107  * Functions to convert u16 variables
       
   108  * between network and host byte order
       
   109  *
       
   110  * NOTE: Modbus uses MSByte first, just like
       
   111  *       tcp/ip, so we use the htons() and
       
   112  *       ntoh() functions to guarantee
       
   113  *       code portability.
       
   114  */
       
   115 static inline u16 mb_hton(u16 h_value) {return htons(h_value);}
       
   116 static inline u16 mb_ntoh(u16 m_value) {return ntohs(m_value);}
       
   117 static inline u8  msb    (u16   value) {return (value >> 8) & 0xFF;}
       
   118 static inline u8  lsb    (u16   value) {return  value & 0xFF;}
       
   119 
       
   120 
       
   121 
       
   122 
       
   123 /*************************************************/
       
   124 /*************************************************/
       
   125 /**                                             **/
       
   126 /**   Common functions for Modbus Protocol.     **/
       
   127 /**                                             **/
       
   128 /*************************************************/
       
   129 /*************************************************/
       
   130 
       
   131 /* build the common elements of a query frame */
       
   132 static inline int build_packet(u8  slave,
       
   133                                u8  function,
       
   134                                u16 start_addr,
       
   135                                u16 count,
       
   136                                u8 *packet) {
       
   137   union {
       
   138       u16 u16;
       
   139       u8  u8[2];
       
   140   } tmp;
       
   141   
       
   142   packet[0] = slave,
       
   143   packet[1] = function;
       
   144     /* NOTE:
       
   145      *  Modbus uses high level addressing starting off from 1, but
       
   146      *  this is sent as 0 on the wire!
       
   147      *  We could expect the user to specify high level addressing 
       
   148      *   starting at 1, and do the conversion to start off at 0 here.
       
   149      *   However, to do this we would then need to use an u32 data type
       
   150      *   to correctly hold the address supplied by the user (which could
       
   151      *   correctly be 65536, which does not fit in an u16), which would
       
   152      *   in turn require us to check whether the address supplied by the user
       
   153      *   is correct (i.e. <= 65536). 
       
   154      *  I decided to go with the other option of using an u16, and 
       
   155      *   requiring the user to use addressing starting off at 0! 
       
   156      */
       
   157   /* NOTE: we do not use up casting - i.e. the following
       
   158    *       *((u16 *)(packet+2)) = mb_hton(start_addr);
       
   159    *       because packet+2 is NOT aligned with an even address, and would
       
   160    *       therefore result in 'bus error' when using compilers that do not 
       
   161    *       automatically do the required decomposing of this supposedly 
       
   162    *       single bus access into two distinct bus accesses.
       
   163    *       (Note that some compilers do do this decomposing automatically
       
   164    *       in which case the following is not necessary).
       
   165    *       At the moment, I (Mario de Sousa) know of at least one cross-compiler
       
   166    *       that does not do the decomposing automatically, i.e. the 
       
   167    *       AVR32 cross-compiler.
       
   168    */
       
   169   tmp.u16 = mb_hton(start_addr);
       
   170   packet[2] = tmp.u8[0];
       
   171   packet[3] = tmp.u8[1];
       
   172   tmp.u16 = mb_hton(count);
       
   173   packet[4] = tmp.u8[0];
       
   174   packet[5] = tmp.u8[1];
       
   175   
       
   176   return 6;
       
   177 }
       
   178 
       
   179 
       
   180 
       
   181 /* Execute a Query/Response transaction between client and server */ 
       
   182 /* returns: <0    -> ERROR: error codes
       
   183  *          >2    -> SUCCESS: frame length
       
   184  *           0..2 -> will never be returned!
       
   185  */
       
   186 static int mb_transaction(u8  *packet,
       
   187                           int query_length,
       
   188                           u8  **data,
       
   189                           int fd,
       
   190                           int send_retries,
       
   191                           u8  *error_code,
       
   192                           const struct timespec *response_timeout) {
       
   193   int error = TIMEOUT;
       
   194   int response_length = INTERNAL_ERROR;
       
   195   u16 send_transaction_id, recv_transaction_id;
       
   196   get_ttyfd(); /* declare the ttyfd variable, ... */
       
   197   
       
   198     /* We must also initialize the recv_transaction_id with the same value,
       
   199      * since some layer 1 protocols do not support transaction id's, so
       
   200      * simply return the recv_transaction_id variable without any changes...
       
   201      */
       
   202   /* NOTE: we re-use the same transaction id for all send re-tries., since, in truth, 
       
   203    * it is still the same transaction. This will also simplify re-synchronising with
       
   204    * some slaves that keep a buffer of outstanding requests, and will reply to all of
       
   205    * them, in FIFO order. In this case, once an error occurs we will be swamping the
       
   206    * slave with requests. By using the same transaction id, we may correctly consider
       
   207    * the reply to the first request sent as the reply to the third request! This means
       
   208    * we stop re-trying the sending of further requests, and no longer swamp the slave...
       
   209    */
       
   210   send_transaction_id = recv_transaction_id = next_transaction_id();
       
   211 
       
   212   for (send_retries++; send_retries > 0; send_retries--) {
       
   213     error = TIMEOUT;
       
   214 
       
   215     if (modbus_write(ttyfd, packet, query_length, send_transaction_id, response_timeout) < 0)
       
   216       {error = PORT_FAILURE; continue;}
       
   217 
       
   218       /* if we receive a correct response but with a wrong transaction id or wrong modbus function, we try to 
       
   219        * receive another frame instead of returning an error or re-sending the request! This first frame could 
       
   220        * have been a response to a previous request of ours that timed out waiting for a response, and the 
       
   221        * response we are waiting for could be coming 'any minute now'.
       
   222        */
       
   223     do {
       
   224       response_length = modbus_read(&ttyfd, data, &recv_transaction_id,
       
   225                                     packet, query_length, response_timeout);
       
   226 
       
   227       /* TIMEOUT condition */
       
   228       /* However, if we had previously received an invalid frame, or some other error,
       
   229        * we return that error instead!
       
   230        * Note that the 'error' variable was initialised with the TIMEOUT error
       
   231        * condition, so if no previous error ocurred, we will be returning the
       
   232        * TIMEOUT error condition here!
       
   233        */
       
   234       if(response_length == -2)  return error;
       
   235       /* NOTE we want to break out of this while loop without even running the while()
       
   236        * condition, as that condition is only valid if response_length > 3 !!
       
   237        */
       
   238       if(response_length  <  0)  {error = PORT_FAILURE; break;}
       
   239       /* This should never occur! Modbus_read() should only return valid frames! */
       
   240       if(response_length  <  3)  return INTERNAL_ERROR;
       
   241 
       
   242     } while (/* we have the wrong transaction id */
       
   243              (send_transaction_id != recv_transaction_id)
       
   244              /* not a response frame to _our_ query */
       
   245             ||
       
   246              (((*data)[1] & ~0x80) != packet[1])
       
   247             /* NOTE: no need to check whether (*data)[0] = slave!              */
       
   248             /*       This has already been done by the modbus_read() function! */
       
   249             );
       
   250 
       
   251     if(response_length < 0)  {error = PORT_FAILURE; continue;}
       
   252 
       
   253     /* Now check whether we received a Modbus Exception frame */
       
   254     if (((*data)[1] & 0x80) != 0) {       /* we have an exception frame! */
       
   255       /* NOTE: we have already checked above that data[2] exists! */
       
   256       if (error_code != NULL)  *error_code = (*data)[2];
       
   257       return MODBUS_ERROR;
       
   258     }
       
   259     /* success! Let's get out of the send retry loop... */
       
   260     return response_length;
       
   261   }
       
   262   /* reached the end of the retries... */
       
   263   return error;
       
   264 }
       
   265 
       
   266 
       
   267 /**************************************/
       
   268 /**************************************/
       
   269 /**                                  **/
       
   270 /**   Modbus Protocol Functions.     **/
       
   271 /**                                  **/
       
   272 /**************************************/
       
   273 /**************************************/
       
   274 
       
   275 
       
   276 
       
   277 /* Execute a transaction for functions that READ BITS.
       
   278  * Bits are stored on an int array, one bit per int.
       
   279  * Called by:  read_input_bits()
       
   280  *             read_output_bits()
       
   281  */
       
   282 static int read_bits(u8  function,
       
   283                      u8  slave,
       
   284                      u16 start_addr,
       
   285                      u16 count,
       
   286                      u16 *dest,
       
   287                      int dest_size,
       
   288                      int ttyfd,
       
   289                      int send_retries,
       
   290                      u8  *error_code,
       
   291                      const struct timespec *response_timeout,
       
   292                      pthread_mutex_t *data_access_mutex) {
       
   293   
       
   294   u8 packet[QUERY_BUFFER_SIZE];
       
   295   u8 *data;
       
   296   int response_length, query_length;
       
   297   int temp, i, bit, dest_pos = 0;
       
   298   int coils_processed = 0;
       
   299   
       
   300   query_length = build_packet(slave, function, start_addr, count, packet);
       
   301   if (query_length < 0)  return INTERNAL_ERROR;
       
   302   
       
   303   response_length = mb_transaction(packet, query_length, &data, ttyfd,
       
   304                                    send_retries, error_code, response_timeout);
       
   305   
       
   306   if (response_length  < 0)                  return response_length;
       
   307   /* NOTE: Integer division. (count+7)/8 is equivalent to ceil(count/8) */
       
   308   if (response_length != 3 + (count+7)/8)    return INVALID_FRAME;
       
   309   if (data[2]         !=     (count+7)/8)    return INVALID_FRAME;
       
   310   
       
   311   if (NULL != data_access_mutex) pthread_mutex_lock(data_access_mutex);
       
   312   for( i = 0; (i < data[2]) && (i < dest_size); i++ ) {
       
   313     temp = data[3 + i];
       
   314     for( bit = 0x01; (bit & 0xff) && (coils_processed < count); ) {
       
   315       dest[dest_pos] = (temp & bit)?1:0;
       
   316       coils_processed++;
       
   317       dest_pos++;
       
   318       bit = bit << 1;
       
   319     }
       
   320   }
       
   321   if (NULL != data_access_mutex) pthread_mutex_unlock(data_access_mutex);
       
   322   
       
   323   return response_length;
       
   324 }
       
   325 
       
   326 
       
   327 
       
   328 /* Execute a transaction for functions that READ BITS.
       
   329  * Bits are stored on an u32 array, 32 bits per u32.
       
   330  * Unused bits in last u32 are set to 0.
       
   331  * Called by:  read_input_bits_u32()
       
   332  *             read_output_bits_u32()
       
   333  */
       
   334 static int read_bits_u32(u8  function,
       
   335                          u8  slave,
       
   336                          u16 start_addr,
       
   337                          u16 count, /* number of bits !! */
       
   338                          u32 *dest,
       
   339                          int ttyfd,
       
   340                          int send_retries,
       
   341                          u8  *error_code,
       
   342                          const struct timespec *response_timeout) {
       
   343   u8 packet[QUERY_BUFFER_SIZE];
       
   344   u8 *data;
       
   345   int response_length, query_length;                         
       
   346   int byte_count, i, dest_pos = 0;
       
   347   
       
   348   query_length = build_packet(slave, function, start_addr, count, packet);
       
   349   if (query_length < 0)  return INTERNAL_ERROR;
       
   350   
       
   351   response_length = mb_transaction(packet, query_length, &data, ttyfd,
       
   352                                    send_retries, error_code, response_timeout);
       
   353   
       
   354   if (response_length < 0)                   return response_length;  
       
   355   /* NOTE: Integer division. (count+7)/8 is equivalent to ceil(count/8) */
       
   356   if (response_length != 3 + (count+7)/8)    return INVALID_FRAME;
       
   357   if (data[2]         !=     (count+7)/8)    return INVALID_FRAME;
       
   358   
       
   359   byte_count = data[2];
       
   360   data += 3;
       
   361   /* handle groups of 4 bytes... */
       
   362   for(i = 0, dest_pos = 0; i + 3 < byte_count; i += 4, dest_pos++)
       
   363     dest[dest_pos] = data[i] + data[i+1]*0x100 + data[i+2]*0x10000 + data[i+3]*0x1000000;
       
   364   /* handle any remaining bytes... begining with the last! */
       
   365   if (i < byte_count) dest[dest_pos] = 0;
       
   366   for(byte_count--; i <= byte_count; byte_count--)
       
   367     dest[dest_pos] = dest[dest_pos]*0x100 + data[byte_count];
       
   368   
       
   369   return response_length;
       
   370 }
       
   371 
       
   372 
       
   373 
       
   374 /* FUNCTION 0x01   - Read Coils
       
   375  * Bits are stored on an int array, one bit per int.
       
   376  */
       
   377 inline int read_output_bits(u8  slave,
       
   378                             u16 start_addr,
       
   379                             u16 count,
       
   380                             u16 *dest,
       
   381                             int dest_size,
       
   382                             int ttyfd,
       
   383                             int send_retries,
       
   384                             u8  *error_code,
       
   385                             const struct timespec *response_timeout,
       
   386                             pthread_mutex_t *data_access_mutex) {
       
   387   if( count > MAX_READ_BITS ) {
       
   388     count = MAX_READ_BITS;
       
   389     #ifdef DEBUG
       
   390     fprintf( stderr, "Too many coils requested.\n" );
       
   391     #endif
       
   392   }
       
   393 
       
   394   return read_bits(0x01 /* function */,
       
   395                    slave, start_addr, count, dest, dest_size, ttyfd, 
       
   396                    send_retries, error_code, response_timeout, data_access_mutex);
       
   397 }
       
   398 
       
   399 
       
   400 
       
   401 /* FUNCTION 0x01   - Read Coils
       
   402  * Bits are stored on an u32 array, 32 bits per u32.
       
   403  * Unused bits in last u32 are set to 0.
       
   404  */
       
   405 inline int read_output_bits_u32(u8  slave,
       
   406                                 u16 start_addr,
       
   407                                 u16 count,
       
   408                                 u32 *dest,
       
   409                                 int ttyfd,
       
   410                                 int send_retries,
       
   411                                 u8  *error_code,
       
   412                                 const struct timespec *response_timeout) {
       
   413   if( count > MAX_READ_BITS ) {
       
   414     count = MAX_READ_BITS;
       
   415     #ifdef DEBUG
       
   416     fprintf( stderr, "Too many coils requested.\n" );
       
   417     #endif
       
   418   }
       
   419 
       
   420   return read_bits_u32(0x01 /* function */,
       
   421                        slave, start_addr, count, dest, ttyfd,
       
   422                        send_retries, error_code, response_timeout);
       
   423 }
       
   424 
       
   425 
       
   426 /* FUNCTION 0x02   - Read Discrete Inputs
       
   427  * Bits are stored on an int array, one bit per int.
       
   428  */
       
   429 inline int read_input_bits(u8  slave,
       
   430                            u16 start_addr,
       
   431                            u16 count,
       
   432                            u16 *dest,
       
   433                            int dest_size,
       
   434                            int ttyfd,
       
   435                            int send_retries,
       
   436                            u8  *error_code,
       
   437                            const struct timespec *response_timeout,
       
   438                            pthread_mutex_t *data_access_mutex) {
       
   439   if( count > MAX_READ_BITS ) {
       
   440     count = MAX_READ_BITS;
       
   441     #ifdef DEBUG
       
   442     fprintf( stderr, "Too many coils requested.\n" );
       
   443     #endif
       
   444   }
       
   445 
       
   446   return read_bits(0x02 /* function */,
       
   447                    slave, start_addr, count, dest, dest_size, ttyfd,
       
   448                    send_retries, error_code, response_timeout, data_access_mutex);
       
   449 }
       
   450 
       
   451 
       
   452 
       
   453 /* FUNCTION 0x02   - Read Discrete Inputs
       
   454  * Bits are stored on an u32 array, 32 bits per u32.
       
   455  * Unused bits in last u32 are set to 0.
       
   456  */
       
   457 inline int read_input_bits_u32(u8  slave,
       
   458                                u16 start_addr,
       
   459                                u16 count,
       
   460                                u32 *dest,
       
   461                                int ttyfd,
       
   462                                int send_retries,
       
   463                                u8  *error_code,
       
   464                                const struct timespec *response_timeout) {
       
   465   if( count > MAX_READ_BITS ) {
       
   466     count = MAX_READ_BITS;
       
   467     #ifdef DEBUG
       
   468     fprintf( stderr, "Too many coils requested.\n" );
       
   469     #endif
       
   470   }
       
   471 
       
   472   return read_bits_u32(0x02 /* function */,
       
   473                        slave, start_addr, count, dest, ttyfd,
       
   474                        send_retries, error_code, response_timeout);
       
   475 }
       
   476 
       
   477 
       
   478 
       
   479 
       
   480 
       
   481 
       
   482 /* Execute a transaction for functions that READ REGISTERS.
       
   483  * Called by:  read_input_words()
       
   484  *             read_output_words()
       
   485  */
       
   486 static int read_registers(u8  function,
       
   487                           u8  slave,
       
   488                           u16 start_addr,
       
   489                           u16 count,
       
   490                           u16 *dest,
       
   491                           int dest_size,
       
   492                           int ttyfd,
       
   493                           int send_retries,
       
   494                           u8  *error_code,
       
   495                           const struct timespec *response_timeout,
       
   496                           pthread_mutex_t *data_access_mutex) {
       
   497   u8 *data;
       
   498   u8 packet[QUERY_BUFFER_SIZE];
       
   499   int response_length;
       
   500   int query_length;
       
   501   int temp,i;
       
   502   
       
   503   query_length = build_packet(slave, function, start_addr, count, packet);
       
   504   if (query_length < 0)    return INTERNAL_ERROR;
       
   505   
       
   506   response_length = mb_transaction(packet, query_length, &data, ttyfd, 
       
   507                                    send_retries, error_code, response_timeout);
       
   508   
       
   509   if (response_length  < 0)              return response_length;  
       
   510   if (response_length != 3 + 2*count)    return INVALID_FRAME;  
       
   511   if (data[2]         !=     2*count)    return INVALID_FRAME;
       
   512   
       
   513   if (NULL != data_access_mutex) pthread_mutex_lock(data_access_mutex);
       
   514   for(i = 0; (i < (data[2]*2)) && (i < dest_size); i++ ) {
       
   515     temp = data[3 + i *2] << 8;    /* copy reg hi byte to temp hi byte*/
       
   516     temp = temp | data[4 + i * 2]; /* copy reg lo byte to temp lo byte*/
       
   517     dest[i] = temp;
       
   518   }
       
   519   if (NULL != data_access_mutex) pthread_mutex_unlock(data_access_mutex);
       
   520   
       
   521   return response_length;
       
   522 }
       
   523 
       
   524 
       
   525 
       
   526 /* Execute a transaction for functions that READ REGISTERS.
       
   527  * return the array with the data to the calling function
       
   528  * Called by:  read_input_words_u16_ref()
       
   529  *             read_output_words_u16_ref()
       
   530  */
       
   531 
       
   532 static int read_registers_u16_ref(u8  function,
       
   533                                   u8  slave,
       
   534                                   u16 start_addr,
       
   535                                   u16 count,
       
   536                                   u16 **dest,
       
   537                                   int ttyfd,
       
   538                                   int send_retries,
       
   539                                   u8  *error_code,
       
   540                                   const struct timespec *response_timeout) {
       
   541   u8 *data;
       
   542   u8 packet[QUERY_BUFFER_SIZE];
       
   543   int response_length;
       
   544   int query_length;
       
   545   int i, byte_count;
       
   546   
       
   547   query_length = build_packet(slave, function, start_addr, count, packet);
       
   548   if (query_length < 0)    return INTERNAL_ERROR;
       
   549   
       
   550   response_length = mb_transaction(packet, query_length, &data, ttyfd,
       
   551                                    send_retries, error_code, response_timeout);
       
   552   
       
   553   if (response_length < 0)               return response_length;  
       
   554   if (response_length != 3 + 2*count)    return INVALID_FRAME;  
       
   555   if (data[2]         !=     2*count)    return INVALID_FRAME;
       
   556   
       
   557   byte_count = data[2];
       
   558   data = data + 3; /* & data[3] */
       
   559   
       
   560   if (ntohs(0x0102) != 0x0102) {
       
   561    /* little endian host... => we need to swap the bytes! */
       
   562     for(i = 0; i < byte_count; i++ ) {
       
   563       /* the following 3 lines result in the two values being exchanged! */ 
       
   564       data[i  ] = data[i] ^ data[i+1];
       
   565       data[i+1] = data[i] ^ data[i+1];
       
   566       data[i  ] = data[i] ^ data[i+1];
       
   567     }
       
   568   }
       
   569   *dest = (u16 *)data;  
       
   570   return byte_count;
       
   571 }
       
   572 
       
   573 
       
   574 
       
   575 
       
   576 /* Execute a transaction for functions that READ REGISTERS.
       
   577  * u16 registers are stored in array of u32, two registers per u32.
       
   578  * Unused bits of last u32 element are set to 0.
       
   579  * Called by:  read_input_words_u32()
       
   580  *             read_output_words_u32()
       
   581  */
       
   582 static int read_registers_u32(u8  function,
       
   583                               u8  slave,
       
   584                               u16 start_addr,
       
   585                               u16 count,
       
   586                               u32 *dest,
       
   587                               int ttyfd,
       
   588                               int send_retries,
       
   589                               u8  *error_code,
       
   590                               const struct timespec *response_timeout) {
       
   591   u8 *data;
       
   592   u8 packet[QUERY_BUFFER_SIZE];
       
   593   int response_length;
       
   594   int query_length;
       
   595   int i, byte_count, dest_pos;
       
   596   
       
   597   query_length = build_packet(slave, function, start_addr, count, packet);
       
   598   if (query_length < 0)    return INTERNAL_ERROR;
       
   599   
       
   600   response_length = mb_transaction(packet, query_length, &data, ttyfd,
       
   601                                    send_retries, error_code, response_timeout);
       
   602   
       
   603   if (response_length  < 0)              return response_length;
       
   604   if (response_length != 3 + 2*count)    return INVALID_FRAME;
       
   605   if (data[2]         !=     2*count)    return INVALID_FRAME;
       
   606   
       
   607   byte_count = data[2];
       
   608   data += 3;
       
   609   
       
   610   if (ntohs(0x0102) == 0x0102) {
       
   611    /* big endian host... */
       
   612     /* handle groups of 4 bytes... */
       
   613     for(i = 0, dest_pos = 0; i + 3 < byte_count; i += 4, dest_pos++) {
       
   614       *(((u8 *)(dest + dest_pos))+ 0) = *(data+i+3);
       
   615       *(((u8 *)(dest + dest_pos))+ 1) = *(data+i+4);
       
   616       *(((u8 *)(dest + dest_pos))+ 2) = *(data+i+0);
       
   617       *(((u8 *)(dest + dest_pos))+ 3) = *(data+i+1);
       
   618     }
       
   619     /* handle any remaining bytes...
       
   620      * since byte_count is supposed to be multiple of 2,
       
   621      * (and has already been verified above 'if (data[2] != 2*count)')
       
   622      * this will be either 2, or none at all!
       
   623      */
       
   624     if (i + 1 < byte_count)
       
   625       *(((u8 *)(dest + dest_pos))+ 0) = 0;
       
   626       *(((u8 *)(dest + dest_pos))+ 1) = 0;
       
   627       *(((u8 *)(dest + dest_pos))+ 2) = *(data+i+0);
       
   628       *(((u8 *)(dest + dest_pos))+ 3) = *(data+i+1);
       
   629   } else {
       
   630    /* little endian host... */
       
   631     /* handle groups of 4 bytes... */
       
   632     for(i = 0, dest_pos = 0; i + 3 < byte_count; i += 4, dest_pos++) {
       
   633       *(((u8 *)(dest + dest_pos))+ 0) = *(data+i+1);
       
   634       *(((u8 *)(dest + dest_pos))+ 1) = *(data+i+0);
       
   635       *(((u8 *)(dest + dest_pos))+ 2) = *(data+i+3);
       
   636       *(((u8 *)(dest + dest_pos))+ 3) = *(data+i+2);
       
   637     }
       
   638     /* handle any remaining bytes...
       
   639      * since byte_count is supposed to be multiple of 2,
       
   640      * (and has already been verified above 'if (data[2] != 2*count)')
       
   641      * this will be either 2, or none at all!
       
   642      */
       
   643     if (i + 1 < byte_count)
       
   644       *(((u8 *)(dest + dest_pos))+ 0) = *(data+i+1);
       
   645       *(((u8 *)(dest + dest_pos))+ 1) = *(data+i+0);
       
   646       *(((u8 *)(dest + dest_pos))+ 2) = 0;
       
   647       *(((u8 *)(dest + dest_pos))+ 3) = 0;
       
   648   }
       
   649   
       
   650   return response_length;
       
   651 }
       
   652 
       
   653 
       
   654 
       
   655 
       
   656 
       
   657 
       
   658 
       
   659 /* FUNCTION 0x03   - Read Holding Registers */
       
   660 inline int read_output_words(u8  slave,
       
   661                              u16 start_addr,
       
   662                              u16 count,
       
   663                              u16 *dest,
       
   664                              int dest_size,
       
   665                              int ttyfd,
       
   666                              int send_retries,
       
   667                              u8  *error_code,
       
   668                              const struct timespec *response_timeout,
       
   669                              pthread_mutex_t *data_access_mutex) {
       
   670   if( count > MAX_READ_REGS ) {
       
   671     count = MAX_READ_REGS;
       
   672     #ifdef DEBUG
       
   673     fprintf( stderr, "Too many registers requested.\n" );
       
   674     #endif
       
   675   }
       
   676 
       
   677   return read_registers(0x03 /* function */,
       
   678                         slave, start_addr, count, dest, dest_size, ttyfd,
       
   679                         send_retries, error_code, response_timeout, data_access_mutex);
       
   680 }
       
   681 
       
   682 
       
   683 
       
   684 
       
   685 /* FUNCTION 0x03   - Read Holding Registers
       
   686  * u16 registers are stored in array of u32, two registers per u32.
       
   687  * Unused bits of last u32 element are set to 0.
       
   688  */
       
   689 inline int read_output_words_u32(u8  slave,
       
   690                                  u16 start_addr,
       
   691                                  u16 count,
       
   692                                  u32 *dest,
       
   693                                  int ttyfd,
       
   694                                  int send_retries,
       
   695                                  u8  *error_code,
       
   696                                  const struct timespec *response_timeout) {
       
   697   if( count > MAX_READ_REGS ) {
       
   698     count = MAX_READ_REGS;
       
   699     #ifdef DEBUG
       
   700     fprintf( stderr, "Too many registers requested.\n" );
       
   701     #endif
       
   702   }
       
   703   
       
   704   return read_registers_u32(0x03 /* function */,
       
   705                             slave, start_addr, count, dest, ttyfd,
       
   706                             send_retries, error_code, response_timeout);
       
   707 }
       
   708 
       
   709 
       
   710 
       
   711 
       
   712 /* FUNCTION 0x03   - Read Holding Registers
       
   713  * return the array with the data to the calling function
       
   714  */
       
   715 inline int read_output_words_u16_ref(u8  slave,
       
   716                                      u16 start_addr,
       
   717                                      u16 count,
       
   718                                      u16 **dest,
       
   719                                      int ttyfd,
       
   720                                      int send_retries,
       
   721                                      u8  *error_code,
       
   722                                      const struct timespec *response_timeout) {
       
   723   if( count > MAX_READ_REGS ) {
       
   724     count = MAX_READ_REGS;
       
   725     #ifdef DEBUG
       
   726     fprintf( stderr, "Too many registers requested.\n" );
       
   727     #endif
       
   728   }
       
   729   
       
   730   return read_registers_u16_ref(0x03 /* function */,
       
   731                                 slave, start_addr, count, dest, ttyfd, send_retries,
       
   732                                 error_code, response_timeout);
       
   733 }
       
   734 
       
   735 
       
   736 
       
   737 
       
   738 /* FUNCTION 0x04   - Read Input Registers */
       
   739 inline int read_input_words(u8  slave,
       
   740                             u16 start_addr,
       
   741                             u16 count,
       
   742                             u16 *dest,
       
   743                             int dest_size,
       
   744                             int ttyfd,
       
   745                             int send_retries,
       
   746                             u8  *error_code,
       
   747                             const struct timespec *response_timeout,
       
   748                             pthread_mutex_t *data_access_mutex) {
       
   749   if( count > MAX_READ_REGS ) {
       
   750     count = MAX_READ_REGS;
       
   751     #ifdef DEBUG
       
   752     fprintf( stderr, "Too many input registers requested.\n" );
       
   753     #endif
       
   754   }
       
   755   
       
   756   return read_registers(0x04 /* function */,
       
   757                         slave, start_addr, count, dest, dest_size, ttyfd, send_retries,
       
   758                         error_code, response_timeout, data_access_mutex);
       
   759 }
       
   760 
       
   761 
       
   762 /* FUNCTION 0x04   - Read Input Registers
       
   763  * u16 registers are stored in array of u32, two registers per u32.
       
   764  * Unused bits of last u32 element are set to 0.
       
   765  */
       
   766 inline int read_input_words_u32(u8  slave,
       
   767                                 u16 start_addr,
       
   768                                 u16 count,
       
   769                                 u32 *dest,
       
   770                                 int ttyfd,
       
   771                                 int send_retries,
       
   772                                 u8  *error_code,
       
   773                                 const struct timespec *response_timeout) {
       
   774   if( count > MAX_READ_REGS ) {
       
   775     count = MAX_READ_REGS;
       
   776     #ifdef DEBUG
       
   777     fprintf( stderr, "Too many input registers requested.\n" );
       
   778     #endif
       
   779   }
       
   780   
       
   781   return read_registers_u32(0x04 /* function */,
       
   782                             slave, start_addr, count, dest, ttyfd, send_retries,
       
   783                             error_code, response_timeout);
       
   784 }
       
   785 
       
   786 
       
   787 
       
   788 
       
   789 /* FUNCTION 0x04   - Read Input Registers
       
   790  * return the array with the data to the calling function
       
   791  */
       
   792 inline int read_input_words_u16_ref(u8  slave,
       
   793                                     u16 start_addr,
       
   794                                     u16 count,
       
   795                                     u16 **dest,
       
   796                                     int ttyfd,
       
   797                                     int send_retries,
       
   798                                     u8  *error_code,
       
   799                                     const struct timespec *response_timeout) {
       
   800   if( count > MAX_READ_REGS ) {
       
   801     count = MAX_READ_REGS;
       
   802     #ifdef DEBUG
       
   803     fprintf( stderr, "Too many input registers requested.\n" );
       
   804     #endif
       
   805   }
       
   806   
       
   807   return read_registers_u16_ref(0x04 /* function */,
       
   808                                 slave, start_addr, count, dest, ttyfd, send_retries,
       
   809                                 error_code, response_timeout);
       
   810 }
       
   811 
       
   812 
       
   813 
       
   814 /* Execute a transaction for functions that WRITE a sinlge BIT.
       
   815  * Called by:  write_output_bit()
       
   816  *             write_output_word()
       
   817  */
       
   818 static int set_single(u8  function,
       
   819                       u8  slave,
       
   820                       u16 addr,
       
   821                       u16 value,
       
   822                       int ttyfd,
       
   823                       int send_retries,
       
   824                       u8  *error_code,
       
   825                       const struct timespec *response_timeout,
       
   826                       pthread_mutex_t *data_access_mutex) {
       
   827   u8 packet[QUERY_BUFFER_SIZE];
       
   828   u8 *data;
       
   829   int query_length, response_length;
       
   830   
       
   831   if (NULL != data_access_mutex) pthread_mutex_lock(data_access_mutex);
       
   832   query_length = build_packet(slave, function, addr, value, packet);
       
   833   if (NULL != data_access_mutex) pthread_mutex_unlock(data_access_mutex);
       
   834   if (query_length < 0)    return INTERNAL_ERROR;
       
   835   
       
   836   response_length = mb_transaction(packet, query_length, &data, ttyfd, send_retries,
       
   837                                    error_code, response_timeout);
       
   838   
       
   839   if (response_length  < 0)  return response_length;  
       
   840   if (response_length != 6)  return INVALID_FRAME;
       
   841   
       
   842   if ((data[2] != packet[2]) || (data[3] != packet[3]) ||
       
   843       (data[4] != packet[4]) || (data[5] != packet[5]))
       
   844     return INVALID_FRAME;
       
   845   
       
   846   return response_length;
       
   847 }
       
   848 
       
   849 
       
   850 
       
   851 
       
   852 
       
   853 
       
   854 /* FUNCTION 0x05   - Force Single Coil */
       
   855 inline int write_output_bit(u8  slave,
       
   856                             u16 coil_addr,
       
   857                             u16 state,
       
   858                             int fd,
       
   859                             int send_retries,
       
   860                             u8  *error_code,
       
   861                             const struct timespec *response_timeout,
       
   862                             pthread_mutex_t *data_access_mutex) {
       
   863   if (state) state = 0xFF00;
       
   864   
       
   865   return set_single(0x05 /* function */,
       
   866                     slave, coil_addr, state, fd, send_retries,
       
   867                     error_code, response_timeout, data_access_mutex);
       
   868 }
       
   869 
       
   870 
       
   871 
       
   872 
       
   873 
       
   874 /* FUNCTION 0x06   - Write Single Register */
       
   875 inline int write_output_word(u8  slave,
       
   876                              u16 reg_addr,
       
   877                              u16 value,
       
   878                              int fd,
       
   879                              int send_retries,
       
   880                              u8  *error_code,
       
   881                              const struct timespec *response_timeout,
       
   882                              pthread_mutex_t *data_access_mutex) {
       
   883   return set_single(0x06 /* function */, 
       
   884                     slave, reg_addr, value, fd, send_retries,
       
   885                     error_code, response_timeout, data_access_mutex);
       
   886 }
       
   887 
       
   888 
       
   889 
       
   890 
       
   891 /* FUNCTION 0x0F   - Force Multiple Coils */
       
   892 int write_output_bits(u8  slave,
       
   893                       u16 start_addr,
       
   894                       u16 coil_count,
       
   895                       u16 *data,
       
   896                       int ttyfd,
       
   897                       int send_retries,
       
   898                       u8  *error_code,
       
   899                       const struct timespec *response_timeout,
       
   900                       pthread_mutex_t *data_access_mutex) {
       
   901   int byte_count, i;
       
   902   u8  bit;
       
   903   int coil_check = 0;
       
   904   int data_array_pos = 0;
       
   905   int query_length, response_length;
       
   906   u8 packet[QUERY_BUFFER_SIZE];
       
   907   u8  *rdata;
       
   908   
       
   909   if( coil_count > MAX_WRITE_COILS ) {
       
   910     coil_count = MAX_WRITE_COILS;
       
   911     #ifdef DEBUG
       
   912     fprintf( stderr, "Writing to too many coils.\n" );
       
   913     #endif
       
   914   }
       
   915   
       
   916   query_length = build_packet(slave, 0x0F /* function */,
       
   917                               start_addr, coil_count, packet);
       
   918   if (query_length < 0)    return INTERNAL_ERROR;
       
   919   
       
   920   /* NOTE: Integer division. (count+7)/8 is equivalent to ceil(count/8) */
       
   921   byte_count = (coil_count+7)/8;
       
   922   packet[query_length] = byte_count;
       
   923   
       
   924   if (NULL != data_access_mutex) pthread_mutex_lock(data_access_mutex);
       
   925   bit = 0x01;
       
   926   for(i = 0; i < byte_count; i++) {
       
   927     packet[++query_length] = 0;
       
   928     while((bit & 0xFF) && (coil_check++ < coil_count)) {
       
   929       if(data[data_array_pos++]) {packet[query_length] |=  bit;}
       
   930       else                       {packet[query_length] &= ~bit;}
       
   931       bit <<= 1;
       
   932     }
       
   933     bit = 0x01;
       
   934   }
       
   935   if (NULL != data_access_mutex) pthread_mutex_unlock(data_access_mutex);
       
   936   
       
   937   response_length = mb_transaction(packet, ++query_length, &rdata, ttyfd, send_retries,
       
   938                                    error_code, response_timeout);
       
   939   
       
   940   if (response_length  < 0)      return response_length;
       
   941   if (response_length != 6)      return INVALID_FRAME;
       
   942   if ((rdata[2] != packet[2]) || 
       
   943       (rdata[3] != packet[3]) ||
       
   944       (rdata[4] != packet[4]) ||
       
   945       (rdata[5] != packet[5]))   return INVALID_FRAME;
       
   946   
       
   947   return response_length;
       
   948 }
       
   949 
       
   950 
       
   951 
       
   952 /* FUNCTION 0x0F   - Force Multiple Coils
       
   953  * Bits should be stored on an u32 array, 32 bits per u32.
       
   954  * Unused bits in last u32 should be set to 0.
       
   955  */
       
   956 int write_output_bits_u32(u8  slave,
       
   957                           u16 start_addr,
       
   958                           u16 coil_count,
       
   959                           u32 *data,
       
   960                           int ttyfd,
       
   961                           int send_retries,
       
   962                           u8  *error_code,
       
   963                           const struct timespec *response_timeout) {
       
   964   int org_pos, byte_count, i;
       
   965   int query_length, response_length;
       
   966   u8 packet[QUERY_BUFFER_SIZE];
       
   967   u8  *rdata;
       
   968   
       
   969   if( coil_count > MAX_WRITE_COILS ) {
       
   970     coil_count = MAX_WRITE_COILS;
       
   971     #ifdef DEBUG
       
   972     fprintf( stderr, "Writing to too many coils.\n" );
       
   973     #endif
       
   974   }
       
   975   
       
   976   query_length = build_packet(slave, 0x0F /* function */,
       
   977                               start_addr, coil_count, packet);
       
   978   if (query_length < 0)    return INTERNAL_ERROR;
       
   979   
       
   980   /* NOTE: Integer division. This is equivalent of determining the ceil(count/8) */
       
   981   byte_count = (coil_count+7)/8;
       
   982   packet[query_length] = byte_count;
       
   983   
       
   984   /* handle groups of 4 bytes... */
       
   985   for(i = 0, org_pos = 0; i + 3 < byte_count; i += 4, org_pos++) {
       
   986     packet[++query_length] = data[org_pos] & 0xFF; data[org_pos] >>= 8;
       
   987     packet[++query_length] = data[org_pos] & 0xFF; data[org_pos] >>= 8;
       
   988     packet[++query_length] = data[org_pos] & 0xFF; data[org_pos] >>= 8;
       
   989     packet[++query_length] = data[org_pos] & 0xFF;
       
   990   }
       
   991   /* handle any remaining bytes... */
       
   992   for(; i < byte_count; i++) {
       
   993     packet[++query_length] = data[org_pos] & 0xFF; 
       
   994     data[org_pos] >>= 8;
       
   995   }
       
   996   
       
   997   response_length = mb_transaction(packet, ++query_length, &rdata, ttyfd, send_retries,
       
   998                                    error_code, response_timeout);
       
   999   
       
  1000   if (response_length  < 0)       return response_length;
       
  1001   if (response_length != 6)       return INVALID_FRAME;
       
  1002   if ((rdata[2] != packet[2]) ||
       
  1003       (rdata[3] != packet[3]) ||
       
  1004       (rdata[4] != packet[4]) ||
       
  1005       (rdata[5] != packet[5]))    return INVALID_FRAME;
       
  1006   
       
  1007   return response_length;
       
  1008 }
       
  1009 
       
  1010 
       
  1011 
       
  1012 
       
  1013 
       
  1014 /* FUNCTION 0x10   - Force Multiple Registers */
       
  1015 int write_output_words(u8  slave,
       
  1016                        u16 start_addr,
       
  1017                        u16 reg_count,
       
  1018                        u16 *data,
       
  1019                        int ttyfd,
       
  1020                        int send_retries,
       
  1021                        u8  *error_code,
       
  1022                        const struct timespec *response_timeout,
       
  1023                        pthread_mutex_t *data_access_mutex) {
       
  1024   u8  byte_count;
       
  1025   int i, query_length, response_length;
       
  1026   u8 packet[QUERY_BUFFER_SIZE];
       
  1027   u8  *rdata;
       
  1028   
       
  1029   if( reg_count > MAX_WRITE_REGS ) {
       
  1030     reg_count = MAX_WRITE_REGS;
       
  1031     #ifdef DEBUG
       
  1032     fprintf( stderr, "Trying to write to too many registers.\n" );
       
  1033     #endif
       
  1034   }
       
  1035   
       
  1036   query_length = build_packet(slave, 0x10 /* function */,
       
  1037                               start_addr, reg_count, packet);
       
  1038   if (query_length < 0)    return INTERNAL_ERROR;
       
  1039   
       
  1040   byte_count = reg_count*2;
       
  1041   packet[query_length] = byte_count;
       
  1042   
       
  1043   if (NULL != data_access_mutex) pthread_mutex_lock(data_access_mutex);
       
  1044   for( i = 0; i < reg_count; i++ ) {
       
  1045     packet[++query_length] = data[i] >> 8;
       
  1046     packet[++query_length] = data[i] & 0x00FF;
       
  1047   }
       
  1048   if (NULL != data_access_mutex) pthread_mutex_unlock(data_access_mutex);
       
  1049   
       
  1050   response_length = mb_transaction(packet, ++query_length, &rdata, ttyfd, send_retries,
       
  1051                                    error_code, response_timeout);
       
  1052   
       
  1053   if (response_length  < 0)       return response_length;  
       
  1054   if (response_length != 6)       return INVALID_FRAME;  
       
  1055   if ((rdata[2] != packet[2]) ||
       
  1056       (rdata[3] != packet[3]) ||      
       
  1057       (rdata[4] != packet[4]) ||
       
  1058       (rdata[5] != packet[5]))    return INVALID_FRAME;
       
  1059   
       
  1060   return response_length;
       
  1061 }
       
  1062 
       
  1063 
       
  1064 
       
  1065 
       
  1066 /* FUNCTION 0x10   - Force Multiple Registers
       
  1067  * u16 registers are stored in array of u32, two registers per u32.
       
  1068  * Unused bits of last u32 element are set to 0.
       
  1069  */
       
  1070 int write_output_words_u32(u8  slave,
       
  1071                            u16 start_addr,
       
  1072                              /* number of 16 bit registers packed in the u32 array! */
       
  1073                            u16 reg_count,
       
  1074                            u32 *data,
       
  1075                            int ttyfd,
       
  1076                            int send_retries,
       
  1077                            u8  *error_code,
       
  1078                            const struct timespec *response_timeout) {
       
  1079   u8  byte_count;
       
  1080   int i, query_length, response_length;
       
  1081   u8 packet_[QUERY_BUFFER_SIZE];
       
  1082   u8 *packet = packet_; /* remove the const'ness of packet_ */
       
  1083   u8  *rdata;
       
  1084   
       
  1085   if( reg_count > MAX_WRITE_REGS ) {
       
  1086     reg_count = MAX_WRITE_REGS;
       
  1087     #ifdef DEBUG
       
  1088     fprintf( stderr, "Trying to write to too many registers.\n" );
       
  1089     #endif
       
  1090   }
       
  1091   
       
  1092   /* Make sure that the de-referencing and up-casting going on later on in 
       
  1093    * this function, i.e. code like the following line:
       
  1094    * *((u16 *)packet) = XXX
       
  1095    * will result in u16 words starting off on even addresses.
       
  1096    * If we don't do this, some compilers (e.g. AVR32 cross-compiler) will 
       
  1097    * generate code which, when executed, will result in 'bus error'.
       
  1098    *
       
  1099    * The following packet++ means that the first byte of the packet array is
       
  1100    * essentially never used. Notice too that the size of thepacket array
       
  1101    * already takes into account this un-used byte.
       
  1102    */
       
  1103   packet++;
       
  1104   
       
  1105   query_length = build_packet(slave, 0x10 /* function */,
       
  1106                               start_addr, reg_count, packet);
       
  1107   if (query_length < 0)  return INTERNAL_ERROR;
       
  1108   
       
  1109   byte_count = reg_count*2;
       
  1110   packet[query_length] = byte_count;
       
  1111   
       
  1112   /* handle groups of 4 bytes... */
       
  1113   for(i = 0; 4*i + 3 < byte_count; i++) {
       
  1114     *((u16 *)(packet+(++query_length))) = mb_hton(data[i]);        ++query_length;
       
  1115     *((u16 *)(packet+(++query_length))) = mb_hton(data[i] >> 16);  ++query_length;
       
  1116   }
       
  1117   
       
  1118   /* handle any remaining bytes...
       
  1119    * since byte_count is supposed to be multiple of 2,
       
  1120    * (and has already been verified above 'if (data[2] != 2*count)')
       
  1121    * this will be either 2, or none at all!
       
  1122    */
       
  1123   if (4*i + 1 < byte_count) {
       
  1124     *((u16 *)(packet+(++query_length))) = mb_hton(data[i]);        ++query_length;
       
  1125   }
       
  1126   
       
  1127   response_length = mb_transaction(packet, ++query_length, &rdata, ttyfd, send_retries,
       
  1128                                    error_code, response_timeout);
       
  1129     
       
  1130   if (response_length  < 0)       return response_length;  
       
  1131   if (response_length != 6)       return INVALID_FRAME;  
       
  1132   if ((rdata[2] != packet[2]) ||
       
  1133       (rdata[3] != packet[3]) ||
       
  1134       (rdata[4] != packet[4]) ||
       
  1135       (rdata[5] != packet[5]))    return INVALID_FRAME;
       
  1136   
       
  1137   return response_length;
       
  1138 }
       
  1139 
       
  1140 
       
  1141 
       
  1142 
       
  1143 
       
  1144 
       
  1145 /************************************************/
       
  1146 /************************************************/
       
  1147 /**                                            **/
       
  1148 /**   Modbus Library Management Functions.     **/
       
  1149 /**                                            **/
       
  1150 /************************************************/
       
  1151 /************************************************/
       
  1152 
       
  1153 
       
  1154 
       
  1155 /* Initialise the Modbus Master Layer */
       
  1156 int mb_master_init__(int extra_bytes) {
       
  1157   #ifdef DEBUG
       
  1158   fprintf(stderr, "mb_master_init__(extra_bytes=%d), QUERY_BUFFER_SIZE=%d\n", extra_bytes, QUERY_BUFFER_SIZE);
       
  1159   #endif
       
  1160   buff_extra_bytes_ = extra_bytes;
       
  1161   return 0;
       
  1162 }
       
  1163 
       
  1164 
       
  1165 /* Shut down the Modbus Master Layer */
       
  1166 int mb_master_done__(void) {
       
  1167         return 0;
       
  1168 }
       
  1169 
       
  1170 
       
  1171 #if 0
       
  1172 int mb_master_init(int nd_count) {
       
  1173   int extra_bytes;
       
  1174   
       
  1175   #ifdef DEBUG
       
  1176   fprintf( stderr, "mb_master_init()\n");
       
  1177   fprintf( stderr, "creating %d nodes\n", nd_count);
       
  1178   #endif
       
  1179   
       
  1180   /* initialise layer 1 library */
       
  1181   if (modbus_init(nd_count, DEF_OPTIMIZATION, &extra_bytes) < 0)
       
  1182     goto error_exit_0;
       
  1183   
       
  1184   /* initialise this library */
       
  1185   if (mb_master_init__(extra_bytes) < 0)
       
  1186     goto error_exit_1;
       
  1187   
       
  1188   return 0;
       
  1189   
       
  1190 error_exit_1:
       
  1191   modbus_done();
       
  1192 error_exit_0:
       
  1193   return -1;
       
  1194 }
       
  1195 
       
  1196 
       
  1197 int mb_master_done(void) {
       
  1198   mb_master_done__();
       
  1199   return modbus_done();
       
  1200 }
       
  1201 #endif
       
  1202 
       
  1203 
       
  1204 /* Establish a connection to a remote server/slave */
       
  1205 /* NOTE: We use the lower 2 bits of the returned node id to identify which 
       
  1206  *       layer1 implementation to use. 
       
  1207  *           0 -> TCP 
       
  1208  *           1 -> RTU 
       
  1209  *           2 -> ASCII 
       
  1210  *           4 -> unused 
       
  1211  *       The node id used by the layer1 is shifted left 2 bits
       
  1212  *       before returning the node id to the caller!
       
  1213  */
       
  1214 int mb_master_connect(node_addr_t node_addr) {
       
  1215   int res = -1;
       
  1216   
       
  1217   #ifdef DEBUG
       
  1218   fprintf( stderr, "mb_master_tcp connect()\n");
       
  1219   #endif
       
  1220   
       
  1221   /* call layer 1 library */
       
  1222   switch(node_addr.naf) {
       
  1223     case naf_tcp:  
       
  1224       res = modbus_tcp_connect(node_addr);
       
  1225       if (res >= 0) res = res*4 + 0 /* offset into fptr_ with TCP functions */;
       
  1226       return res;
       
  1227     case naf_rtu:  
       
  1228       res = modbus_rtu_connect(node_addr);
       
  1229       if (res >= 0) res = res*4 + 1 /* offset into fptr_ with RTU functions */;
       
  1230       return res;
       
  1231     case naf_ascii:  
       
  1232       res = modbus_ascii_connect(node_addr);
       
  1233       if (res >= 0) res = res*4 + 2 /* offset into fptr_ with ASCII functions */;
       
  1234       return res;
       
  1235   }
       
  1236   
       
  1237   return -1;
       
  1238 }
       
  1239 
       
  1240 
       
  1241 
       
  1242 
       
  1243 
       
  1244 /* Shut down a connection to a remote server/slave */
       
  1245 int mb_master_close(int fd) {
       
  1246   #ifdef DEBUG
       
  1247   fprintf( stderr, "mb_master_close(): nd = %d\n", fd);
       
  1248   #endif
       
  1249   get_ttyfd(); /* declare the ttyfd variable, ... */
       
  1250   /* call layer 1 library */
       
  1251   return modbus_close(ttyfd);
       
  1252 }
       
  1253 
       
  1254 
       
  1255 
       
  1256 
       
  1257 
       
  1258 
       
  1259 /* Tell the library that communications will be suspended for some time. */
       
  1260 /* RTU and ASCII versions ignore this function
       
  1261  * TCP version closes all the open tcp connections (connections are automatically
       
  1262  *   re-established the next time an IO function to the slave is requested).
       
  1263  *   To be more precise, the TCP version makes an estimate of how long
       
  1264  *   the silence will be based on previous invocations to this exact same
       
  1265  *   function, and will only close the connections if this silence is
       
  1266  *   expected to be longer than 1 second!
       
  1267  *   (The closing of connections is specified in Modbus specification)
       
  1268  */
       
  1269 int mb_master_tcp_silence_init(void) {
       
  1270   #ifdef DEBUG
       
  1271   fprintf( stderr, "mb_master_silence_init():\n");
       
  1272   #endif
       
  1273   /* call layer 1 library */
       
  1274   return modbus_tcp_silence_init();
       
  1275 }
       
  1276 
       
  1277