BluetoothLink.cc 10 KB
Newer Older
dogmaphobic's avatar
dogmaphobic committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/*=====================================================================

QGroundControl Open Source Ground Control Station

(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QGROUNDCONTROL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @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/QBluetoothSocket>
#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QtBluetooth/QBluetoothUuid>

#include "BluetoothLink.h"
#include "QGC.h"

45
/*
dogmaphobic's avatar
dogmaphobic committed
46 47 48 49 50 51 52 53 54 55 56
static void print_device_info(QBluetoothDeviceInfo info)
{
    qDebug() << "Bluetooth:      " << info.name();
    qDebug() << "       Services:" << info.serviceClasses();
    qDebug() << "   Major Classs:" << info.majorDeviceClass();
    qDebug() << "   Minor Classs:" << info.minorDeviceClass();
    qDebug() << "           RSSI:" << info.rssi();
    qDebug() << "           UUID:" << info.deviceUuid();
    qDebug() << "   Service UUID:" << info.serviceUuids();
    qDebug() << "    Core Config:" << info.coreConfigurations();
    qDebug() << "          Valid:" << info.isValid();
57
    qDebug() << "        Address:" << info.address().toString();
dogmaphobic's avatar
dogmaphobic committed
58
}
59
*/
dogmaphobic's avatar
dogmaphobic committed
60 61 62 63 64 65 66 67 68 69 70 71

BluetoothLink::BluetoothLink(BluetoothConfiguration* config)
    : _connectState(false)
    , _targetSocket(NULL)
    , _targetDevice(NULL)
    , _running(false)
{
    Q_ASSERT(config != NULL);
    _config = config;
    _config->setLink(this);
    // We're doing it wrong - because the Qt folks got the API wrong:
    // http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
72
    moveToThread(this);
dogmaphobic's avatar
dogmaphobic committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
}

BluetoothLink::~BluetoothLink()
{
    // Disconnect link from configuration
    _config->setLink(NULL);
    _disconnect();
    // Tell the thread to exit
    _running = false;
    quit();
    // Wait for it to exit
    wait();
    this->deleteLater();
}

void BluetoothLink::run()
{
    if(_running && _hardwareConnect()) {
        exec();
    }
}

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

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

void BluetoothLink::writeBytes(const char* data, qint64 size)
{
    _sendBytes(data, size);
}

void BluetoothLink::_sendBytes(const char* data, qint64 size)
{
    if(_targetSocket)
    {
        if(_targetSocket->isWritable())
        {
            if(_targetSocket->write(data, size) > 0) {
                _logOutputDataRate(size, QDateTime::currentMSecsSinceEpoch());
            }
            else
                qWarning() << "Bluetooth write error";
        }
        else
            qWarning() << "Bluetooth not writable error";
    }
}

void BluetoothLink::readBytes()
{
    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());
    }
}

void BluetoothLink::_disconnect(void)
{
    _running = false;
    quit();
    wait();
    if(_targetDevice)
    {
        delete _targetDevice;
        _targetDevice = NULL;
    }
    if(_targetSocket)
    {
        _targetSocket->deleteLater();
        _targetSocket = NULL;
        emit disconnected();
    }
    _connectState = false;
}

bool BluetoothLink::_connect(void)
{
    if(this->isRunning() || _running)
    {
        _running = false;
        quit();
        wait();
    }
    if(_targetDevice)
    {
        delete _targetDevice;
        _targetDevice = NULL;
    }
175 176 177
    //-- Start Thread
    _running = true;
    start(NormalPriority);
dogmaphobic's avatar
dogmaphobic committed
178 179 180 181 182 183 184 185 186 187
    return true;
}

bool BluetoothLink::_hardwareConnect()
{
    if(_targetSocket)
    {
        delete _targetSocket;
        _targetSocket = NULL;
    }
188
    _targetDevice = new QBluetoothDeviceInfo(QBluetoothAddress(_config->device().address), _config->device().name, _config->device().bits);
dogmaphobic's avatar
dogmaphobic committed
189 190 191
    _targetDevice->setCoreConfigurations(QBluetoothDeviceInfo::BaseRateCoreConfiguration);
    _targetSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
    _targetSocket->moveToThread(this);
192
    //print_device_info(*_targetDevice);
dogmaphobic's avatar
dogmaphobic committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 241 242 243 244 245 246 247 248 249 250 251 252 253
    QObject::connect(_targetSocket, SIGNAL(connected()), this, SLOT(deviceConnected()));
    QObject::connect(_targetSocket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(deviceError(QBluetoothSocket::SocketError)));
    QObject::connect(_targetSocket, SIGNAL(readyRead()), this, SLOT(readBytes()));
    QObject::connect(_targetSocket, SIGNAL(disconnected()), this, SLOT(deviceDisconnected()));
    _targetSocket->connectToService(_targetDevice->address(), QBluetoothUuid(QBluetoothUuid::Rfcomm));
    return true;
}

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;
    emit communicationError("Bluetooth Link Error", _targetSocket->errorString());
}

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)
    , _deviceDiscover(NULL)
{

}

