BluetoothLink.cc 10.2 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * 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 19 20 21 22 23 24 25 26


/**
 * @file
 *   @brief Definition of Bluetooth connection for unmanned vehicles
 *   @author Gus Grubba <mavlink@grubba.com>
 *
 */

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

#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QtBluetooth/QBluetoothUuid>
dogmaphobic's avatar
dogmaphobic committed
27
#include <QtBluetooth/QBluetoothSocket>
dogmaphobic's avatar
dogmaphobic committed
28

29
#include "QGCApplication.h"
dogmaphobic's avatar
dogmaphobic committed
30 31 32
#include "BluetoothLink.h"
#include "QGC.h"

33 34
BluetoothLink::BluetoothLink(SharedLinkConfigurationPointer& config)
    : LinkInterface(config)
35
    , _config(qobject_cast<BluetoothConfiguration*>(config.data()))
36
    , _connectState(false)
37
    , _targetSocket(nullptr)
dogmaphobic's avatar
dogmaphobic committed
38
#ifdef __ios__
39
    , _discoveryAgent(nullptr)
dogmaphobic's avatar
dogmaphobic committed
40 41
#endif
    , _shutDown(false)
dogmaphobic's avatar
dogmaphobic committed
42
{
43

dogmaphobic's avatar
dogmaphobic committed
44 45 46 47 48
}

BluetoothLink::~BluetoothLink()
{
    _disconnect();
dogmaphobic's avatar
dogmaphobic committed
49 50 51 52 53
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
54
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
55 56
    }
#endif
dogmaphobic's avatar
dogmaphobic committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
}

void BluetoothLink::run()
{
}

void BluetoothLink::_restartConnection()
{
    if(this->isConnected())
    {
        _disconnect();
        _connect();
    }
}

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

77
void BluetoothLink::_writeBytes(const QByteArray bytes)
dogmaphobic's avatar
dogmaphobic committed
78
{
79 80
    if (_targetSocket) {
        if(_targetSocket->write(bytes) > 0) {
Pierre TILAK's avatar
Pierre TILAK committed
81
            emit bytesSent(this, bytes);
82 83 84
            _logOutputDataRate(bytes.size(), QDateTime::currentMSecsSinceEpoch());
        } else {
            qWarning() << "Bluetooth write error";
dogmaphobic's avatar
dogmaphobic committed
85 86 87 88 89 90
        }
    }
}

void BluetoothLink::readBytes()
{
91 92 93 94 95 96 97 98
    if (_targetSocket) {
        while (_targetSocket->bytesAvailable() > 0) {
            QByteArray datagram;
            datagram.resize(_targetSocket->bytesAvailable());
            _targetSocket->read(datagram.data(), datagram.size());
            emit bytesReceived(this, datagram);
            _logInputDataRate(datagram.length(), QDateTime::currentMSecsSinceEpoch());
        }
dogmaphobic's avatar
dogmaphobic committed
99 100 101 102 103
    }
}

void BluetoothLink::_disconnect(void)
{
dogmaphobic's avatar
dogmaphobic committed
104 105 106 107 108
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
109
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
110
    }
dogmaphobic's avatar
dogmaphobic committed
111
#endif
dogmaphobic's avatar
dogmaphobic committed
112 113
    if(_targetSocket)
    {
114
        _targetSocket->deleteLater();
115
        _targetSocket = nullptr;
dogmaphobic's avatar
dogmaphobic committed
116 117 118 119 120 121 122
        emit disconnected();
    }
    _connectState = false;
}

bool BluetoothLink::_connect(void)
{
dogmaphobic's avatar
dogmaphobic committed
123
    _hardwareConnect();
dogmaphobic's avatar
dogmaphobic committed
124 125 126 127
    return true;
}

