Fix many typos
[libmodbus.git] / tests / bandwidth-server-one.c
blob2ce17f1f388938d3d66f0e1d01d009ea90a809c5
1 /*
2 * Copyright © 2008-2014 Stéphane Raimbault <stephane.raimbault@gmail.com>
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
7 #include <stdio.h>
8 #ifndef _MSC_VER
9 #include <unistd.h>
10 #endif
11 #include <string.h>
12 #include <stdlib.h>
13 #include <errno.h>
15 #include <modbus.h>
17 #if defined(_WIN32)
18 #define close closesocket
19 #endif
21 enum {
22 TCP,
23 RTU
26 int main(int argc, char *argv[])
28 int s = -1;
29 modbus_t *ctx = NULL;
30 modbus_mapping_t *mb_mapping = NULL;
31 int rc;
32 int use_backend;
34 /* TCP */
35 if (argc > 1) {
36 if (strcmp(argv[1], "tcp") == 0) {
37 use_backend = TCP;
38 } else if (strcmp(argv[1], "rtu") == 0) {
39 use_backend = RTU;
40 } else {
41 printf("Usage:\n %s [tcp|rtu] - Modbus client to measure data bandwidth\n\n", argv[0]);
42 exit(1);
44 } else {
45 /* By default */
46 use_backend = TCP;
49 if (use_backend == TCP) {
50 ctx = modbus_new_tcp("127.0.0.1", 1502);
51 s = modbus_tcp_listen(ctx, 1);
52 modbus_tcp_accept(ctx, &s);
54 } else {
55 ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
56 modbus_set_slave(ctx, 1);
57 modbus_connect(ctx);
60 mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
61 MODBUS_MAX_READ_REGISTERS, 0);
62 if (mb_mapping == NULL) {
63 fprintf(stderr, "Failed to allocate the mapping: %s\n",
64 modbus_strerror(errno));
65 modbus_free(ctx);
66 return -1;
69 for(;;) {
70 uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
72 rc = modbus_receive(ctx, query);
73 if (rc > 0) {
74 modbus_reply(ctx, query, rc, mb_mapping);
75 } else if (rc == -1) {
76 /* Connection closed by the client or error */
77 break;
81 printf("Quit the loop: %s\n", modbus_strerror(errno));
83 modbus_mapping_free(mb_mapping);
84 if (s != -1) {
85 close(s);
87 /* For RTU, skipped by TCP (no TCP connect) */
88 modbus_close(ctx);
89 modbus_free(ctx);
91 return 0;