Fix Bluetooth Ping Timeout

This commit is contained in:
2019-02-04 21:35:20 +01:00
parent d114c685d0
commit b623ba5003
5 changed files with 113 additions and 87 deletions
+50 -2
View File
@@ -6,6 +6,7 @@
#include <bluetooth/hci.h>
#include <bluetooth/l2cap.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/poll.h>
#include "Socket.h"
@@ -42,8 +43,55 @@ bool Functions::Ping(const std::string& macAddress)
socketAddress.l2_family = AF_BLUETOOTH;
str2ba(macAddress.c_str(), &socketAddress.l2_bdaddr);
if (connect(socketDescriptor, reinterpret_cast<struct sockaddr*>(&socketAddress), sizeof(socketAddress)) < 0)
return false;
struct timeval timeoutStruct;
timeoutStruct.tv_sec = 3;
timeoutStruct.tv_usec = 0;
fd_set writeDescriptor, errorDescriptor;
FD_ZERO(&writeDescriptor);
FD_ZERO(&errorDescriptor);
FD_SET(socketDescriptor, &writeDescriptor);
FD_SET(socketDescriptor, &errorDescriptor);
int flags;
if((flags = fcntl(socketDescriptor, F_GETFL, 0) < 0))
throw std::runtime_error("Can't get socket options");
if(fcntl(socketDescriptor, F_SETFL, flags | O_NONBLOCK) < 0)
throw std::runtime_error("Can't set socket options");
int ret = 0;
if ((ret = connect(socketDescriptor, reinterpret_cast<struct sockaddr*>(&socketAddress), sizeof(socketAddress)) < 0))
{
if (errno != EINPROGRESS)
return false;
}
if (ret != 0)
{
if (select(socketDescriptor + 1, &errorDescriptor, &writeDescriptor, NULL, &timeoutStruct) < 0)
return false;
int error = 0;
socklen_t len = sizeof(error);
if (FD_ISSET(socketDescriptor, &errorDescriptor) || FD_ISSET(socketDescriptor, &writeDescriptor))
{
if (getsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
return false;
}
else
{
return false;
}
if (error)
return false;
}
if(fcntl(socketDescriptor, F_SETFL, flags) < 0)
throw std::runtime_error("Can't set socket options");
connect(socketDescriptor, reinterpret_cast<struct sockaddr*>(&socketAddress), sizeof(socketAddress));
memset(&socketAddress, 0, sizeof(socketAddress));
socklen_t optlen = sizeof(socketAddress);