bandwidth-server-one.c 2.1 KB

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