BluetoothLink.cc 9.25 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
dogmaphobic's avatar
dogmaphobic committed
9 10 11 12 13 14 15 16 17 18

#include <QtGlobal>
#include <QTimer>
#include <QList>
#include <QDebug>
#include <iostream>

#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QtBluetooth/QBluetoothUuid>
dogmaphobic's avatar
dogmaphobic committed
19
#include <QtBluetooth/QBluetoothSocket>
dogmaphobic's avatar
dogmaphobic committed
20

21
#include "QGCApplication.h"
dogmaphobic's avatar
dogmaphobic committed
22 23
#include "BluetoothLink.h"
#include "QGC.h"
24
#include "LinkManager.h"
dogmaphobic's avatar
dogmaphobic committed
25

26 27
BluetoothLink::BluetoothLink(SharedLinkConfigurationPtr& config)
    : LinkInterface     (config)
dogmaphobic's avatar
dogmaphobic committed
28
{
29

dogmaphobic's avatar
dogmaphobic committed
30 31 32 33
}

BluetoothLink::~BluetoothLink()
{
34
    disconnect();
dogmaphobic's avatar
dogmaphobic committed
35 36 37 38 39
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
40
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
41 42
    }
#endif
dogmaphobic's avatar
dogmaphobic committed
43 44 45 46 47 48 49 50 51 52 53 54
}

void BluetoothLink::run()
{

}

QString BluetoothLink::getName() const
{
    return _config->name();
}

55
void BluetoothLink::_writeBytes(const QByteArray bytes)
dogmaphobic's avatar
dogmaphobic committed
56
{
57 58
    if (_targetSocket) {
        if(_targetSocket->write(bytes) > 0) {
Pierre TILAK's avatar
Pierre TILAK committed
59
            emit bytesSent(this, bytes);
60 61
        } else {
            qWarning() << "Bluetooth write error";
dogmaphobic's avatar
dogmaphobic committed
62 63 64 65 66 67
        }
    }
}

void BluetoothLink::readBytes()
{
68 69 70 71 72 73 74
    if (_targetSocket) {
        while (_targetSocket->bytesAvailable() > 0) {
            QByteArray datagram;
            datagram.resize(_targetSocket->bytesAvailable());
            _targetSocket->read(datagram.data(), datagram.size());
            emit bytesReceived(this, datagram);
        }
dogmaphobic's avatar
dogmaphobic committed
75 76 77
    }
}

78
void BluetoothLink::disconnect(void)
dogmaphobic's avatar
dogmaphobic committed
79
{
dogmaphobic's avatar
dogmaphobic committed
80 81 82 83 84
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
85
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
86
    }
dogmaphobic's avatar
dogmaphobic committed
87
#endif
88
    if(_targetSocket) {
89
        _targetSocket->deleteLater();
90
        _targetSocket = nullptr;
dogmaphobic's avatar
dogmaphobic committed
91 92 93 94 95 96 97
        emit disconnected();
    }
    _connectState = false;
}

bool BluetoothLink::_connect(void)
{
dogmaphobic's avatar
dogmaphobic committed
98
    _hardwareConnect();
dogmaphobic's avatar
dogmaphobic committed
99 100 101 102
    return true;
}

bool BluetoothLink::_hardwareConnect()
dogmaphobic's avatar
dogmaphobic committed
103 104 105 106 107 108
{
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
109
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
110 111
    }
    _discoveryAgent = new QBluetoothServiceDiscoveryAgent(this);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
112 113 114
    QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::serviceDiscovered, this, &BluetoothLink::serviceDiscovered);
    QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::finished, this, &BluetoothLink::discoveryFinished);
    QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::canceled, this, &BluetoothLink::discoveryFinished);
dogmaphobic's avatar
dogmaphobic committed
115 116 117 118
    _shutDown = false;
    _discoveryAgent->start();
#else
    _createSocket();
119
    _targetSocket->connectToService(QBluetoothAddress(qobject_cast<BluetoothConfiguration*>(_config.get())->device().address), QBluetoothUuid(QBluetoothUuid::SerialPort));
dogmaphobic's avatar
dogmaphobic committed
120 121 122 123 124
#endif
    return true;
}

