random-test-server.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. #ifndef _MSC_VER
  19. #include <unistd.h>
  20. #endif
  21. #include <stdlib.h>
  22. #include <errno.h>
  23. #include <modbus.h>
  24. int main(void)
  25. {
  26. int socket = -1;
  27. modbus_t *ctx;
  28. modbus_mapping_t *mb_mapping;
  29. ctx = modbus_new_tcp("127.0.0.1", 1502);
  30. /* modbus_set_debug(ctx, TRUE); */
  31. mb_mapping = modbus_mapping_new(500, 500, 500, 500);
  32. if (mb_mapping == NULL) {
  33. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  34. modbus_strerror(errno));
  35. modbus_free(ctx);
  36. return -1;
  37. }
  38. socket = modbus_tcp_listen(ctx, 1);
  39. modbus_tcp_accept(ctx, &socket);
  40. for (;;) {
  41. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  42. int rc;
  43. rc = modbus_receive(ctx, query);
  44. if (rc > 0) {
  45. /* rc is the query size */
  46. modbus_reply(ctx, query, rc, mb_mapping);
  47. } else if (rc == -1) {
  48. /* Connection closed by the client or error */
  49. break;
  50. }
  51. }
  52. printf("Quit the loop: %s\n", modbus_strerror(errno));
  53. if (socket != -1) {
  54. close(socket);
  55. }
  56. modbus_mapping_free(mb_mapping);
  57. modbus_close(ctx);
  58. modbus_free(ctx);
  59. return 0;
  60. }