bandwidth-server-one.c 2.0 KB

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