void BluetoothLink::_createSocket()
dogmaphobic's avatar
dogmaphobic committed
125 126 127 128
{
    if(_targetSocket)
    {
        delete _targetSocket;
129
        _targetSocket = nullptr;
dogmaphobic's avatar
dogmaphobic committed
130 131
    }
    _targetSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
132
    QObject::connect(_targetSocket, &QBluetoothSocket::connected, this, &BluetoothLink::deviceConnected);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
133

134 135
    QObject::connect(_targetSocket, &QBluetoothSocket::readyRead, this, &BluetoothLink::readBytes);
    QObject::connect(_targetSocket, &QBluetoothSocket::disconnected, this, &BluetoothLink::deviceDisconnected);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
136 137 138

    QObject::connect(_targetSocket, static_cast<void (QBluetoothSocket::*)(QBluetoothSocket::SocketError)>(&QBluetoothSocket::error),
            this, &BluetoothLink::deviceError);
dogmaphobic's avatar
dogmaphobic committed
139 140
}

dogmaphobic's avatar
dogmaphobic committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
#ifdef __ios__
void BluetoothLink::serviceDiscovered(const QBluetoothServiceInfo& info)
{
    if(!info.device().name().isEmpty() && !_targetSocket)
    {
        if(_config->device().uuid == info.device().deviceUuid() && _config->device().name == info.device().name())
        {
            _createSocket();
            _targetSocket->connectToService(info);
        }
    }
}
#endif

#ifdef __ios__
void BluetoothLink::discoveryFinished()
{
    if(_discoveryAgent && !_shutDown)
    {
        _shutDown = true;
        _discoveryAgent->deleteLater();
162
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
163 164 165 166 167 168 169 170 171
        if(!_targetSocket)
        {
            _connectState = false;
            emit communicationError("Could not locate Bluetooth device:", _config->device().name);
        }
    }
}
#endif

dogmaphobic's avatar
dogmaphobic committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
void BluetoothLink::deviceConnected()
{
    _connectState = true;
    emit connected();
}

void BluetoothLink::deviceDisconnected()
{
    _connectState = false;
    qWarning() << "Bluetooth disconnected";
}

void BluetoothLink::deviceError(QBluetoothSocket::SocketError error)
{
    _connectState = false;
    qWarning() << "Bluetooth error" << error;
188
    emit communicationError(tr("Bluetooth Link Error"), _targetSocket->errorString());
dogmaphobic's avatar
dogmaphobic committed
189 190 191 192 193 194 195 196 197 198 199 200
}

bool BluetoothLink::isConnected() const
{
    return _connectState;
}

//--------------------------------------------------------------------------
//-- BluetoothConfiguration

BluetoothConfiguration::BluetoothConfiguration(const QString& name)
    : LinkConfiguration(name)
201
    , _deviceDiscover(nullptr)
dogmaphobic's avatar
dogmaphobic committed
202 203 204 205 206 207
{

}

BluetoothConfiguration::BluetoothConfiguration(BluetoothConfiguration* source)
    : LinkConfiguration(source)
208
    , _deviceDiscover(nullptr)
209
    , _device(source->device())
dogmaphobic's avatar
dogmaphobic committed
210 211 212 213 214 215 216 217 218 219 220 221
{
}

BluetoothConfiguration::~BluetoothConfiguration()
{
    if(_deviceDiscover)
    {
        _deviceDiscover->stop();
        delete _deviceDiscover;
    }
}

222 223 224 225 226 227 228 229 230
QString BluetoothConfiguration::settingsTitle()
{
    if(qgcApp()->toolbox()->linkManager()->isBluetoothAvailable()) {
        return tr("Bluetooth Link Settings");
    } else {
        return tr("Bluetooth Not Available");
    }
}

dogmaphobic's avatar
dogmaphobic committed
231 232 233
void BluetoothConfiguration::copyFrom(LinkConfiguration *source)
{
    LinkConfiguration::copyFrom(source);
234
    auto* usource = qobject_cast<BluetoothConfiguration*>(source);
235
    Q_ASSERT(usource != nullptr);
236
    _device = usource->device();
dogmaphobic's avatar
dogmaphobic committed
237 238 239 240 241
}

void BluetoothConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
dogmaphobic's avatar
dogmaphobic committed
242 243 244 245 246 247
    settings.setValue("deviceName", _device.name);
#ifdef __ios__
    settings.setValue("uuid", _device.uuid.toString());
#else
    settings.setValue("address",_device.address);
