author | Edouard Tisserant <edouard.tisserant@gmail.com> |
Mon, 07 Jun 2021 11:21:26 +0200 | |
changeset 17 | e319814f1c17 |
parent 12 | 16ea5cbbda4e |
permissions | -rw-r--r-- |
0 | 1 |
/* |
2 |
* Copyright (c) 2002,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 |
||
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 <assert.h> |
|
35 |
#include <errno.h> /* Error definitions */ |
|
36 |
#include <time.h> /* clock_gettime() */ |
|
37 |
#include <sys/types.h> |
|
38 |
#include <sys/socket.h> |
|
39 |
#include <netinet/in.h> /* required for htons() and ntohs() */ |
|
40 |
#include <netinet/tcp.h> /* TCP level socket options */ |
|
41 |
#include <netinet/ip.h> /* IP level socket options */ |
|
42 |
||
43 |
#include <pthread.h> |
|
44 |
#include <sched.h> /* sched_yield() */ |
|
45 |
||
46 |
||
47 |
||
48 |
#include "sin_util.h" /* internet socket utility functions... */ |
|
49 |
#include "mb_layer1.h" /* The public interface this file implements... */ |
|
50 |
#include "mb_tcp_private.h" |
|
51 |
||
52 |
||
53 |
||
54 |
/************************************/ |
|
55 |
/** **/ |
|
56 |
/** Include common code... **/ |
|
57 |
/** **/ |
|
58 |
/************************************/ |
|
59 |
||
60 |
#include "mb_time_util.h" |
|
61 |
||
62 |
||
63 |
//#define ERRMSG |
|
64 |
#define ERRMSG_HEAD "Modbus/TCP: " |
|
65 |
||
66 |
||
67 |
// #define DEBUG /* uncomment to see the data sent and received */ |
|
68 |
||
69 |
||
70 |
#ifdef DEBUG |
|
71 |
#ifndef ERRMSG |
|
72 |
#define ERRMSG |
|
73 |
#endif |
|
74 |
#endif |
|
75 |
||
76 |
||
77 |
||
78 |
/**************************************************************/ |
|
79 |
/**************************************************************/ |
|
80 |
/**** ****/ |
|
81 |
/**** ****/ |
|
82 |
/**** Forward Declarations ****/ |
|
83 |
/**** and Defaults ****/ |
|
84 |
/**** ****/ |
|
85 |
/**************************************************************/ |
|
86 |
/**************************************************************/ |
|
87 |
||
88 |
||
89 |
/* A Node Descriptor metadata, |
|
90 |
* Due to the fact that modbus TCP is connection oriented, |
|
91 |
* and that if the client detects an error the connection |
|
92 |
* must be shut down and re-established automatically, |
|
93 |
* the modbus TCP layer needs to keep the address of the remote server. |
|
94 |
* |
|
95 |
* We do this by implementing a node descriptor table, in which each |
|
96 |
* entry will have the remote address, and the file descriptor |
|
97 |
* of the socket currently in use. |
|
98 |
* |
|
99 |
* We do not pass the file descriptor up to the next higher layer. We |
|
100 |
* send them the node descriptor instead... |
|
101 |
*/ |
|
102 |
#define MB_MASTER_NODE 12 |
|
103 |
#define MB_LISTEN_NODE 14 |
|
104 |
#define MB_SLAVE_NODE 16 |
|
105 |
#define MB_FREE_NODE 18 |
|
106 |
typedef sa_family_t nd_type_t; |
|
107 |
||
108 |
typedef struct { |
|
109 |
int fd; /* socket descriptor == file descriptor */ |
|
110 |
/* NOTE: |
|
111 |
* Modbus TCP says that on error, we should close |
|
112 |
* a connection and retry with a new connection. |
|
113 |
* Since it takes time for a socket to close |
|
114 |
* a connection if the remote server is down, |
|
115 |
* we close the connection on the socket, close the |
|
116 |
* socket itself, and create a new one for the new |
|
117 |
* connection. There will be times when the node will |
|
118 |
* not have any valid socket, and it will have to |
|
119 |
* be created on the fly. |
|
120 |
* When the node does not have a valid socket, |
|
121 |
* fd will be set to -1 |
|
122 |
*/ |
|
123 |
int node_type; /* What kind of use we are giving to this node... |
|
124 |
* If node_type == MB_MASTER_NODE |
|
125 |
* The node descriptor was initialised by the |
|
126 |
* modbus_connect() function. |
|
127 |
* The node descriptor is being used by a master |
|
128 |
* device, and the addr contains the address of the slave. |
|
129 |
* Remember that in this case fd may be >= 0 while |
|
130 |
* we have a valid connection, or it may be < 0 when |
|
131 |
* the connection needs to be reset. |
|
132 |
* If node_type == MB_LISTEN_NODE |
|
133 |
* The node descriptor was initialised by the |
|
134 |
* modbus_listen() function. |
|
135 |
* The node is merely used to accept() new connection |
|
136 |
* requests. The new slave connections will use another |
|
137 |
* node to transfer data. |
|
138 |
* In this case fd must be >= 0. |
|
139 |
* fd < 0 is an ilegal state and should never occur. |
|
140 |
* If node_type == MB_SLAVE_NODE |
|
141 |
* The node descriptor was initialised when a new |
|
142 |
* connection request arrived on a MB_LISTEN type node. |
|
143 |
* The node descriptor is being used by a slave device, |
|
144 |
* and is currently being used to connect to a master. |
|
145 |
* In this case fd must be >= 0. |
|
146 |
* fd < 0 is an ilegal state and should never occur. |
|
147 |
* If node_type == FREE_ND |
|
148 |
* The node descriptor is currently not being used. |
|
149 |
* In this case fd is set to -1, but is really irrelevant. |
|
150 |
*/ |
|
151 |
struct sockaddr_in addr; /* The internet adress we are using. |
|
152 |
* If node_type == MB_MASTER_NODE |
|
153 |
* addr will be the address of the remote slave |
|
154 |
* If node_type == MB_LISTEN_NODE |
|
155 |
* addr will be the address of the local listening port and network interface |
|
156 |
* If node_type == MB_SLAVE_NODE |
|
157 |
* addr will be the address of the local port and network interface |
|
158 |
* of the connection to the specific client. |
|
159 |
*/ |
|
160 |
int listen_node; /* When a slave accepts a connection through a MB_LISTEN_NODE, it will |
|
161 |
* will use an empty node for the new connection, and configure this new node |
|
162 |
* to use the type MB_SLAVE_NODE. |
|
163 |
* The listen_node entry is only used by nodes of type MB_SLAVE_NODE. |
|
164 |
* In this case, listen_node will be the node of type MB_LISTEN_NODE through |
|
165 |
* which the connection request came through... |
|
166 |
*/ |
|
167 |
int close_on_silence; /* A flag used only by Master Nodes. |
|
168 |
* When (close_on_silence > 0), then the connection to the |
|
169 |
* slave device will be shut down whenever the |
|
170 |
* modbus_tcp_silence_init() function is called. |
|
171 |
* Remember that the connection will be automatically |
|
172 |
* re-established the next time the user wishes to communicate |
|
173 |
* with the same slave (using this same node descripto). |
|
174 |
* If the user wishes to comply with the sugestion |
|
175 |
* in the OpenModbus Spec, (s)he should set this flag |
|
176 |
* if a silence interval longer than 1 second is expected. |
|
177 |
*/ |
|
178 |
int print_connect_error; /* flag to guarantee we only print an error the first time we |
|
179 |
* attempt to connect to a emote server. |
|
180 |
* Stops us from generting a cascade of errors while the slave |
|
181 |
* is down. |
|
182 |
* Flag will get reset every time we successfully |
|
183 |
* establish a connection, so a message is once again generated |
|
184 |
* on the next error. |
|
185 |
*/ |
|
186 |
u8 *recv_buf; /* This node's receive buffer |
|
187 |
* The library supports multiple simultaneous connections, |
|
188 |
* and may need to receive multiple frames through mutiple nodes concurrently. |
|
189 |
* To make the library thread-safe, we use one buffer for each node. |
|
190 |
*/ |
|
191 |
} nd_entry_t; |
|
192 |
||
193 |
||
194 |
/* please make sure to lock the node table mutex before calling this function */ |
|
195 |
static int nd_entry_init(nd_entry_t *nde) { |
|
196 |
nde->addr.sin_family = AF_INET ; |
|
197 |
nde->node_type = MB_FREE_NODE; |
|
198 |
nde->fd = -1; /* not currently connected... */ |
|
199 |
/* initialise recv buffer */ |
|
200 |
nde->recv_buf = malloc(sizeof(u8) * RECV_BUFFER_SIZE); |
|
201 |
if (nde->recv_buf == NULL) |
|
202 |
return -1; |
|
203 |
return 0; |
|
204 |
} |
|
205 |
||
206 |
/* please make sure to lock the node table mutex before calling this function */ |
|
207 |
static int nd_entry_done(nd_entry_t *nde) { |
|
208 |
free(nde->recv_buf); |
|
209 |
return 0; |
|
210 |
} |
|
211 |
||
212 |
||
213 |
||
214 |
typedef struct { |
|
215 |
/* the array of node descriptors, and current size... */ |
|
216 |
nd_entry_t *node; /* array of node entries. if NULL => node table not initialized */ |
|
217 |
int node_count; /* total number of nodes in the node[] array */ |
|
218 |
int free_node_count; /* number of free nodes in the node[] array */ |
|
219 |
pthread_mutex_t mutex; |
|
220 |
} nd_table_t; |
|
221 |
||
222 |
||
223 |
||
224 |
static int nd_table_done(nd_table_t *ndt) { |
|
225 |
int count; |
|
226 |
||
227 |
if (ndt->node == NULL) |
|
228 |
return 0; |
|
229 |
||
230 |
/* lock the mutex */ |
|
231 |
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield(); |
|
232 |
||
233 |
/* initialise the state of each node in the array... */ |
|
234 |
for (count = 0; count < ndt->node_count; count++) { |
|
235 |
nd_entry_done(&ndt->node[count]); |
|
236 |
} /* for() */ |
|
237 |
||
238 |
free(ndt->node); |
|
239 |
pthread_mutex_unlock (&ndt->mutex); |
|
240 |
pthread_mutex_destroy(&ndt->mutex); |
|
241 |
*ndt = (nd_table_t){.node=NULL, .node_count=0, .free_node_count=0}; |
|
242 |
||
243 |
return 0; |
|
244 |
} |
|
245 |
||
246 |
||
247 |
||
248 |
||
249 |
#if 1 |
|
250 |
/* nd_table_init() |
|
251 |
* Version 1 of the nd_table_init() function. |
|
252 |
* If called more than once, 2nd and any subsequent calls will |
|
253 |
* be interpreted as a request to confirm that it was already correctly |
|
254 |
* initialized with the requested number of nodes. |
|
255 |
*/ |
|
256 |
static int nd_table_init(nd_table_t *ndt, int nd_count) { |
|
257 |
int count; |
|
258 |
||
259 |
if (ndt->node != NULL) { |
|
260 |
/* this function has already been called, and the node table is already initialised */ |
|
261 |
return (ndt->node_count == nd_count)?0:-1; |
|
262 |
} |
|
263 |
||
264 |
/* initialise the node table mutex... */ |
|
265 |
pthread_mutex_init(&ndt->mutex, NULL); |
|
266 |
if (pthread_mutex_lock(&ndt->mutex) != 0) { |
|
267 |
#ifdef DEBUG |
|
268 |
perror("pthread_mutex_lock()"); |
|
269 |
fprintf(stderr, "[%lu] Unable to lock newly crated mutex while creating new node table!\n", pthread_self()); |
|
270 |
#endif |
|
271 |
pthread_mutex_destroy(&ndt->mutex); |
|
272 |
return -1; |
|
273 |
} |
|
274 |
||
275 |
/* initialise the node descriptor metadata array... */ |
|
276 |
ndt->node = malloc(sizeof(nd_entry_t) * nd_count); |
|
277 |
if (ndt->node == NULL) { |
|
278 |
#ifdef DEBUG |
|
279 |
perror("malloc()"); |
|
280 |
fprintf(stderr, "[%lu] Out of memory: error initializing node address buffer\n", pthread_self()); |
|
281 |
#endif |
|
282 |
#ifdef ERRMSG |
|
283 |
perror("malloc()"); |
|
284 |
fprintf(stderr, ERRMSG_HEAD "Out of memory. Error initializing node address buffer\n"); |
|
285 |
#endif |
|
286 |
pthread_mutex_unlock (&ndt->mutex); |
|
287 |
pthread_mutex_destroy(&ndt->mutex); |
|
288 |
return -1; |
|
289 |
} |
|
290 |
||
291 |
/* initialise the state of each node in the array... */ |
|
292 |
for (count = 0; count < nd_count; count++) { |
|
293 |
if (nd_entry_init(&ndt->node[count]) < 0) { |
|
294 |
pthread_mutex_unlock(&ndt->mutex); |
|
295 |
nd_table_done(ndt); |
|
296 |
return -1; |
|
297 |
} |
|
298 |
ndt->node_count = count+1; |
|
299 |
ndt->free_node_count = count+1; |
|
300 |
} /* for() */ |
|
301 |
||
302 |
ndt->node_count = nd_count; |
|
303 |
ndt->free_node_count = nd_count; |
|
304 |
||
305 |
pthread_mutex_unlock(&ndt->mutex); |
|
306 |
return nd_count; /* number of succesfully created nodes! */ |
|
307 |
} |
|
308 |
||
309 |
||
310 |
#else |
|
311 |
/* nd_table_init() |
|
312 |
* Version 2 of the nd_table_init() function. |
|
313 |
* If called more than once, 2nd and any subsequent calls will |
|
314 |
* be interpreted as a request to reserve an extra new_nd_count |
|
315 |
* number of nodes. This will be done using realloc(). |
|
316 |
*/ |
|
317 |
static int nd_table_init(nd_table_t *ndt, int new_nd_count) { |
|
318 |
int count; |
|
319 |
||
320 |
if (ndt->node == NULL) { |
|
321 |
/* Node table nt yet initialized => we must initialise the node table mutex... */ |
|
322 |
pthread_mutex_init(&ndt->mutex, NULL); |
|
323 |
} |
|
324 |
||
325 |
/* lock the mutex */ |
|
326 |
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield(); |
|
327 |
||
328 |
/* initialise the node descriptor metadata array... */ |
|
329 |
ndt->node = realloc(ndt->node, sizeof(nd_entry_t) * (ndt->node_count + new_nd_count)); |
|
330 |
if (ndt->node == NULL) { |
|
331 |
#ifdef DEBUG |
|
332 |
perror("malloc()"); |
|
333 |
fprintf(stderr, "[%lu] Out of memory: error initializing node address buffer\n", pthread_self()); |
|
334 |
#endif |
|
335 |
#ifdef ERRMSG |
|
336 |
perror("malloc()"); |
|
337 |
fprintf(stderr, ERRMSG_HEAD "Out of memory. Error initializing node address buffer\n"); |
|
338 |
#endif |
|
339 |
pthread_mutex_unlock (&ndt->mutex); |
|
340 |
pthread_mutex_destroy(&ndt->mutex); |
|
341 |
return -1; |
|
342 |
} |
|
343 |
||
344 |
/* initialise the state of each newly added node in the array... */ |
|
345 |
for (count = ndt->node_count; count < ndt->node_count + new_nd_count; count++) { |
|
346 |
if (nd_entry_init(&ndt->node[count]) < 0) { |
|
347 |
pthread_mutex_unlock(&ndt->mutex); |
|
348 |
return -1; |
|
349 |
} |
|
350 |
} /* for() */ |
|
351 |
ndt->node_count += new_nd_count; |
|
352 |
ndt->free_node_count += new_nd_count; |
|
353 |
||
354 |
pthread_mutex_unlock(&ndt->mutex); |
|
355 |
return new_nd_count; /* number of succesfully created nodes! */ |
|
356 |
} |
|
357 |
#endif |
|
358 |
||
359 |
||
360 |
static int nd_table_get_free_node(nd_table_t *ndt, nd_type_t nd_type) { |
|
361 |
int count; |
|
362 |
||
363 |
/* lock the mutex */ |
|
364 |
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield(); |
|
365 |
||
366 |
/* check for free nodes... */ |
|
367 |
if (ndt->free_node_count <= 0) { |
|
368 |
/* no free nodes... */ |
|
369 |
pthread_mutex_unlock(&ndt->mutex); |
|
370 |
return -1; |
|
371 |
} |
|
372 |
||
373 |
/* Decrement the free node counter...*/ |
|
374 |
ndt->free_node_count--; |
|
375 |
||
376 |
/* search for a free node... */ |
|
377 |
for (count = 0; count < ndt->node_count; count++) { |
|
378 |
if(ndt->node[count].node_type == MB_FREE_NODE) { |
|
379 |
/* found one!! Allocate it to the new type! */ |
|
380 |
ndt->node[count].node_type = nd_type; |
|
381 |
pthread_mutex_unlock(&ndt->mutex); |
|
382 |
return count; |
|
383 |
} |
|
384 |
} /* for() */ |
|
385 |
||
386 |
/* Strange... We should have free nodes, but we didn't finda any! */ |
|
387 |
/* Let's try to get into a consistent state, and return an error! */ |
|
388 |
ndt->free_node_count = 0; |
|
389 |
pthread_mutex_unlock(&ndt->mutex); |
|
390 |
return -1; |
|
391 |
} |
|
392 |
||
393 |
||
394 |
||
395 |
static void nd_table_close_node(nd_table_t *ndt, int nd) { |
|
396 |
||
397 |
/* lock the mutex */ |
|
398 |
while (pthread_mutex_lock(&ndt->mutex) != 0) sched_yield(); |
|
399 |
||
400 |
if(ndt->node[nd].node_type == MB_FREE_NODE) { |
|
401 |
/* Node already free... */ |
|
402 |
pthread_mutex_unlock(&ndt->mutex); |
|
403 |
return; |
|
404 |
} |
|
405 |
||
406 |
/* Increment the free node counter...*/ |
|
407 |
ndt->free_node_count++; |
|
408 |
/* Mark the node as being free. */ |
|
409 |
ndt->node[nd].node_type = MB_FREE_NODE; |
|
410 |
||
411 |
pthread_mutex_unlock(&ndt->mutex); |
|
412 |
return; |
|
413 |
} |
|
414 |
||
415 |
||
416 |
||
417 |
/**************************************************************/ |
|
418 |
/**************************************************************/ |
|
419 |
/**** ****/ |
|
420 |
/**** ****/ |
|
421 |
/**** Global Library State ****/ |
|
422 |
/**** ****/ |
|
423 |
/**** ****/ |
|
424 |
/**************************************************************/ |
|
425 |
/**************************************************************/ |
|
426 |
||
427 |
||
428 |
/* The node descriptor table... */ |
|
429 |
/* NOTE: The node_table_ Must be initialized correctly here! */ |
|
430 |
static nd_table_t nd_table_ = {.node=NULL, .node_count=0, .free_node_count=0}; |
|
431 |
||
432 |
||
433 |
/**************************************************************/ |
|
434 |
/**************************************************************/ |
|
435 |
/**** ****/ |
|
436 |
/**** ****/ |
|
437 |
/**** Local Utility functions... ****/ |
|
438 |
/**** ****/ |
|
439 |
/**** ****/ |
|
440 |
/**************************************************************/ |
|
441 |
/**************************************************************/ |
|
442 |
||
443 |
||
444 |
#define min(a,b) ((a<b)?a:b) |
|
445 |
#define max(a,b) ((a>b)?a:b) |
|
446 |
||
447 |
/************************************/ |
|
448 |
/** **/ |
|
449 |
/** Configure socket for Modbus **/ |
|
450 |
/** **/ |
|
451 |
/************************************/ |
|
452 |
||
453 |
||
454 |
static int configure_socket(int socket_id) { |
|
455 |
||
456 |
/* configure the socket */ |
|
457 |
/* Set it to be non-blocking. This is safe because we always use select() before reading from it! |
|
458 |
* It is also required for the connect() call. The default timeout in the TCP stack is much too long |
|
459 |
* (typically blocks for 128 s ??) when the connect does not succedd imediately! |
|
460 |
*/ |
|
461 |
if (fcntl(socket_id, F_SETFL, O_NONBLOCK) < 0) { |
|
462 |
#ifdef ERRMSG |
|
463 |
perror("fcntl()"); |
|
464 |
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'non-blocking' option.\n"); |
|
465 |
#endif |
|
466 |
return -1; |
|
467 |
} |
|
468 |
||
469 |
/* configure the socket */ |
|
12
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
470 |
{ |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
471 |
int optval; |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
472 |
socklen_t optlen = sizeof(optval); |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
473 |
optval = 1; |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
474 |
if(setsockopt(socket_id, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) { |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
475 |
#ifdef ERRMSG |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
476 |
perror("setsockopt()"); |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
477 |
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'KeepAlive' option.\n"); |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
478 |
#endif |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
479 |
return -1; |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
480 |
} |
16ea5cbbda4e
Add KeepAlive support for all TCP sockets.
Edouard Tisserant
parents:
10
diff
changeset
|
481 |
} |
0 | 482 |
/* set the TCP no delay flag. */ |
483 |
{int bool_opt = 1; |
|
484 |
if (setsockopt(socket_id, SOL_TCP, TCP_NODELAY, |
|
485 |
(const void *)&bool_opt, sizeof(bool_opt)) |
|
486 |
< 0) { |
|
487 |
#ifdef ERRMSG |
|
488 |
perror("setsockopt()"); |
|
489 |
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'TCP no delay' option.\n"); |
|
490 |
#endif |
|
491 |
return -1; |
|
492 |
} |
|
493 |
} |
|
494 |
||
495 |
/* set the IP low delay option. */ |
|
496 |
{int priority_opt = IPTOS_LOWDELAY; |
|
497 |
if (setsockopt(socket_id, SOL_IP, IP_TOS, |
|
498 |
(const void *)&priority_opt, sizeof(priority_opt)) |
|
499 |
< 0) { |
|
500 |
#ifdef ERRMSG |
|
501 |
perror("setsockopt()"); |
|
502 |
fprintf(stderr, ERRMSG_HEAD "Error configuring socket 'IP low delay' option.\n"); |
|
503 |
#endif |
|
504 |
return -1; |
|
505 |
} |
|
506 |
} |
|
507 |
||
508 |
#if 0 |
|
509 |
/* send buffer */ |
|
510 |
/* NOTE: For slave devices, that may be receiving multiple |
|
511 |
* requests before they have a chance to reply to the first, |
|
512 |
* it probably is a good idea to have a large receive buffer. |
|
513 |
* So it is best to leave it with the default configuration, as it is |
|
514 |
* larger than the largest Modbus TCP frame. |
|
515 |
* |
|
516 |
* For the send buffer, a smaller buffer should suffice. |
|
517 |
* However, it probably does not make sense to |
|
518 |
* waste time asking for a smaller buffer, since the larger |
|
519 |
* default buffer has already been allocated (the socket has already |
|
520 |
* been created!) |
|
521 |
* |
|
522 |
* We might just as well leave out the configuration of the socket |
|
523 |
* buffer size... |
|
524 |
*/ |
|
525 |
#define SOCK_BUF_SIZE 300 /* The size proposed in the Modbus TCP spec. */ |
|
526 |
{int sock_buf_size; |
|
527 |
sock_buf_size = SOCK_BUF_SIZE; |
|
528 |
if (setsockopt(socket_id, SOL_SOCKET, SO_SNDBUF, |
|
529 |
(const void *)&sock_buf_size, sizeof(sock_buf_size)) |
|
530 |
< 0) |
|
531 |
return -1; |
|
532 |
/* recv buffer */ |
|
533 |
sock_buf_size = SOCK_BUF_SIZE; |
|
534 |
if (setsockopt(socket_id, SOL_SOCKET, SO_RCVBUF, |
|
535 |
(const void *)&sock_buf_size, sizeof(sock_buf_size)) |
|
536 |
< 0) |
|
537 |
return -1; |
|
538 |
} |
|
539 |
#endif |
|
540 |
||
541 |
return 0; |
|
542 |
} |
|
543 |
||
544 |
||
545 |
/************************************/ |
|
546 |
/** **/ |
|
547 |
/** Connect socket to remote host **/ |
|
548 |
/** **/ |
|
549 |
/************************************/ |
|
550 |
||
551 |
/* This function will create a new socket, and connect it to a remote host... */ |
|
552 |
static inline int open_connection(int nd, const struct timespec *timeout) { |
|
553 |
int socket_id, con_res; |
|
554 |
||
555 |
#ifdef DEBUG |
|
556 |
printf("[%lu] open_connection(): called, nd = %d\n", pthread_self(), nd); |
|
557 |
#endif |
|
558 |
||
559 |
if (nd_table_.node[nd].fd >= 0) |
|
560 |
/* nd already connected) */ |
|
561 |
return nd_table_.node[nd].fd; |
|
562 |
||
563 |
if (nd_table_.node[nd].addr.sin_family != AF_INET) |
|
564 |
/* invalid remote address, or invalid nd */ |
|
565 |
return -1; |
|
566 |
||
567 |
/* lets try to connect... */ |
|
568 |
/* create the socket */ |
|
569 |
if ((socket_id = socket(PF_INET, DEF_TYPE, 0 /* protocol_num */)) < 0) { |
|
570 |
#ifdef DEBUG |
|
571 |
perror("socket()"); |
|
572 |
fprintf(stderr, "[%lu] Error creating socket\n", pthread_self()); |
|
573 |
#endif |
|
574 |
#ifdef ERRMSG |
|
575 |
perror("socket()"); |
|
576 |
fprintf(stderr, ERRMSG_HEAD "Error creating socket\n"); |
|
577 |
#endif |
|
578 |
return -1; |
|
579 |
} |
|
580 |
||
581 |
/* configure the socket - includes setting non-blocking option! */ |
|
582 |
if (configure_socket(socket_id) < 0) { |
|
583 |
close(socket_id); |
|
584 |
return -1; |
|
585 |
}; |
|
586 |
||
587 |
/* establish the connection to remote host */ |
|
588 |
con_res = connect(socket_id, |
|
589 |
(struct sockaddr *)&(nd_table_.node[nd].addr), |
|
590 |
sizeof(nd_table_.node[nd].addr)); |
|
591 |
||
592 |
/* The following condition is not strictly necessary |
|
593 |
* (we could let the code fall through) |
|
594 |
* but it does make the code easier to read/understand... |
|
595 |
*/ |
|
596 |
if (con_res >= 0) |
|
597 |
goto success_exit; /* connected succesfully on first try! */ |
|
598 |
||
599 |
if (con_res < 0) { |
|
600 |
if ((errno != EINPROGRESS) && (errno != EALREADY)) |
|
601 |
goto error_exit; /* error in connection request! */ |
|
602 |
||
603 |
/* connection request is ongoing */ |
|
604 |
/* EINPROGRESS -> first call to connect, EALREADY -> subsequent calls to connect */ |
|
605 |
/* Must wait for connect to complete at most 'timeout' seconds */ |
|
606 |
{fd_set fdset; |
|
607 |
int res, so_error; |
|
608 |
socklen_t len; |
|
609 |
struct timespec end_time, *et_ptr; |
|
610 |
||
611 |
et_ptr = NULL; |
|
612 |
if (timeout != NULL) { |
|
613 |
et_ptr = &end_time; |
|
614 |
*et_ptr = timespec_add_curtime(*timeout); |
|
615 |
} |
|
616 |
||
617 |
FD_ZERO(&fdset); |
|
618 |
FD_SET(socket_id, &fdset); |
|
619 |
||
620 |
res = my_select(socket_id+1, NULL, &fdset, et_ptr); |
|
621 |
if (res < 0) goto error_exit; /* error on call to select */ |
|
622 |
if (res == 0) goto error_exit; /* timeout */ |
|
623 |
/* (res > 0) -> connection attemt completed. May have been success or failure! */ |
|
624 |
||
625 |
len = sizeof(so_error); |
|
626 |
res = getsockopt(socket_id, SOL_SOCKET, SO_ERROR, &so_error, &len); |
|
627 |
if (res < 0) goto error_exit; /* error on call to getsockopt */ |
|
628 |
if (so_error != 0) goto error_exit; /* error on connection attempt */ |
|
629 |
goto success_exit; /* succesfully completed connection attempt! */ |
|
630 |
/* goto sucess_exit is not strcitly necessary - we could let the code fall through! */ |
|
631 |
} |
|
632 |
} |
|
633 |
||
634 |
success_exit: |
|
635 |
nd_table_.node[nd].fd = socket_id; |
|
636 |
/* Succesfully established connection => print a message next time we have error. */ |
|
637 |
nd_table_.node[nd].print_connect_error = 1; |
|
638 |
||
639 |
#ifdef DEBUG |
|
640 |
printf("[%lu] open_connection(): returning...\n", pthread_self()); |
|
641 |
#endif |
|
642 |
return socket_id; |
|
643 |
||
644 |
error_exit: |
|
645 |
#ifdef ERRMSG |
|
646 |
if (nd_table_.node[nd].print_connect_error > 0) { |
|
647 |
perror("connect()"); |
|
648 |
fprintf(stderr, ERRMSG_HEAD "Error establishing socket connection.\n"); |
|
649 |
/* do not print more error messages for this node... */ |
|
650 |
nd_table_.node[nd].print_connect_error = 0; |
|
651 |
} |
|
652 |
#endif |
|
653 |
close(socket_id); |
|
654 |
return -1; |
|
655 |
} |
|
656 |
||
657 |
||
658 |
/* This function will accept a new connection request, and attribute it to a new node... */ |
|
659 |
static inline int accept_connection(int nd) { |
|
660 |
int socket_id, new_nd; |
|
661 |
||
662 |
#ifdef DEBUG |
|
663 |
printf("[%lu] accept_connection(): called, nd = %d\n", pthread_self(), nd); |
|
664 |
#endif |
|
665 |
||
666 |
/* NOTE: We MUST accccept8) all connection requests, even if no new node is available. |
|
667 |
* => We first accept the connection request, and only later look for a node. |
|
668 |
* If no node is free/available for this new connections request, the |
|
669 |
* connection will be accepted and immediately closed. |
|
670 |
* Reason: |
|
671 |
* When the library is used for a Modbus/TCP server and no free node is |
|
672 |
* available, if we do not accept() all newly arrived connection requests |
|
673 |
* we would enter an infinite loop calling |
|
674 |
* - select() (in modbus_tcp_read()) |
|
675 |
* - and accept_connection(). |
|
676 |
* Note that select() will continue to return immediately if the |
|
677 |
* connection request is not accept()ted! |
|
678 |
*/ |
|
679 |
/* lets accept new connection request... */ |
|
680 |
if ((socket_id = accept(nd_table_.node[nd].fd, NULL, NULL)) < 0) { |
|
681 |
#ifdef ERRMSG |
|
682 |
perror("accept()"); |
|
683 |
fprintf(stderr, ERRMSG_HEAD "Error while waiting for connection request from new client\n"); |
|
684 |
#endif |
|
685 |
/* error establishing new connection... */ |
|
686 |
return -1; |
|
687 |
} |
|
688 |
||
689 |
/* find a free node */ |
|
690 |
if ((new_nd = nd_table_get_free_node(&nd_table_, MB_SLAVE_NODE)) < 0) { |
|
691 |
/* no available free nodes for the new connection... */ |
|
692 |
close(socket_id); |
|
693 |
return -1; |
|
694 |
} |
|
695 |
||
696 |
/* configure the socket - includes setting the non-blocking option! */ |
|
697 |
if (configure_socket(socket_id) < 0) { |
|
698 |
nd_table_close_node(&nd_table_, new_nd); /* first free up the un-used node. */ |
|
699 |
close(socket_id); |
|
700 |
return -1; |
|
701 |
} |
|
702 |
||
703 |
/* set up the node entry and update the fd sets */ |
|
704 |
nd_table_.node[new_nd].fd = socket_id; |
|
705 |
nd_table_.node[new_nd].listen_node = nd; |
|
706 |
||
707 |
#ifdef DEBUG |
|
708 |
printf("[%lu] accept_connection(): returning new_nd = %d\n", pthread_self(), new_nd); |
|
709 |
#endif |
|
710 |
return new_nd; |
|
711 |
} |
|
712 |
||
713 |
||
714 |
static inline void close_connection(int nd) { |
|
715 |
if (nd_table_.node[nd].fd >= 0) { |
|
716 |
/* disconnect the tcp connection */ |
|
717 |
shutdown(nd_table_.node[nd].fd, SHUT_RDWR); |
|
718 |
#ifdef ERRMSG |
|
719 |
int res = |
|
720 |
#endif |
|
721 |
close(nd_table_.node[nd].fd); |
|
722 |
#ifdef ERRMSG |
|
723 |
if (res < 0) { |
|
724 |
perror("close()"); |
|
725 |
fprintf(stderr, ERRMSG_HEAD "Error closing socket\n"); |
|
726 |
} |
|
727 |
#endif |
|
728 |
nd_table_.node[nd].fd = -1; |
|
729 |
} |
|
730 |
||
731 |
if (nd_table_.node[nd].node_type == MB_SLAVE_NODE) { |
|
732 |
/* If it is a slave node, we will not be receiving any more data over this disconnected node, |
|
733 |
* (MB_SLAVE_NODE do not get re-connected!), so we free the node... |
|
734 |
*/ |
|
735 |
nd_table_close_node(&nd_table_, nd); |
|
736 |
} |
|
737 |
} |
|
738 |
||
739 |
||
740 |
||
741 |
/************************************/ |
|
742 |
/** **/ |
|
743 |
/** Data format conversion **/ |
|
744 |
/** **/ |
|
745 |
/************************************/ |
|
746 |
||
747 |
/* |
|
748 |
* Functions to convert u16 variables |
|
749 |
* between network and host byte order |
|
750 |
* |
|
751 |
* NOTE: Modbus uses MSByte first, just like |
|
752 |
* tcp/ip, so we use the htons() and |
|
753 |
* ntoh() functions to guarantee |
|
754 |
* code portability. |
|
755 |
*/ |
|
756 |
||
757 |
static inline u16 mb_hton(u16 h_value) { |
|
758 |
/* return h_value; */ |
|
759 |
return htons(h_value); |
|
760 |
} |
|
761 |
||
762 |
static inline u16 mb_ntoh(u16 m_value) { |
|
763 |
/* return m_value; */ |
|
764 |
return ntohs(m_value); |
|
765 |
} |
|
766 |
||
767 |
static inline u8 msb(u16 value) { |
|
768 |
/* return Most Significant Byte of value; */ |
|
769 |
return (value >> 8) & 0xFF; |
|
770 |
} |
|
771 |
||
772 |
static inline u8 lsb(u16 value) { |
|
773 |
/* return Least Significant Byte of value; */ |
|
774 |
return value & 0xFF; |
|
775 |
} |
|
776 |
||
777 |
#define u16_v(char_ptr) (*((u16 *)(&(char_ptr)))) |
|
778 |
||
779 |
||
780 |
/************************************/ |
|
781 |
/** **/ |
|
782 |
/** Build/Check a frame header **/ |
|
783 |
/** **/ |
|
784 |
/************************************/ |
|
785 |
||
786 |
/* A modbus TCP frame header has 6 bytes... |
|
787 |
* header[0-1] -> transaction id |
|
788 |
* header[2-3] -> must be 0 |
|
789 |
* header[4-5] -> frame data length (must be <= 255) |
|
790 |
*/ |
|
791 |
#if TCP_HEADER_LENGTH < 6 |
|
792 |
#error This code assumes a header size of 6 bytes, but TCP_HEADER_LENGTH < 6 |
|
793 |
#endif |
|
794 |
||
795 |
static inline void build_header(u8 *header, |
|
796 |
u16 transaction_id, |
|
797 |
u16 byte_count) |
|
798 |
{ |
|
799 |
u16_v(header[0]) = mb_hton(transaction_id); |
|
800 |
header[2] = 0; |
|
801 |
header[3] = 0; |
|
802 |
u16_v(header[4]) = mb_hton(byte_count); |
|
803 |
} |
|
804 |
||
805 |
||
806 |
static inline int check_header(u8 *header, |
|
807 |
u16 *transaction_id, |
|
808 |
u16 *byte_count) |
|
809 |
{ |
|
810 |
if ((header[2] != 0) || (header[3] != 0)) |
|
811 |
return -1; |
|
812 |
||
813 |
*transaction_id = mb_ntoh(*(u16 *)(header + 0)); |
|
814 |
*byte_count = mb_ntoh(*(u16 *)(header + 4)); |
|
815 |
||
816 |
if (*byte_count > MAX_L2_FRAME_LENGTH) |
|
817 |
return -1; |
|
818 |
||
819 |
return 0; |
|
820 |
} |
|
821 |
||
822 |
||
823 |
||
824 |
||
825 |
||
826 |
/**************************************************************/ |
|
827 |
/**************************************************************/ |
|
828 |
/**** ****/ |
|
829 |
/**** ****/ |
|
830 |
/**** Sending of Modbus TCP Frames ****/ |
|
831 |
/**** ****/ |
|
832 |
/**** ****/ |
|
833 |
/**************************************************************/ |
|
834 |
/**************************************************************/ |
|
835 |
||
836 |
// pthread_mutex_t sendmsg_mutex = PTHREAD_MUTEX_INITIALIZER; |
|
837 |
||
838 |
/* NOTE: this function MUST be thread safe!! */ |
|
839 |
int modbus_tcp_write(int nd, /* node descriptor */ |
|
840 |
u8 *data, |
|
841 |
size_t data_length, |
|
842 |
u16 transaction_id, |
|
843 |
const struct timespec *transmit_timeout |
|
844 |
) |
|
845 |
{ |
|
846 |
#define data_vector_size 2 |
|
847 |
||
848 |
u8 header[TCP_HEADER_LENGTH]; |
|
849 |
struct iovec data_vector[data_vector_size] = { |
|
850 |
{(void *)header, TCP_HEADER_LENGTH}, |
|
851 |
{NULL, 0}}; |
|
852 |
struct msghdr msg = {NULL, 0, data_vector, data_vector_size, NULL, 0, 0}; |
|
853 |
int res, bytes_sent; |
|
854 |
||
855 |
#ifdef DEBUG |
|
856 |
printf("[%lu] modbus_tcp_write(): called... nd=%d\n", pthread_self(), nd); |
|
857 |
#endif |
|
858 |
||
859 |
if ((nd >= nd_table_.node_count) || (nd < 0)) |
|
860 |
/* invalid node descriptor... */ |
|
861 |
return -1; |
|
862 |
||
863 |
#ifdef DEBUG |
|
864 |
// printf("[%lu] locking mutex...\n", pthread_self()); |
|
865 |
#endif |
|
866 |
// while (pthread_mutex_lock(&sendmsg_mutex) != 0); |
|
867 |
||
868 |
/************************* |
|
869 |
* prepare the header... * |
|
870 |
*************************/ |
|
871 |
build_header(header, transaction_id, data_length); |
|
872 |
#ifdef DEBUG |
|
873 |
/* Print the hex value of each character that is about to be |
|
874 |
* sent over the bus. |
|
875 |
*/ |
|
876 |
{ int i; |
|
877 |
printf("modbus_tcp_write(): sending data...\n"); |
|
878 |
for(i = 0; i < TCP_HEADER_LENGTH; i++) |
|
879 |
printf("[0x%2X]", header[i]); |
|
880 |
for(i = 0; i < data_length; i++) |
|
881 |
printf("[0x%2X]", data[i]); |
|
882 |
printf("\n"); |
|
883 |
} |
|
884 |
#endif |
|
885 |
||
886 |
/****************************************** |
|
887 |
* do we need to re-establish connection? * |
|
888 |
******************************************/ |
|
889 |
if (open_connection(nd, transmit_timeout) < 0) { |
|
890 |
#ifdef DEBUG |
|
891 |
fprintf(stderr, "[%lu] modbus_tcp_write(): could not establish connection...\n", pthread_self()); |
|
892 |
#endif |
|
893 |
#ifdef ERRMSG |
|
894 |
fprintf(stderr, ERRMSG_HEAD "could not establish connection...\n"); |
|
895 |
#endif |
|
896 |
return -1; |
|
897 |
} |
|
898 |
||
899 |
/********************** |
|
900 |
* write to output... * |
|
901 |
**********************/ |
|
902 |
/* TWO ALTERNATIVE IMPLEMENTATIONS !!! */ |
|
903 |
#if 0 |
|
904 |
/* write header */ |
|
905 |
bytes_sent = 0; |
|
906 |
while (1) { |
|
907 |
res = write(nd_table_.node[nd].fd, header+bytes_sent, TCP_HEADER_LENGTH-bytes_sent); |
|
908 |
if (res < 0) { |
|
909 |
if ((errno != EAGAIN ) && (errno != EINTR )) { |
|
910 |
/* error sending message... */ |
|
911 |
close_connection(nd); |
|
912 |
return -1; |
|
913 |
} else { |
|
914 |
continue; |
|
915 |
} |
|
916 |
} else { |
|
917 |
/* res >= 0 */ |
|
918 |
bytes_sent += res; |
|
919 |
if (bytes_sent >= TCP_HEADER_LENGTH) { |
|
920 |
break; |
|
921 |
} |
|
922 |
} |
|
923 |
} |
|
924 |
||
925 |
/* write data */ |
|
926 |
bytes_sent = 0; |
|
927 |
while (1) { |
|
928 |
res = write(nd_table_.node[nd].fd, data+bytes_sent, data_length-bytes_sent); |
|
929 |
if (res < 0) { |
|
930 |
if ((errno != EAGAIN ) && (errno != EINTR )) { |
|
931 |
/* error sending message... */ |
|
932 |
close_connection(nd); |
|
933 |
return -1; |
|
934 |
} else { |
|
935 |
continue; |
|
936 |
} |
|
937 |
} else { |
|
938 |
/* res >= 0 */ |
|
939 |
bytes_sent += res; |
|
940 |
if (bytes_sent >= data_length) { |
|
941 |
/* query succesfully sent! */ |
|
942 |
#ifdef DEBUG |
|
943 |
printf("[%lu] modbus_tcp_write(): sent %d bytes\n", pthread_self(), TCP_HEADER_LENGTH+data_length); |
|
944 |
#endif |
|
945 |
return data_length; |
|
946 |
} |
|
947 |
} |
|
948 |
} |
|
949 |
||
950 |
/********************** |
|
951 |
* write to output... * |
|
952 |
**********************/ |
|
953 |
#else |
|
954 |
/* We are optimising for the most likely case, and in doing that |
|
955 |
* we are making the least likely case have worse behaviour! |
|
956 |
* Read on for an explanation... |
|
957 |
* |
|
958 |
* - The optimised behaviour for the most likely case: |
|
959 |
* We have set the NO_DELAY flag on the socket, so the IP datagram |
|
960 |
* is not delayed and is therefore sent as soon as any data is written to |
|
961 |
* the socket. |
|
962 |
* In order to send the whole message in a single IP datagram, we have to |
|
963 |
* write both the the header and the data with a single call to write() |
|
964 |
* In order to not to have to copy the data around just to add the |
|
965 |
* message header, we use sendmsg() instead of write()! |
|
966 |
* |
|
967 |
* - The worse behaviour for the least likely case: |
|
968 |
* If for some reason only part of the data is sent with the first call to |
|
969 |
* write(), a datagram is sent right away, and the subsequent data will |
|
970 |
* be sent in another datagram. :-( |
|
971 |
*/ |
|
972 |
/* NOTE: since snedmsg() is not thread safe, we use a mutex to protect access to this function... */ |
|
973 |
||
974 |
data_vector[data_vector_size - 1].iov_base = data; |
|
975 |
data_vector[data_vector_size - 1].iov_len = data_length; |
|
976 |
data_vector[ 0].iov_base = header; |
|
977 |
data_vector[ 0].iov_len = TCP_HEADER_LENGTH; |
|
978 |
bytes_sent = 0; |
|
979 |
while (1) { |
|
980 |
int sendmsg_errno; |
|
981 |
/* Please see the comment just above the main loop!! */ |
|
982 |
res = sendmsg(nd_table_.node[nd].fd, &msg, 0); |
|
983 |
sendmsg_errno = errno; |
|
984 |
if (res < 0) { |
|
985 |
if ((sendmsg_errno != EAGAIN ) && (sendmsg_errno != EINTR )) { |
|
986 |
/* error sending message... */ |
|
987 |
close_connection(nd); |
|
988 |
return -1; |
|
989 |
} else { |
|
990 |
continue; |
|
991 |
} |
|
992 |
} else { |
|
993 |
/* res >= 0 */ |
|
994 |
bytes_sent += res; |
|
995 |
if (bytes_sent >= data_length + TCP_HEADER_LENGTH) { |
|
996 |
/* query succesfully sent! */ |
|
997 |
#ifdef DEBUG |
|
998 |
printf("[%lu] modbus_tcp_write(): sent %d bytes\n", pthread_self(), bytes_sent); |
|
999 |
#endif |
|
1000 |
// pthread_mutex_unlock(&sendmsg_mutex); |
|
1001 |
#ifdef DEBUG |
|
1002 |
// printf("[%lu] unlocked mutex...\n", pthread_self()); |
|
1003 |
#endif |
|
1004 |
return data_length; |
|
1005 |
} |
|
1006 |
||
1007 |
/* adjust the data_vector... */ |
|
1008 |
if (res < data_vector[0].iov_len) { |
|
1009 |
u8* tmp = data_vector[0].iov_base; |
|
1010 |
tmp += res; |
|
1011 |
data_vector[0].iov_len -= res; |
|
1012 |
data_vector[0].iov_base = tmp; |
|
1013 |
} else { |
|
1014 |
u8* tmp = data_vector[1].iov_base; |
|
1015 |
tmp += res; |
|
1016 |
res -= data_vector[0].iov_len; |
|
1017 |
data_vector[0].iov_len = 0; |
|
1018 |
data_vector[1].iov_len -= res; |
|
1019 |
data_vector[1].iov_base = tmp; |
|
1020 |
} |
|
1021 |
} |
|
1022 |
} /* while (1) */ |
|
1023 |
#endif |
|
1024 |
||
1025 |
/* humour the compiler... */ |
|
1026 |
// pthread_mutex_unlock(&sendmsg_mutex); |
|
1027 |
#ifdef DEBUG |
|
1028 |
// printf("[%lu] unlocked mutex...\n", pthread_self()); |
|
1029 |
#endif |
|
1030 |
return -1; |
|
1031 |
} |
|
1032 |
||
1033 |
||
1034 |
||
1035 |
/**************************************************************/ |
|
1036 |
/**************************************************************/ |
|
1037 |
/**** ****/ |
|
1038 |
/**** ****/ |
|
1039 |
/**** Receiving Modbus TCP Frames ****/ |
|
1040 |
/**** ****/ |
|
1041 |
/**** ****/ |
|
1042 |
/**************************************************************/ |
|
1043 |
/**************************************************************/ |
|
1044 |
||
1045 |
||
1046 |
/* A helper function to modbus_tcp_read() |
|
1047 |
* |
|
1048 |
* WARNING: The semantics of this function are not what you would expect! |
|
1049 |
* |
|
1050 |
* if (data_already_available != 0) |
|
1051 |
* It assumes that select() has already been called before |
|
1052 |
* this function got called, and we are therefore guaranteed |
|
1053 |
* to have at least one byte to read off the socket (the fd). |
|
1054 |
* |
|
1055 |
* if (data_already_available == 0) |
|
1056 |
* it starts off by calling select()! |
|
1057 |
* |
|
1058 |
* |
|
1059 |
* NOTE: Ususal select semantics for (a: end_time == NULL) and |
|
1060 |
* (b: *end_time == 0) also apply. |
|
1061 |
* |
|
1062 |
* (a) Indefinite timeout |
|
1063 |
* (b) Try once, and and quit if no data available. |
|
1064 |
*/ |
|
1065 |
/* RETURNS: number of bytes read |
|
1066 |
* -1 read error! |
|
1067 |
* -2 timeout |
|
1068 |
*/ |
|
1069 |
static int read_bytes(int fd, |
|
1070 |
u8 *data, |
|
1071 |
int max_data_count, |
|
1072 |
const struct timespec *end_time, |
|
1073 |
int data_already_available) |
|
1074 |
{ |
|
1075 |
fd_set rfds; |
|
1076 |
int res, data_count; |
|
1077 |
||
1078 |
data_count = 0; |
|
1079 |
||
1080 |
while (data_count < max_data_count) { |
|
1081 |
/*============================* |
|
1082 |
* wait for data availability * |
|
1083 |
*============================*/ |
|
1084 |
if (data_already_available == 0) { |
|
1085 |
int sel_res; |
|
1086 |
FD_ZERO(&rfds); |
|
1087 |
FD_SET(fd, &rfds); |
|
1088 |
sel_res = my_select(fd + 1, &rfds, NULL, end_time); |
|
1089 |
if (sel_res < 0) |
|
1090 |
return -1; |
|
1091 |
if (sel_res == 0) |
|
1092 |
/* timeout! */ |
|
1093 |
return -2; |
|
1094 |
} |
|
1095 |
||
1096 |
/*============================* |
|
1097 |
* read the available data... * |
|
1098 |
*============================*/ |
|
1099 |
res = read(fd, data + data_count, max_data_count - data_count); |
|
1100 |
if (res == 0) { |
|
1101 |
/* We are guaranteed to have data to read off the fd since we called |
|
1102 |
* select(), but read() returned 0 bytes. |
|
1103 |
* This means that the remote process has closed down the connection, |
|
1104 |
* so we return 0. |
|
1105 |
*/ |
|
1106 |
return 0; |
|
1107 |
} |
|
1108 |
||
1109 |
if (res < 0) { |
|
1110 |
if (errno != EINTR) |
|
1111 |
return -1; |
|
1112 |
else |
|
1113 |
res = 0; |
|
1114 |
} |
|
1115 |
#ifdef DEBUG |
|
1116 |
{/* display the hex code of each character received */ |
|
1117 |
int i; |
|
1118 |
for (i=0; i < res; i++) |
|
1119 |
printf("<0x%2X>", *(data + data_count + i)); |
|
1120 |
} |
|
1121 |
#endif |
|
1122 |
data_count += res; |
|
1123 |
data_already_available = 0; |
|
1124 |
} /* while ()*/ |
|
1125 |
||
1126 |
/* data read succesfully... */ |
|
1127 |
return data_count; |
|
1128 |
} |
|
1129 |
||
1130 |
||
1131 |
||
1132 |
/***************************************/ |
|
1133 |
/** **/ |
|
1134 |
/** Read a Modbus TCP frame **/ |
|
1135 |
/** off a single identified node. **/ |
|
1136 |
/** **/ |
|
1137 |
/***************************************/ |
|
1138 |
||
1139 |
/* This private function will read a Modbus TCP frame off a single identified node |
|
1140 |
* that we know before hand that has data ready to be read off it. The data may or may not be |
|
1141 |
* a valid Modbus TCP frame. It is up to this function to figure that out. |
|
1142 |
*/ |
|
1143 |
/* NOTES: |
|
1144 |
* - We re-use the recv_buf_ to load the frame header, so we have to make |
|
1145 |
* sure that the buffer is large enough to take it... |
|
1146 |
*/ |
|
1147 |
/* RETURNS: number of bytes read |
|
1148 |
* -1 on read from file/node error |
|
1149 |
* -2 on timeout |
|
1150 |
*/ |
|
1151 |
#if RECV_BUFFER_SIZE < TCP_HEADER_LENGTH |
|
1152 |
#error The receive buffer is smaller than the frame header length. |
|
1153 |
#endif |
|
1154 |
||
1155 |
static int modbus_tcp_read_frame(int nd, |
|
1156 |
u16 *transaction_id, |
|
1157 |
struct timespec *ts_ptr) { |
|
1158 |
int fd, res; |
|
1159 |
u16 frame_length; |
|
1160 |
||
1161 |
#ifdef DEBUG |
|
1162 |
printf("[%lu] modbus_tcp_read_frame(): reading off nd=%d\n", pthread_self(), nd); |
|
1163 |
#endif |
|
1164 |
/*=========================* |
|
1165 |
* read a Modbus TCP frame * |
|
1166 |
*=========================*/ |
|
1167 |
/* assume error... */ |
|
1168 |
fd = nd_table_.node[nd].fd; |
|
1169 |
||
1170 |
/*-------------* |
|
1171 |
* read header * |
|
1172 |
*-------------*/ |
|
1173 |
if ((res = read_bytes(fd, nd_table_.node[nd].recv_buf, TCP_HEADER_LENGTH, ts_ptr, 1)) != TCP_HEADER_LENGTH) { |
|
1174 |
#ifdef DEBUG |
|
1175 |
printf("[%lu] modbus_tcp_read_frame(): frame with insuficient bytes for a valid header...\n", pthread_self()); |
|
1176 |
#endif |
|
1177 |
if (res < 0) return res; |
|
1178 |
return -1; |
|
1179 |
} |
|
1180 |
||
1181 |
/* let's check for header consistency... */ |
|
1182 |
if (check_header(nd_table_.node[nd].recv_buf, transaction_id, &frame_length) < 0) { |
|
1183 |
#ifdef DEBUG |
|
1184 |
printf("[%lu] modbus_tcp_read_frame(): frame with non valid header...\n", pthread_self()); |
|
1185 |
#endif |
|
1186 |
return -1; |
|
1187 |
} |
|
1188 |
||
1189 |
/*-----------* |
|
1190 |
* read data * |
|
1191 |
*-----------*/ |
|
1192 |
if ((res = read_bytes(fd, nd_table_.node[nd].recv_buf, frame_length, ts_ptr, 0)) != frame_length) { |
|
1193 |
#ifdef DEBUG |
|
1194 |
printf("[%lu] modbus_tcp_read_frame(): frame with non valid frame length...\n", pthread_self()); |
|
1195 |
#endif |
|
1196 |
if (res < 0) return res; |
|
1197 |
return -1; |
|
1198 |
} |
|
1199 |
||
1200 |
/* frame received succesfully... */ |
|
1201 |
#ifdef DEBUG |
|
1202 |
printf("\n"); |
|
1203 |
#endif |
|
1204 |
return frame_length; |
|
1205 |
} |
|
1206 |
||
1207 |
||
1208 |
||
1209 |
||
1210 |
/***************************************/ |
|
1211 |
/** **/ |
|
1212 |
/** Read a Modbus TCP frame **/ |
|
1213 |
/** OR Accept connection requests **/ |
|
1214 |
/** off possibly multiple node... **/ |
|
1215 |
/** **/ |
|
1216 |
/***************************************/ |
|
1217 |
||
1218 |
/* The public function that reads a valid modbus frame. |
|
1219 |
* The frame is read from...: |
|
1220 |
* - if (nd >= 0) and (nd is of type MB_MASTER_NODE or MB_SLAVE_NODE) |
|
1221 |
* The frame is read from the node descriptor nd |
|
1222 |
* - if (nd >= 0) and (nd is of type MB_LISTEN_NODE) |
|
1223 |
* The frame is read from the all node descriptors of type MB_SLAVE_NODE that were |
|
1224 |
* opened as a consequence of a connection request to the nd slave. |
|
1225 |
* In this case, new connection requests to nd will also be accepted! |
|
1226 |
* - if (nd == -1) |
|
1227 |
* The frame is read from any valid and initialised node descriptor. |
|
1228 |
* In this case, new connection requests to any nd of type MB_LISTEN_NODE will also be accepted! |
|
1229 |
* In this case, the node where the data is eventually read from is returned in *nd. |
|
1230 |
* |
|
1231 |
* The send_data and send_length parameters are ignored... |
|
1232 |
* (However, these parameters must stay in order to keep the function |
|
1233 |
* interface identical to the ASCII and RTU versons!) |
|
1234 |
* |
|
1235 |
* return value: The length (in bytes) of the valid frame, |
|
1236 |
* -1 on error |
|
1237 |
* |
|
1238 |
* NOTE: Ususal select semantics for (a: recv_timeout == NULL) and |
|
1239 |
* (b: *recv_timeout == 0) also apply. |
|
1240 |
* |
|
1241 |
* (a) Indefinite timeout |
|
1242 |
* (b) Try once, and and quit if no data available. |
|
1243 |
*/ |
|
1244 |
||
1245 |
/* RETURNS: number of bytes read |
|
1246 |
* -1 on read from file/node error |
|
1247 |
* -2 on timeout |
|
1248 |
*/ |
|
1249 |
int modbus_tcp_read(int *nd, /* node descriptor */ |
|
1250 |
u8 **recv_data_ptr, |
|
1251 |
u16 *transaction_id, |
|
1252 |
const u8 *send_data, /* ignored ! */ |
|
1253 |
int send_length, /* ignored ! */ |
|
1254 |
const struct timespec *recv_timeout) { |
|
1255 |
||
1256 |
struct timespec end_time, *ts_ptr; |
|
1257 |
u8 *local_recv_data_ptr; |
|
1258 |
u16 local_transaction_id = 0; |
|
1259 |
||
1260 |
#ifdef DEBUG |
|
1261 |
printf("[%lu] modbus_tcp_read(): called... nd=%d\n", pthread_self(), *nd); |
|
1262 |
#endif |
|
1263 |
||
1264 |
if (nd == NULL) |
|
1265 |
return -1; |
|
1266 |
||
1267 |
if (*nd >= nd_table_.node_count) |
|
1268 |
/* invalid *nd */ |
|
1269 |
/* remember that *nd < 0 is valid!! */ |
|
1270 |
return -1; |
|
1271 |
||
1272 |
if (recv_data_ptr == NULL) |
|
1273 |
recv_data_ptr = &local_recv_data_ptr; |
|
1274 |
if (transaction_id == NULL) |
|
1275 |
transaction_id = &local_transaction_id; |
|
1276 |
||
1277 |
/* We will potentially call read() multiple times to read in a single frame. |
|
1278 |
* We therefore determine the absolute time_out, and use this as a parameter |
|
1279 |
* for each call to read_bytes() instead of using a relative timeout. |
|
1280 |
* |
|
1281 |
* NOTE: see also the timeout related comment in the read_bytes() function! |
|
1282 |
*/ |
|
1283 |
ts_ptr = NULL; |
|
1284 |
if (recv_timeout != NULL) { |
|
1285 |
ts_ptr = &end_time; |
|
1286 |
*ts_ptr = timespec_add_curtime(*recv_timeout); |
|
1287 |
} |
|
1288 |
||
1289 |
/* If we must read off a single node... */ |
|
1290 |
if (*nd >= 0) |
|
1291 |
/* but the node does not have a valid fd */ |
|
1292 |
if ((nd_table_.node[*nd].node_type == MB_FREE_NODE) || |
|
1293 |
(nd_table_.node[*nd].fd < 0)) |
|
1294 |
/* then we return an error... */ |
|
1295 |
return -1; |
|
1296 |
||
1297 |
/* We will loop forever... |
|
1298 |
* We jump out of the loop and return from the function as soon as: |
|
1299 |
* - we receive a valid modbus message; |
|
1300 |
* OR |
|
1301 |
* - we time out. |
|
1302 |
* |
|
1303 |
* NOTE: This loop will close connections through which we receive invalid frames. |
|
1304 |
* This means that the set of nodes through which we may receive data may change with each |
|
1305 |
* loop iteration. => We need to re-calculate the fds in each loop iteration! |
|
1306 |
*/ |
|
1307 |
||
1308 |
while (1) { |
|
1309 |
int nd_count, fd_high; |
|
1310 |
fd_set rfds; |
|
1311 |
||
1312 |
/* We prepare our fd sets here so we can later call select() */ |
|
1313 |
FD_ZERO(&rfds); |
|
1314 |
fd_high = -1; |
|
1315 |
||
1316 |
for (nd_count = 0; nd_count < nd_table_.node_count; nd_count++) { |
|
1317 |
if (nd_table_.node[nd_count].node_type != MB_FREE_NODE) |
|
1318 |
{ |
|
1319 |
if ((*nd < 0) // we select from all nodes |
|
1320 |
|| (*nd == nd_count) // we select from this specific node |
|
1321 |
// we are listening on a MB_LISTEN_NODE, so we must also receive requests sent to slave nodes |
|
1322 |
// whose connection requests arrived through this MB_LISTEN_NDODE |
|
1323 |
|| ((nd_table_.node[nd_count].node_type == MB_SLAVE_NODE) && (nd_table_.node[nd_count].listen_node == *nd))) |
|
1324 |
{ |
|
1325 |
/* check if valid fd */ |
|
1326 |
if (nd_table_.node[nd_count].fd >= 0) { |
|
1327 |
/* Add the descriptor to the fd set... */ |
|
1328 |
FD_SET(nd_table_.node[nd_count].fd, &rfds); |
|
1329 |
fd_high = max(fd_high, nd_table_.node[nd_count].fd); |
|
1330 |
} |
|
1331 |
} |
|
1332 |
} |
|
1333 |
} /* for(;;) */ |
|
1334 |
||
1335 |
#ifdef DEBUG |
|
1336 |
printf("[%lu] modbus_tcp_read(): while(1) looping. fd_high = %d, nd=%d\n", pthread_self(), fd_high, *nd); |
|
1337 |
#endif |
|
1338 |
||
1339 |
if (fd_high == -1) |
|
1340 |
/* we will not be reading from any node! */ |
|
1341 |
return -1; |
|
1342 |
||
1343 |
/* We now call select and wait for activity on the nodes we are listening to */ |
|
1344 |
{ int sel_res = my_select(fd_high + 1, &rfds, NULL, ts_ptr); |
|
1345 |
if (sel_res < 0) |
|
1346 |
return -1; |
|
1347 |
if (sel_res == 0) |
|
1348 |
/* timeout! */ |
|
1349 |
return -2; |
|
1350 |
} |
|
1351 |
||
1352 |
/* figure out which nd is ready to be read... */ |
|
1353 |
for (nd_count = 0; nd_count < nd_table_.node_count; nd_count++) { |
|
1354 |
if ((nd_table_.node[nd_count].node_type != MB_FREE_NODE) && |
|
1355 |
(nd_table_.node[nd_count].fd >= 0)) { |
|
1356 |
if (FD_ISSET(nd_table_.node[nd_count].fd, &rfds)) { |
|
1357 |
/* Found the node descriptor... */ |
|
1358 |
#ifdef DEBUG |
|
1359 |
printf("[%lu] modbus_tcp_read(): my_select() returned due to activity on node nd=%d\n", pthread_self(), nd_count); |
|
1360 |
#endif |
|
1361 |
if (nd_table_.node[nd_count].node_type == MB_LISTEN_NODE) { |
|
1362 |
/* We must accept a new connection... |
|
1363 |
* No need to check for errors. |
|
1364 |
* If one occurs, there is nothing we can do... |
|
1365 |
*/ |
|
1366 |
accept_connection(nd_count); |
|
1367 |
} else { |
|
1368 |
/* it is a MB_SLAVE_NODE or a MB_MASTER_NODE */ |
|
1369 |
/* We will read a frame off this nd */ |
|
1370 |
int res; |
|
1371 |
res = modbus_tcp_read_frame(nd_count, transaction_id, ts_ptr); |
|
1372 |
if (res > 0) { |
|
1373 |
*nd = nd_count; |
|
1374 |
*recv_data_ptr = nd_table_.node[nd_count].recv_buf; |
|
1375 |
return res; |
|
1376 |
} |
|
1377 |
if (res < 0) { |
|
1378 |
/* We had an error reading the frame... |
|
1379 |
* We handle it by closing the connection, as specified by |
|
1380 |
* the modbus TCP protocol! |
|
1381 |
* |
|
1382 |
* NOTE: The error may have been a timeout, which means this function should return immediately. |
|
1383 |
* However, in this case we let the execution loop once again |
|
1384 |
* in the while(1) loop. My_select() will be called again |
|
1385 |
* and the timeout detected. The timeout error code (-2) |
|
1386 |
* will then be returned correctly! |
|
1387 |
*/ |
|
1388 |
#ifdef DEBUG |
|
1389 |
printf("[%lu] modbus_tcp_read(): error reading frame. Closing connection...\n", pthread_self()); |
|
1390 |
#endif |
|
1391 |
/* We close the socket... */ |
|
1392 |
close_connection(nd_count); |
|
1393 |
} |
|
1394 |
} |
|
1395 |
/* we have found the node descriptor, so let's jump out of the for(;;) loop */ |
|
1396 |
break; |
|
1397 |
} |
|
1398 |
} |
|
1399 |
} /* for(;;) */ |
|
1400 |
||
1401 |
/* We were unsuccesfull reading a frame, so we try again... */ |
|
1402 |
} /* while (1) */ |
|
1403 |
||
1404 |
/* humour the compiler... */ |
|
1405 |
return -1; |
|
1406 |
} |
|
1407 |
||
1408 |
||
1409 |
||
1410 |
||
1411 |
||
1412 |
/**************************************************************/ |
|
1413 |
/**************************************************************/ |
|
1414 |
/**** ****/ |
|
1415 |
/**** ****/ |
|
1416 |
/**** Initialising and Shutting Down Library ****/ |
|
1417 |
/**** ****/ |
|
1418 |
/**** ****/ |
|
1419 |
/**************************************************************/ |
|
1420 |
/**************************************************************/ |
|
1421 |
||
1422 |
||
1423 |
/* Ugly hack... |
|
1424 |
* Beremiz will be calling modbus_tcp_init() multiple times (through modbus_init() ) |
|
1425 |
* (once for each plugin instance) |
|
1426 |
* It will also be calling modbus_tcp_done() the same number of times |
|
1427 |
* We only want to really shutdown the library the last time it is called. |
|
1428 |
* We therefore keep a counter of how many times modbus_tcp_init() is called, |
|
1429 |
* and decrement it in modbus_tcp_done() |
|
1430 |
*/ |
|
1431 |
int modbus_tcp_init_counter = 0; |
|
1432 |
||
1433 |
/******************************/ |
|
1434 |
/** **/ |
|
1435 |
/** Load Default Values **/ |
|
1436 |
/** **/ |
|
1437 |
/******************************/ |
|
1438 |
||
1439 |
static void set_defaults(const char **service) { |
|
1440 |
/* Set the default values, if required... */ |
|
1441 |
if (*service == NULL) |
|
1442 |
*service = DEF_SERVICE; |
|
1443 |
} |
|
1444 |
||
1445 |
||
1446 |
/******************************/ |
|
1447 |
/** **/ |
|
1448 |
/** Initialise Library **/ |
|
1449 |
/** **/ |
|
1450 |
/******************************/ |
|
1451 |
/* returns the number of nodes succesfully initialised... |
|
1452 |
* returns -1 on error. |
|
1453 |
*/ |
|
1454 |
int modbus_tcp_init(int nd_count, |
|
1455 |
optimization_t opt /* ignored... */, |
|
1456 |
int *extra_bytes) { |
|
1457 |
#ifdef DEBUG |
|
1458 |
printf("[%lu] modbus_tcp_init(): called...\n", pthread_self()); |
|
1459 |
printf("[%lu] creating %d nodes:\n", pthread_self(), nd_count); |
|
1460 |
#endif |
|
1461 |
||
1462 |
modbus_tcp_init_counter++; |
|
1463 |
||
1464 |
/* set the extra_bytes value... */ |
|
1465 |
/* Please see note before the modbus_rtu_write() function for a |
|
1466 |
* better understanding of this extremely ugly hack... This will be |
|
1467 |
* in the mb_rtu.c file!! |
|
1468 |
* |
|
1469 |
* The number of extra bytes that must be allocated to the data buffer |
|
1470 |
* before calling modbus_tcp_write() |
|
1471 |
*/ |
|
1472 |
if (extra_bytes != NULL) |
|
1473 |
*extra_bytes = 0; |
|
1474 |
||
1475 |
if (0 == nd_count) |
|
1476 |
/* no need to initialise this layer! */ |
|
1477 |
return 0; |
|
1478 |
if (nd_count <= 0) |
|
1479 |
/* invalid node count... */ |
|
1480 |
goto error_exit_1; |
|
1481 |
||
1482 |
/* initialise the node table... */ |
|
1483 |
if (nd_table_init(&nd_table_, nd_count) < 0) |
|
1484 |
goto error_exit_1; |
|
1485 |
||
1486 |
#ifdef DEBUG |
|
1487 |
printf("[%lu] modbus_tcp_init(): %d node(s) opened succesfully\n", pthread_self(), nd_count); |
|
1488 |
#endif |
|
1489 |
return nd_count; /* number of succesfully created nodes! */ |
|
1490 |
||
1491 |
/* |
|
1492 |
error_exit_2: |
|
1493 |
nd_table_done(&nd_table_); |
|
1494 |
*/ |
|
1495 |
error_exit_1: |
|
1496 |
if (extra_bytes != NULL) |
|
1497 |
*extra_bytes = 0; |
|
1498 |
return -1; |
|
1499 |
} |
|
1500 |
||
1501 |
||
1502 |
||
1503 |
||
1504 |
||
1505 |
||
1506 |
/******************************/ |
|
1507 |
/** **/ |
|
1508 |
/** Open a Master Node **/ |
|
1509 |
/** **/ |
|
1510 |
/******************************/ |
|
1511 |
int modbus_tcp_connect(node_addr_t node_addr) { |
|
1512 |
int node_descriptor; |
|
1513 |
struct sockaddr_in tmp_addr; |
|
1514 |
||
1515 |
#ifdef DEBUG |
|
1516 |
printf("[%lu] modbus_tcp_connect(): called...\n", pthread_self()); |
|
1517 |
printf("[%lu] %s:%s\n", pthread_self(), |
|
1518 |
node_addr.addr.tcp.host, |
|
1519 |
node_addr.addr.tcp.service); |
|
1520 |
#endif |
|
1521 |
||
1522 |
/* Check for valid address family */ |
|
1523 |
if (node_addr.naf != naf_tcp) |
|
1524 |
/* wrong address type... */ |
|
1525 |
return -1; |
|
1526 |
||
1527 |
/* set the default values... */ |
|
1528 |
set_defaults(&(node_addr.addr.tcp.service)); |
|
1529 |
||
1530 |
/* Check the parameters we were passed... */ |
|
1531 |
if(sin_initaddr(&tmp_addr, |
|
10
1aed7a582ca7
correct version of --> Allow "" and NULL on TCP host and service (=> IP=INADDR_ANY, and port=0)
Mario de Sousa <msousa@fe.up.pt>
parents:
9
diff
changeset
|
1532 |
node_addr.addr.tcp.host, 1, // 1 => allow host NULL, "" or "*" -> INADDR_ANY |
1aed7a582ca7
correct version of --> Allow "" and NULL on TCP host and service (=> IP=INADDR_ANY, and port=0)
Mario de Sousa <msousa@fe.up.pt>
parents:
9
diff
changeset
|
1533 |
node_addr.addr.tcp.service, 1, // 1 => allow serivce NULL or "" -> port = 0 |
0 | 1534 |
DEF_PROTOCOL) |
1535 |
< 0) { |
|
1536 |
#ifdef ERRMSG |
|
1537 |
fprintf(stderr, ERRMSG_HEAD "Error parsing/resolving address %s:%s\n", |
|
1538 |
node_addr.addr.tcp.host, |
|
1539 |
node_addr.addr.tcp.service); |
|
1540 |
#endif |
|
1541 |
return -1; |
|
1542 |
} |
|
1543 |
||
1544 |
/* find a free node descriptor */ |
|
1545 |
if ((node_descriptor = nd_table_get_free_node(&nd_table_, MB_MASTER_NODE)) < 0) |
|
1546 |
/* if no free nodes to initialize, then we are finished... */ |
|
1547 |
return -1; |
|
1548 |
||
1549 |
nd_table_.node[node_descriptor].addr = tmp_addr; |
|
1550 |
nd_table_.node[node_descriptor].fd = -1; /* not currently connected... */ |
|
1551 |
nd_table_.node[node_descriptor].close_on_silence = node_addr.addr.tcp.close_on_silence; |
|
1552 |
||
1553 |
if (nd_table_.node[node_descriptor].close_on_silence < 0) |
|
1554 |
nd_table_.node[node_descriptor].close_on_silence = DEF_CLOSE_ON_SILENCE; |
|
1555 |
||
1556 |
/* WE have never tried to connect, so print an error the next time we try to connect */ |
|
1557 |
nd_table_.node[node_descriptor].print_connect_error = 1; |
|
1558 |
||
1559 |
#ifdef DEBUG |
|
1560 |
printf("[%lu] modbus_tcp_connect(): returning nd=%d\n", pthread_self(), node_descriptor); |
|
1561 |
#endif |
|
1562 |
return node_descriptor; |
|
1563 |
} |
|
1564 |
||
1565 |
||
1566 |
||
1567 |
/******************************/ |
|
1568 |
/** **/ |
|
1569 |
/** Open a Slave Node **/ |
|
1570 |
/** **/ |
|
1571 |
/******************************/ |
|
1572 |
||
1573 |
int modbus_tcp_listen(node_addr_t node_addr) { |
|
1574 |
int fd, nd; |
|
1575 |
||
1576 |
#ifdef DEBUG |
|
1577 |
printf("[%lu] modbus_tcp_listen(): called...\n", pthread_self()); |
|
1578 |
printf("[%lu] %s:%s\n", pthread_self(), |
|
1579 |
node_addr.addr.tcp.host, |
|
1580 |
node_addr.addr.tcp.service); |
|
1581 |
#endif |
|
1582 |
||
1583 |
/* Check for valid address family */ |
|
1584 |
if (node_addr.naf != naf_tcp) |
|
1585 |
/* wrong address type... */ |
|
1586 |
goto error_exit_0; |
|
1587 |
||
1588 |
/* set the default values... */ |
|
1589 |
set_defaults(&(node_addr.addr.tcp.service)); |
|
1590 |
||
1591 |
/* create a socket and bind it to the appropriate port... */ |
|
1592 |
fd = sin_bindsock(node_addr.addr.tcp.host, |
|
1593 |
node_addr.addr.tcp.service, |
|
1594 |
DEF_PROTOCOL); |
|
1595 |
if (fd < 0) { |
|
1596 |
#ifdef ERRMSG |
|
1597 |
fprintf(stderr, ERRMSG_HEAD "Could not bind to socket %s:%s\n", |
|
1598 |
((node_addr.addr.tcp.host==NULL)?"#ANY#":node_addr.addr.tcp.host), |
|
1599 |
node_addr.addr.tcp.service); |
|
1600 |
#endif |
|
1601 |
goto error_exit_0; |
|
1602 |
} |
|
1603 |
if (listen(fd, DEF_MAX_PENDING_CONNECTION_REQUESTS) < 0) |
|
1604 |
goto error_exit_0; |
|
1605 |
||
1606 |
/* find a free node descriptor */ |
|
1607 |
if ((nd = nd_table_get_free_node(&nd_table_, MB_LISTEN_NODE)) < 0) { |
|
1608 |
/* if no free nodes to initialize, then we are finished... */ |
|
1609 |
goto error_exit_1; |
|
1610 |
} |
|
1611 |
||
1612 |
/* nd_table_.node[nd].addr = tmp_addr; */ /* does not apply for MB_LISTEN_NODE */ |
|
1613 |
nd_table_.node[nd].fd = fd; /* not currently connected... */ |
|
1614 |
||
1615 |
#ifdef DEBUG |
|
1616 |
printf("[%lu] modbus_tcp_listen(): returning nd=%d\n", pthread_self(), nd); |
|
1617 |
#endif |
|
1618 |
return nd; |
|
1619 |
||
1620 |
error_exit_1: |
|
1621 |
close(fd); |
|
1622 |
error_exit_0: |
|
1623 |
return -1; |
|
1624 |
} |
|
1625 |
||
1626 |
||
1627 |
||
1628 |
/******************************/ |
|
1629 |
/** **/ |
|
1630 |
/** Close a node **/ |
|
1631 |
/** **/ |
|
1632 |
/******************************/ |
|
1633 |
||
1634 |
int modbus_tcp_close(int nd) { |
|
1635 |
#ifdef DEBUG |
|
1636 |
fprintf(stderr, "[%lu] modbus_tcp_close(): called... nd=%d\n", pthread_self(), nd); |
|
1637 |
#endif |
|
1638 |
||
1639 |
if ((nd < 0) || (nd >= nd_table_.node_count)) { |
|
1640 |
/* invalid nd */ |
|
1641 |
#ifdef DEBUG |
|
1642 |
fprintf(stderr, "[%lu] modbus_tcp_close(): invalid node %d. Should be < %d\n", pthread_self(), nd, nd_table_.node_count); |
|
1643 |
#endif |
|
1644 |
return -1; |
|
1645 |
} |
|
1646 |
||
1647 |
if (nd_table_.node[nd].node_type == MB_FREE_NODE) |
|
1648 |
/* already free node */ |
|
1649 |
return 0; |
|
1650 |
||
1651 |
close_connection(nd); |
|
1652 |
||
1653 |
nd_table_close_node(&nd_table_, nd); |
|
1654 |
||
1655 |
return 0; |
|
1656 |
} |
|
1657 |
||
1658 |
||
1659 |
||
1660 |
/**********************************/ |
|
1661 |
/** **/ |
|
1662 |
/** Close all open connections **/ |
|
1663 |
/** **/ |
|
1664 |
/**********************************/ |
|
1665 |
||
1666 |
int modbus_tcp_silence_init(void) { |
|
1667 |
int nd; |
|
1668 |
||
1669 |
#ifdef DEBUG |
|
1670 |
printf("[%lu] modbus_tcp_silence_init(): called...\n", pthread_self()); |
|
1671 |
#endif |
|
1672 |
||
1673 |
/* close all master connections that remain open... */ |
|
1674 |
for (nd = 0; nd < nd_table_.node_count; nd++) |
|
1675 |
if (nd_table_.node[nd].node_type == MB_MASTER_NODE) |
|
1676 |
if (nd_table_.node[nd].close_on_silence > 0) |
|
1677 |
/* node is is being used for a master device, |
|
1678 |
* and wishes to be closed... ...so we close it! |
|
1679 |
*/ |
|
1680 |
close_connection(nd); |
|
1681 |
||
1682 |
return 0; |
|
1683 |
} |
|
1684 |
||
1685 |
||
1686 |
||
1687 |
/******************************/ |
|
1688 |
/** **/ |
|
1689 |
/** Shutdown the Library **/ |
|
1690 |
/** **/ |
|
1691 |
/******************************/ |
|
1692 |
||
1693 |
int modbus_tcp_done(void) { |
|
1694 |
int i; |
|
1695 |
||
1696 |
modbus_tcp_init_counter--; |
|
1697 |
if (modbus_tcp_init_counter != 0) return 0; /* ignore this request */ |
|
1698 |
||
1699 |
/* close all the connections... */ |
|
1700 |
for (i = 0; i < nd_table_.node_count; i++) |
|
1701 |
modbus_tcp_close(i); |
|
1702 |
||
1703 |
/* Free memory... */ |
|
1704 |
nd_table_done(&nd_table_); |
|
1705 |
||
1706 |
return 0; |
|
1707 |
} |
|
1708 |
||
1709 |
||
1710 |
||
1711 |
||
1712 |
double modbus_tcp_get_min_timeout(int baud, |
|
1713 |
int parity, |
|
1714 |
int data_bits, |
|
1715 |
int stop_bits) { |
|
1716 |
return 0; |
|
1717 |
} |