bandwidth-server-one.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright © 2008-2012 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 <string.h>
  22. #include <stdlib.h>
  23. #include <errno.h>
  24. #include <modbus.h>
  25. #if defined(_WIN32)
  26. #define close closesocket
  27. #endif
  28. enum {
  29. TCP,
  30. RTU
  31. };
  32. int main(int argc, char *argv[])
  33. {
  34. int socket;
  35. modbus_t *ctx;
  36. modbus_mapping_t *mb_mapping;
  37. int rc;
  38. int use_backend;
  39. /* TCP */
  40. if (argc > 1) {
  41. if (strcmp(argv[1], "tcp") == 0) {
  42. use_backend = TCP;
  43. } else if (strcmp(argv[1], "rtu") == 0) {
  44. use_backend = RTU;
  45. } else {
  46. printf("Usage:\n %s [tcp|rtu] - Modbus client to measure data bandwith\n\n", argv[0]);
  47. exit(1);
  48. }
  49. } else {
  50. /* By default */
  51. use_backend = TCP;
  52. }
  53. if (use_backend == TCP) {
  54. ctx = modbus_new_tcp("127.0.0.1", 1502);
  55. socket = modbus_tcp_listen(ctx, 1);
  56. modbus_tcp_accept(ctx, &socket);
  57. } else {
  58. ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
  59. modbus_set_slave(ctx, 1);
  60. modbus_connect(ctx);
  61. }
  62. mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
  63. MODBUS_MAX_READ_REGISTERS, 0);
  64. if (mb_mapping == NULL) {
  65. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  66. modbus_strerror(errno));
  67. modbus_free(ctx);
  68. return -1;
  69. }
  70. for(;;) {
  71. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  72. rc = modbus_receive(ctx, query);
  73. if (rc > 0) {
  74. modbus_reply(ctx, query, rc, mb_mapping);
  75. } else if (rc == -1) {
  76. /* Connection closed by the client or error */
  77. break;
  78. }
  79. }
  80. printf("Quit the loop: %s\n", modbus_strerror(errno));
  81. modbus_mapping_free(mb_mapping);
  82. close(socket);
  83. modbus_free(ctx);
  84. return 0;
  85. }