bandwidth-server-one.c 2.5 KB

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