random-test-server.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright © 2008-2010 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 GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <stdio.h>
  18. #include <unistd.h>
  19. #include <stdlib.h>
  20. #include <errno.h>
  21. #include <modbus.h>
  22. int main(void)
  23. {
  24. int socket;
  25. modbus_t *ctx;
  26. modbus_mapping_t *mb_mapping;
  27. ctx = modbus_new_tcp("127.0.0.1", 1502);
  28. /* modbus_set_debug(ctx, TRUE); */
  29. mb_mapping = modbus_mapping_new(500, 500, 500, 500);
  30. if (mb_mapping == NULL) {
  31. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  32. modbus_strerror(errno));
  33. modbus_free(ctx);
  34. return -1;
  35. }
  36. socket = modbus_tcp_listen(ctx, 1);
  37. modbus_tcp_accept(ctx, &socket);
  38. for (;;) {
  39. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  40. int rc;
  41. rc = modbus_receive(ctx, query);
  42. if (rc > 0) {
  43. /* rc is the query size */
  44. modbus_reply(ctx, query, rc, mb_mapping);
  45. } else if (rc == -1) {
  46. /* Connection closed by the client or error */
  47. break;
  48. }
  49. }
  50. printf("Quit the loop: %s\n", modbus_strerror(errno));
  51. modbus_mapping_free(mb_mapping);
  52. modbus_close(ctx);
  53. modbus_free(ctx);
  54. return 0;
  55. }