bool BluetoothLink::_hardwareConnect()
dogmaphobic's avatar
dogmaphobic committed
128 129 130 131 132 133
{
#ifdef __ios__
    if(_discoveryAgent) {
        _shutDown = true;
        _discoveryAgent->stop();
        _discoveryAgent->deleteLater();
134
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
135 136
    }
    _discoveryAgent = new QBluetoothServiceDiscoveryAgent(this);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
137 138 139
    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
140 141 142 143
    _shutDown = false;
    _discoveryAgent->start();
#else
    _createSocket();
144
    _targetSocket->connectToService(QBluetoothAddress(_config->device().address), QBluetoothUuid(QBluetoothUuid::SerialPort));
dogmaphobic's avatar
dogmaphobic committed
145 146 147 148 149
#endif
    return true;
}

void BluetoothLink::_createSocket()
dogmaphobic's avatar
dogmaphobic committed
150 151 152 153
{
    if(_targetSocket)
    {
        delete _targetSocket;
154
        _targetSocket = nullptr;
dogmaphobic's avatar
dogmaphobic committed
155 156
    }
    _targetSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
157
    QObject::connect(_targetSocket, &QBluetoothSocket::connected, this, &BluetoothLink::deviceConnected);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
158

159 160
    QObject::connect(_targetSocket, &QBluetoothSocket::readyRead, this, &BluetoothLink::readBytes);
    QObject::connect(_targetSocket, &QBluetoothSocket::disconnected, this, &BluetoothLink::deviceDisconnected);
Tomaz Canabrava's avatar
Tomaz Canabrava committed
161 162 163

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

dogmaphobic's avatar
dogmaphobic committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
#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();
187
        _discoveryAgent = nullptr;
dogmaphobic's avatar
dogmaphobic committed
188 189 190 191 192 193 194 195 196
        if(!_targetSocket)
        {
            _connectState = false;
            emit communicationError("Could not locate Bluetooth device:", _config->device().name);
        }
    }
}
#endif

dogmaphobic's avatar
dogmaphobic committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
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;
213
    emit communicationError(tr("Bluetooth Link Error"), _targetSocket->errorString());
dogmaphobic's avatar
dogmaphobic committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
}

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

qint64 BluetoothLink::getConnectionSpeed() const
{
    return 1000000; // 1 Mbit
}

qint64 BluetoothLink::getCurrentInDataRate() const
{
    return 0;
}

qint64 BluetoothLink::getCurrentOutDataRate() const
{
    return 0;
}

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

BluetoothConfiguration::BluetoothConfiguration(const QString& name)
    : LinkConfiguration(name)
241
    , _deviceDiscover(nullptr)
dogmaphobic's avatar
dogmaphobic committed
242 243 244 245 246 247
{

}

BluetoothConfiguration::BluetoothConfiguration(BluetoothConfiguration* source)
    : LinkConfiguration(source)
248
    , _deviceDiscover(nullptr)
249
    , _device(source->device())
dogmaphobic's avatar
dogmaphobic committed
250 251 252 253 254 255 256 257 258 259 260 261
{
}

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

262 263 264 265 266 267 268 269 270
QString BluetoothConfiguration::settingsTitle()
{
    if(qgcApp()->toolbox()->linkManager()->isBluetoothAvailable()) {
        return tr("Bluetooth Link Settings");
    } else {
        return tr("Bluetooth Not Available");
    }
}

dogmaphobic's avatar
dogmaphobic committed
271 272 273
void BluetoothConfiguration::copyFrom(LinkConfiguration *source)
{
    LinkConfiguration::copyFrom(source);
274
    auto* usource = qobject_cast<BluetoothConfiguration*>(source);
275
    Q_ASSERT(usource != nullptr);
276
    _device = usource->device();
dogmaphobic's avatar
dogmaphobic committed
277 278 279 280 281
}

void BluetoothConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
dogmaphobic's avatar
dogmaphobic committed
282 283 284 285 286 287
    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
288 289 290 291 292 293
    settings.endGroup();
}

void BluetoothConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
dogmaphobic's avatar
dogmaphobic committed
294 295 296 297 298
    _device.name    = settings.value("deviceName", _device.name).toString();
#ifdef __ios__
    QString suuid   = settings.value("uuid", _device.uuid.toString()).toString();
    _device.uuid    = QUuid(suuid);
#else
299
    _device.address = settings.value("address", _device.address).toString();
