random-test-server.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright © 2008-2014 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 <stdlib.h>
  11. #include <errno.h>
  12. #include <modbus.h>
  13. int main(void)
  14. {
  15. int s = -1;
  16. modbus_t *ctx;
  17. modbus_mapping_t *mb_mapping;
  18. ctx = modbus_new_tcp("127.0.0.1", 1502);
  19. /* modbus_set_debug(ctx, TRUE); */
  20. mb_mapping = modbus_mapping_new(500, 500, 500, 500);
  21. if (mb_mapping == NULL) {
  22. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  23. modbus_strerror(errno));
  24. modbus_free(ctx);
  25. return -1;
  26. }
  27. s = modbus_tcp_listen(ctx, 1);
  28. modbus_tcp_accept(ctx, &s);
  29. for (;;) {
  30. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  31. int rc;
  32. rc = modbus_receive(ctx, query);
  33. if (rc > 0) {
  34. /* rc is the query size */
  35. modbus_reply(ctx, query, rc, mb_mapping);
  36. } else if (rc == -1) {
  37. /* Connection closed by the client or error */
  38. break;
  39. }
  40. }
  41. printf("Quit the loop: %s\n", modbus_strerror(errno));
  42. if (s != -1) {
  43. close(s);
  44. }
  45. modbus_mapping_free(mb_mapping);
  46. modbus_close(ctx);
  47. modbus_free(ctx);
  48. return 0;
  49. }