TCPServerDevice.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #include "TCPServerDevice.h"
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <AP_HAL/AP_HAL.h>
  7. extern const AP_HAL::HAL& hal;
  8. TCPServerDevice::TCPServerDevice(const char *ip, uint16_t port, bool wait):
  9. _ip(ip),
  10. _port(port),
  11. _wait(wait)
  12. {
  13. }
  14. TCPServerDevice::~TCPServerDevice()
  15. {
  16. if (sock != nullptr) {
  17. delete sock;
  18. sock = nullptr;
  19. }
  20. }
  21. ssize_t TCPServerDevice::write(const uint8_t *buf, uint16_t n)
  22. {
  23. if (sock == nullptr) {
  24. return -1;
  25. }
  26. return sock->send(buf, n);
  27. }
  28. /*
  29. when we try to read we accept new connections if one isn't already
  30. established
  31. */
  32. ssize_t TCPServerDevice::read(uint8_t *buf, uint16_t n)
  33. {
  34. if (sock == nullptr) {
  35. sock = listener.accept(0);
  36. if (sock != nullptr) {
  37. sock->set_blocking(_blocking);
  38. }
  39. }
  40. if (sock == nullptr) {
  41. return -1;
  42. }
  43. ssize_t ret = sock->recv(buf, n, 1);
  44. if (ret == 0) {
  45. // EOF, go back to waiting for a new connection
  46. delete sock;
  47. sock = nullptr;
  48. return -1;
  49. }
  50. return ret;
  51. }
  52. bool TCPServerDevice::open()
  53. {
  54. listener.reuseaddress();
  55. if (!listener.bind(_ip, _port)) {
  56. if (AP_HAL::millis() - _last_bind_warning > 5000) {
  57. ::printf("bind failed on %s port %u - %s\n",
  58. _ip,
  59. _port,
  60. strerror(errno));
  61. _last_bind_warning = AP_HAL::millis();
  62. }
  63. return false;
  64. }
  65. if (!listener.listen(1)) {
  66. if (AP_HAL::millis() - _last_bind_warning > 5000) {
  67. ::printf("listen failed on %s port %u - %s\n",
  68. _ip,
  69. _port,
  70. strerror(errno));
  71. _last_bind_warning = AP_HAL::millis();
  72. }
  73. return false;
  74. }
  75. listener.set_blocking(false);
  76. if (_wait) {
  77. ::printf("Waiting for connection on %s:%u ....\n",
  78. _ip, (unsigned)_port);
  79. ::fflush(stdout);
  80. while (sock == nullptr) {
  81. sock = listener.accept(1000);
  82. }
  83. sock->set_blocking(_blocking);
  84. ::printf("connected\n");
  85. ::fflush(stdout);
  86. }
  87. return true;
  88. }
  89. bool TCPServerDevice::close()
  90. {
  91. if (sock != nullptr) {
  92. delete sock;
  93. sock = nullptr;
  94. }
  95. return true;
  96. }
  97. void TCPServerDevice::set_blocking(bool blocking)
  98. {
  99. _blocking = blocking;
  100. listener.set_blocking(_blocking);
  101. }
  102. void TCPServerDevice::set_speed(uint32_t speed)
  103. {
  104. }