Ver código fonte

Unique transaction identifier by TCP connection

- remove static variable in the library

libabc is a really good source of inspiration!
https://git.kernel.org/?p=linux/kernel/git/kay/libabc.git
Stéphane Raimbault 13 anos atrás
pai
commit
6564c32b21
2 arquivos alterados com 19 adições e 13 exclusões
  1. 9 0
      src/modbus-tcp-private.h
  2. 10 13
      src/modbus-tcp.c

+ 9 - 0
src/modbus-tcp-private.h

@@ -25,7 +25,14 @@
 
 #define _MODBUS_TCP_CHECKSUM_LENGTH    0
 
+/* In both structures, the transaction ID must be placed on first position
+   to have a quick access not dependant of the TCP backend */
 typedef struct _modbus_tcp {
+    /* Extract from MODBUS Messaging on TCP/IP Implementation Guide V1.0b
+       (page 23/46):
+       The transaction identifier is used to associate the future response
+       with the request. This identifier is unique on each TCP connection. */
+    uint16_t t_id;
     /* TCP port */
     int port;
     /* IP address */
@@ -36,6 +43,8 @@ typedef struct _modbus_tcp {
 #define _MODBUS_TCP_PI_SERVICE_LENGTH   32
 
 typedef struct _modbus_tcp_pi {
+    /* Transaction ID */
+    uint16_t t_id;
     /* TCP port */
     int port;
     /* Node */

+ 10 - 13
src/modbus-tcp.c

@@ -102,21 +102,15 @@ int _modbus_tcp_build_request_basis(modbus_t *ctx, int function,
                                     int addr, int nb,
                                     uint8_t *req)
 {
+    modbus_tcp_t *ctx_tcp = ctx->backend_data;
 
-    /* Extract from MODBUS Messaging on TCP/IP Implementation Guide V1.0b
-       (page 23/46):
-       The transaction identifier is used to associate the future response
-       with the request. So, at a time, on a TCP connection, this identifier
-       must be unique. */
-    static uint16_t t_id = 0;
-
-    /* Transaction ID */
-    if (t_id < UINT16_MAX)
-        t_id++;
+    /* Increase transaction ID */
+    if (ctx_tcp->t_id < UINT16_MAX)
+        ctx_tcp->t_id++;
     else
-        t_id = 0;
-    req[0] = t_id >> 8;
-    req[1] = t_id & 0x00ff;
+        ctx_tcp->t_id = 0;
+    req[0] = ctx_tcp->t_id >> 8;
+    req[1] = ctx_tcp->t_id & 0x00ff;
 
     /* Protocol Modbus */
     req[2] = 0;
@@ -688,6 +682,7 @@ modbus_t* modbus_new_tcp(const char *ip, int port)
     }
 
     ctx_tcp->port = port;
+    ctx_tcp->t_id = 0;
 
     return ctx;
 }
@@ -743,5 +738,7 @@ modbus_t* modbus_new_tcp_pi(const char *node, const char *service)
         return NULL;
     }
 
+    ctx_tcp_pi->t_id = 0;
+
     return ctx;
 }