ardupilot/libraries/AP_HAL_Linux/TCPServerDevice.cpp

121 lines
2.5 KiB
C++
Raw Permalink Normal View History

#include "TCPServerDevice.h"
2015-06-19 10:58:40 -03:00
#include <errno.h>
#include <stdio.h>
2015-06-19 10:58:40 -03:00
#include <stdlib.h>
#include <unistd.h>
2015-06-19 10:58:40 -03:00
#include <AP_HAL/AP_HAL.h>
2015-06-19 10:58:40 -03:00
extern const AP_HAL::HAL& hal;
TCPServerDevice::TCPServerDevice(const char *ip, uint16_t port, bool wait):
2015-06-19 10:58:40 -03:00
_ip(ip),
_port(port),
_wait(wait)
2015-06-19 10:58:40 -03:00
{
}
2015-07-08 14:27:21 -03:00
TCPServerDevice::~TCPServerDevice()
2015-06-19 10:58:40 -03:00
{
if (sock != nullptr) {
delete sock;
sock = nullptr;
}
2015-06-19 10:58:40 -03:00
}
2015-07-08 14:27:21 -03:00
ssize_t TCPServerDevice::write(const uint8_t *buf, uint16_t n)
2015-06-19 10:58:40 -03:00
{
if (sock == nullptr) {
return -1;
}
return sock->send(buf, n);
2015-06-19 10:58:40 -03:00
}
/*
when we try to read we accept new connections if one isn't already
established
*/
2015-07-08 14:27:21 -03:00
ssize_t TCPServerDevice::read(uint8_t *buf, uint16_t n)
2015-06-19 10:58:40 -03:00
{
if (sock == nullptr) {
sock = listener.accept(0);
if (sock != nullptr) {
sock->set_blocking(_blocking);
}
}
if (sock == nullptr) {
return -1;
}
ssize_t ret = sock->recv(buf, n, 1);
if (ret == 0) {
// EOF, go back to waiting for a new connection
delete sock;
sock = nullptr;
return -1;
}
return ret;
2015-06-19 10:58:40 -03:00
}
2015-07-08 14:27:21 -03:00
bool TCPServerDevice::open()
2015-06-19 10:58:40 -03:00
{
listener.reuseaddress();
if (!listener.bind(_ip, _port)) {
if (AP_HAL::millis() - _last_bind_warning > 5000) {
::printf("bind failed on %s port %u - %s\n",
_ip,
_port,
strerror(errno));
_last_bind_warning = AP_HAL::millis();
}
return false;
}
if (!listener.listen(1)) {
if (AP_HAL::millis() - _last_bind_warning > 5000) {
::printf("listen failed on %s port %u - %s\n",
_ip,
_port,
strerror(errno));
_last_bind_warning = AP_HAL::millis();
}
return false;
2015-06-19 10:58:40 -03:00
}
listener.set_blocking(false);
if (_wait) {
::printf("Waiting for connection on %s:%u ....\n",
_ip, (unsigned)_port);
::fflush(stdout);
while (sock == nullptr) {
sock = listener.accept(1000);
}
sock->set_blocking(_blocking);
::printf("connected\n");
::fflush(stdout);
}
2015-06-19 10:58:40 -03:00
return true;
}
2015-07-08 14:27:21 -03:00
bool TCPServerDevice::close()
2015-06-19 10:58:40 -03:00
{
if (sock != nullptr) {
delete sock;
sock = nullptr;
}
2015-06-19 10:58:40 -03:00
return true;
}
2015-07-08 14:27:21 -03:00
void TCPServerDevice::set_blocking(bool blocking)
2015-06-19 10:58:40 -03:00
{
_blocking = blocking;
listener.set_blocking(_blocking);
2015-06-19 10:58:40 -03:00
}
2015-07-08 14:27:21 -03:00
void TCPServerDevice::set_speed(uint32_t speed)
2015-06-19 10:58:40 -03:00
{
}