#endif
dogmaphobic's avatar
dogmaphobic committed
248 249 250 251 252 253
    settings.endGroup();
}

void BluetoothConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
dogmaphobic's avatar
dogmaphobic committed
254 255 256 257 258
    _device.name    = settings.value("deviceName", _device.name).toString();
#ifdef __ios__
    QString suuid   = settings.value("uuid", _device.uuid.toString()).toString();
    _device.uuid    = QUuid(suuid);
#else
259
    _device.address = settings.value("address", _device.address).toString();
dogmaphobic's avatar
dogmaphobic committed
260
#endif
dogmaphobic's avatar
dogmaphobic committed
261 262 263 264 265 266 267
    settings.endGroup();
}

void BluetoothConfiguration::stopScan()
{
    if(_deviceDiscover)
    {
268 269
        _deviceDiscover->stop();
        _deviceDiscover->deleteLater();
270
        _deviceDiscover = nullptr;
271
        emit scanningChanged();
dogmaphobic's avatar
dogmaphobic committed
272 273 274 275 276
    }
}

void BluetoothConfiguration::startScan()
{
277
    if(!_deviceDiscover) {
dogmaphobic's avatar
dogmaphobic committed
278
        _deviceDiscover = new QBluetoothDeviceDiscoveryAgent(this);
279 280
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,  this, &BluetoothConfiguration::deviceDiscovered);
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::finished,          this, &BluetoothConfiguration::doneScanning);
dogmaphobic's avatar
dogmaphobic committed
281
        emit scanningChanged();
282
    } else {
dogmaphobic's avatar
dogmaphobic committed
283 284
        _deviceDiscover->stop();
    }
285
    _nameList.clear();
dogmaphobic's avatar
dogmaphobic committed
286
    _deviceList.clear();
287
    emit nameListChanged();
dogmaphobic's avatar
dogmaphobic committed
288 289 290 291 292 293
    _deviceDiscover->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
    _deviceDiscover->start();
}

void BluetoothConfiguration::deviceDiscovered(QBluetoothDeviceInfo info)
{
294 295
    if(!info.name().isEmpty() && info.isValid())
    {
296 297 298 299 300
#if 0
        qDebug() << "Name:           " << info.name();
        qDebug() << "Address:        " << info.address().toString();
        qDebug() << "Service Classes:" << info.serviceClasses();
        QList<QBluetoothUuid> uuids = info.serviceUuids();
301
        for (QBluetoothUuid uuid: uuids) {
302 303 304
            qDebug() << "Service UUID:   " << uuid.toString();
        }
#endif
305 306
        BluetoothData data;
        data.name    = info.name();
dogmaphobic's avatar
dogmaphobic committed
307 308 309
#ifdef __ios__
        data.uuid    = info.deviceUuid();
#else
310
        data.address = info.address().toString();
dogmaphobic's avatar
dogmaphobic committed
311
#endif
312 313 314 315 316 317 318 319
        if(!_deviceList.contains(data))
        {
            _deviceList += data;
            _nameList   += data.name;
            emit nameListChanged();
            return;
        }
    }
dogmaphobic's avatar
dogmaphobic committed
320 321 322 323 324 325 326
}

void BluetoothConfiguration::doneScanning()
{
    if(_deviceDiscover)
    {
        _deviceDiscover->deleteLater();
327
        _deviceDiscover = nullptr;
dogmaphobic's avatar
dogmaphobic committed
328 329 330 331
        emit scanningChanged();
    }
}

332
void BluetoothConfiguration::setDevName(const QString &name)
dogmaphobic's avatar
dogmaphobic committed
333
{
334
    for(const BluetoothData& data: _deviceList)
dogmaphobic's avatar
dogmaphobic committed
335
    {
336 337 338 339
        if(data.name == name)
        {
            _device = data;
            emit devNameChanged();
dogmaphobic's avatar
dogmaphobic committed
340
#ifndef __ios__
341
            emit addressChanged();
dogmaphobic's avatar
dogmaphobic committed
342
#endif
343 344
            return;
        }
dogmaphobic's avatar
dogmaphobic committed
345 346 347
    }
}

dogmaphobic's avatar
dogmaphobic committed
348 349 350
QString BluetoothConfiguration::address()
{
#ifdef __ios__
351
    return {};
dogmaphobic's avatar
dogmaphobic committed
352 353 354 355
#else
    return _device.address;
#endif
}