dogmaphobic's avatar
dogmaphobic committed
300
#endif
dogmaphobic's avatar
dogmaphobic committed
301 302 303 304 305 306
    settings.endGroup();
}

void BluetoothConfiguration::updateSettings()
{
    if(_link) {
307
        auto* ulink = qobject_cast<BluetoothLink*>(_link);
dogmaphobic's avatar
dogmaphobic committed
308 309 310 311 312 313 314 315 316 317
        if(ulink) {
            ulink->_restartConnection();
        }
    }
}

void BluetoothConfiguration::stopScan()
{
    if(_deviceDiscover)
    {
318 319
        _deviceDiscover->stop();
        _deviceDiscover->deleteLater();
320
        _deviceDiscover = nullptr;
321
        emit scanningChanged();
dogmaphobic's avatar
dogmaphobic committed
322 323 324 325 326 327 328 329
    }
}

void BluetoothConfiguration::startScan()
{
    if(!_deviceDiscover)
    {
        _deviceDiscover = new QBluetoothDeviceDiscoveryAgent(this);
330 331
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,  this, &BluetoothConfiguration::deviceDiscovered);
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::finished,          this, &BluetoothConfiguration::doneScanning);
dogmaphobic's avatar
dogmaphobic committed
332 333 334 335 336 337
        emit scanningChanged();
    }
    else
    {
        _deviceDiscover->stop();
    }
338
    _nameList.clear();
dogmaphobic's avatar
dogmaphobic committed
339
    _deviceList.clear();
340
    emit nameListChanged();
dogmaphobic's avatar
dogmaphobic committed
341 342 343 344 345 346
    _deviceDiscover->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
    _deviceDiscover->start();
}

void BluetoothConfiguration::deviceDiscovered(QBluetoothDeviceInfo info)
{
347 348
    if(!info.name().isEmpty() && info.isValid())
    {
349 350 351 352 353
#if 0
        qDebug() << "Name:           " << info.name();
        qDebug() << "Address:        " << info.address().toString();
        qDebug() << "Service Classes:" << info.serviceClasses();
        QList<QBluetoothUuid> uuids = info.serviceUuids();
354
        for (QBluetoothUuid uuid: uuids) {
355 356 357
            qDebug() << "Service UUID:   " << uuid.toString();
        }
#endif
358 359
        BluetoothData data;
        data.name    = info.name();
dogmaphobic's avatar
dogmaphobic committed
360 361 362
#ifdef __ios__
        data.uuid    = info.deviceUuid();
#else
363
        data.address = info.address().toString();
dogmaphobic's avatar
dogmaphobic committed
364
#endif
365 366 367 368 369 370 371 372
        if(!_deviceList.contains(data))
        {
            _deviceList += data;
            _nameList   += data.name;
            emit nameListChanged();
            return;
        }
    }
dogmaphobic's avatar
dogmaphobic committed
373 374 375 376 377 378 379
}

void BluetoothConfiguration::doneScanning()
{
    if(_deviceDiscover)
    {
        _deviceDiscover->deleteLater();
380
        _deviceDiscover = nullptr;
dogmaphobic's avatar
dogmaphobic committed
381 382 383 384
        emit scanningChanged();
    }
}

385
void BluetoothConfiguration::setDevName(const QString &name)
dogmaphobic's avatar
dogmaphobic committed
386
{
387
    for(const BluetoothData& data: _deviceList)
dogmaphobic's avatar
dogmaphobic committed
388
    {
389 390 391 392
        if(data.name == name)
        {
            _device = data;
            emit devNameChanged();
dogmaphobic's avatar
dogmaphobic committed
393
#ifndef __ios__
394
            emit addressChanged();
dogmaphobic's avatar
dogmaphobic committed
395
#endif
396 397
            return;
        }
dogmaphobic's avatar
dogmaphobic committed
398 399 400
    }
}

dogmaphobic's avatar
dogmaphobic committed
401 402 403
QString BluetoothConfiguration::address()
{
#ifdef __ios__
404
    return {};
dogmaphobic's avatar
dogmaphobic committed
405 406 407 408
#else
    return _device.address;
#endif
}