| 1 | /* |
| 2 | * Copyright © Stéphane Raimbault <[email protected]> |
| 3 | * |
| 4 | * SPDX-License-Identifier: BSD-3-Clause |
| 5 | */ |
| 6 | |
| 7 | #include <stdio.h> |
| 8 | #ifndef _MSC_VER |
| 9 | #include <unistd.h> |
| 10 | #endif |
| 11 | #include <errno.h> |
| 12 | #include <stdlib.h> |
| 13 | #include <string.h> |
| 14 | |
| 15 | #include <modbus.h> |
| 16 | |
| 17 | #if defined(_WIN32) |
| 18 | #define close closesocket |
| 19 | #endif |
| 20 | |
| 21 | enum { |
| 22 | TCP, |
| 23 | RTU |
| 24 | }; |
| 25 | |
| 26 | int main(int argc, char *argv[]) |
| 27 | { |
| 28 | int s = -1; |
| 29 | modbus_t *ctx = NULL; |
| 30 | modbus_mapping_t *mb_mapping = NULL; |
| 31 | int rc; |
| 32 | int use_backend; |
| 33 | |
| 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", |
| 42 | argv[0]); |
| 43 | exit(1); |
| 44 | } |
| 45 | } else { |
| 46 | /* By default */ |
| 47 | use_backend = TCP; |
| 48 | } |
| 49 | |
| 50 | if (use_backend == TCP) { |
| 51 | ctx = modbus_new_tcp("127.0.0.1", 1502); |
| 52 | s = modbus_tcp_listen(ctx, 1); |
| 53 | modbus_tcp_accept(ctx, &s); |
| 54 | |
| 55 | } else { |
| 56 | ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1); |
| 57 | modbus_set_slave(ctx, 1); |
| 58 | modbus_connect(ctx); |
| 59 | } |
| 60 | |
| 61 | mb_mapping = |
| 62 | modbus_mapping_new(MODBUS_MAX_READ_BITS, 0, MODBUS_MAX_READ_REGISTERS, 0); |
| 63 | if (mb_mapping == NULL) { |
| 64 | fprintf(stderr, "Failed to allocate the mapping: %s\n", modbus_strerror(errno)); |
| 65 | modbus_free(ctx); |
| 66 | return -1; |
| 67 | } |
| 68 | |
| 69 | for (;;) { |
| 70 | uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH]; |
| 71 | |
| 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; |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | printf("Quit the loop: %s\n", modbus_strerror(errno)); |
| 82 | |
| 83 | modbus_mapping_free(mb_mapping); |
| 84 | if (s != -1) { |
| 85 | close(s); |
| 86 | } |
| 87 | /* For RTU, skipped by TCP (no TCP connect) */ |
| 88 | modbus_close(ctx); |
| 89 | modbus_free(ctx); |
| 90 | |
| 91 | return 0; |
| 92 | } |