BluetoothConfiguration::BluetoothConfiguration(BluetoothConfiguration* source)
    : LinkConfiguration(source)
    , _deviceDiscover(NULL)
{
254
    _device = source->device();
dogmaphobic's avatar
dogmaphobic committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
}

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

void BluetoothConfiguration::copyFrom(LinkConfiguration *source)
{
    LinkConfiguration::copyFrom(source);
    BluetoothConfiguration* usource = dynamic_cast<BluetoothConfiguration*>(source);
    Q_ASSERT(usource != NULL);
271
    _device = usource->device();
dogmaphobic's avatar
dogmaphobic committed
272 273 274 275 276
}

void BluetoothConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
277 278 279
    settings.setValue("name",    _device.name);
    settings.setValue("address", _device.address);
    settings.setValue("bits",    _device.bits);
dogmaphobic's avatar
dogmaphobic committed
280 281 282 283 284 285
    settings.endGroup();
}

void BluetoothConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    settings.beginGroup(root);
286 287 288
    _device.name    = settings.value("name",    _device.name).toString();
    _device.address = settings.value("address", _device.address).toString();
    _device.bits    = settings.value("bits",    _device.bits).toUInt();
dogmaphobic's avatar
dogmaphobic committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    settings.endGroup();
}

void BluetoothConfiguration::updateSettings()
{
    if(_link) {
        BluetoothLink* ulink = dynamic_cast<BluetoothLink*>(_link);
        if(ulink) {
            ulink->_restartConnection();
        }
    }
}

void BluetoothConfiguration::stopScan()
{
    if(_deviceDiscover)
    {
306 307 308 309
        _deviceDiscover->stop();
        _deviceDiscover->deleteLater();
        _deviceDiscover = NULL;
        emit scanningChanged();
dogmaphobic's avatar
dogmaphobic committed
310 311 312 313 314 315 316 317
    }
}

void BluetoothConfiguration::startScan()
{
    if(!_deviceDiscover)
    {
        _deviceDiscover = new QBluetoothDeviceDiscoveryAgent(this);
318 319
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,  this, &BluetoothConfiguration::deviceDiscovered);
        connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::finished,          this, &BluetoothConfiguration::doneScanning);
dogmaphobic's avatar
dogmaphobic committed
320 321 322 323 324 325
        emit scanningChanged();
    }
    else
    {
        _deviceDiscover->stop();
    }
326
    _nameList.clear();
dogmaphobic's avatar
dogmaphobic committed
327
    _deviceList.clear();
328
    emit nameListChanged();
dogmaphobic's avatar
dogmaphobic committed
329 330 331 332 333 334
    _deviceDiscover->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
    _deviceDiscover->start();
}

void BluetoothConfiguration::deviceDiscovered(QBluetoothDeviceInfo info)
{
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    //print_device_info(info);
    if(!info.name().isEmpty() && info.isValid())
    {
        BluetoothData data;
        data.name    = info.name();
        data.address = info.address().toString();
        data.bits |= ((qint32)info.serviceClasses()   << 13);   // Service Class
        data.bits |= ((qint32)info.majorDeviceClass() << 8);    // CLASS MAJOR
        data.bits |= ((qint32)info.minorDeviceClass() << 2);    // CLASS MINOR
        if(!_deviceList.contains(data))
        {
            _deviceList += data;
            _nameList   += data.name;
            emit nameListChanged();
            return;
        }
    }
dogmaphobic's avatar
dogmaphobic committed
352 353 354 355 356 357 358 359 360 361 362 363
}

void BluetoothConfiguration::doneScanning()
{
    if(_deviceDiscover)
    {
        _deviceDiscover->deleteLater();
        _deviceDiscover = NULL;
        emit scanningChanged();
    }
}

364
void BluetoothConfiguration::setDevName(const QString &name)
dogmaphobic's avatar
dogmaphobic committed
365
{
366
    foreach(const BluetoothData& data, _deviceList)
dogmaphobic's avatar
dogmaphobic committed
367
    {
368 369 370 371 372 373 374
        if(data.name == name)
        {
            _device = data;
            emit devNameChanged();
            emit addressChanged();
            return;
        }
dogmaphobic's avatar
dogmaphobic committed
375 376 377
    }
}