random-test-server.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 <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", modbus_strerror(errno));
  23. modbus_free(ctx);
  24. return -1;
  25. }
  26. s = modbus_tcp_listen(ctx, 1);
  27. modbus_tcp_accept(ctx, &s);
  28. for (;;) {
  29. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  30. int rc;
  31. rc = modbus_receive(ctx, query);
  32. if (rc > 0) {
  33. /* rc is the query size */
  34. modbus_reply(ctx, query, rc, mb_mapping);
  35. } else if (rc == -1) {
  36. /* Connection closed by the client or error */
  37. break;
  38. }
  39. }
  40. printf("Quit the loop: %s\n", modbus_strerror(errno));
  41. if (s != -1) {
  42. close(s);
  43. }
  44. modbus_mapping_free(mb_mapping);
  45. modbus_close(ctx);
  46. modbus_free(ctx);
  47. return 0;
  48. }