random-test-server.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright © 2008-2014 Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the BSD License.
  6. */
  7. #include <stdio.h>
  8. #ifndef _MSC_VER
  9. #include <unistd.h>
  10. #endif
  11. #include <stdlib.h>
  12. #include <errno.h>
  13. #include <modbus.h>
  14. int main(void)
  15. {
  16. int s = -1;
  17. modbus_t *ctx;
  18. modbus_mapping_t *mb_mapping;
  19. ctx = modbus_new_tcp("127.0.0.1", 1502);
  20. /* modbus_set_debug(ctx, TRUE); */
  21. mb_mapping = modbus_mapping_new(500, 500, 500, 500);
  22. if (mb_mapping == NULL) {
  23. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  24. modbus_strerror(errno));
  25. modbus_free(ctx);
  26. return -1;
  27. }
  28. s = modbus_tcp_listen(ctx, 1);
  29. modbus_tcp_accept(ctx, &s);
  30. for (;;) {
  31. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  32. int rc;
  33. rc = modbus_receive(ctx, query);
  34. if (rc > 0) {
  35. /* rc is the query size */
  36. modbus_reply(ctx, query, rc, mb_mapping);
  37. } else if (rc == -1) {
  38. /* Connection closed by the client or error */
  39. break;
  40. }
  41. }
  42. printf("Quit the loop: %s\n", modbus_strerror(errno));
  43. if (s != -1) {
  44. close(s);
  45. }
  46. modbus_mapping_free(mb_mapping);
  47. modbus_close(ctx);
  48. modbus_free(ctx);
  49. return 0;
  50. }