diff options
author | Alex Blasche <alexander.blasche@digia.com> | 2014-05-26 14:56:49 +0200 |
---|---|---|
committer | Alex Blasche <alexander.blasche@digia.com> | 2014-05-26 14:56:49 +0200 |
commit | f334ea4b196950c4074e7513626aabeef3d99d7f (patch) | |
tree | ccb07d59afbb60a92b80a061645c8013aab9b96c /examples/bluetooth | |
parent | 3910d9ffcc11db7b3beb7f2b6f0c1754103cfacb (diff) | |
parent | 552f1a164d627720942414915fb56ae7d3b7ef22 (diff) |
Merge branch 'dev' into btle
Conflicts:
examples/bluetooth/bluetooth.pro
src/bluetooth/bluez/bluez.pri
src/bluetooth/doc/src/bluetooth-index.qdoc
src/bluetooth/qbluetoothdevicediscoveryagent_bluez.cpp
src/bluetooth/qbluetoothdeviceinfo.cpp
src/bluetooth/qbluetoothservicediscoveryagent_bluez.cpp
src/bluetooth/qbluetoothservicediscoveryagent_p.h
src/bluetooth/qbluetoothservicediscoveryagent_qnx.cpp
Change-Id: I88b22c51a4ee95b067ef8d2b2fddb5cbff4566f8
Diffstat (limited to 'examples/bluetooth')
45 files changed, 1256 insertions, 2607 deletions
diff --git a/examples/bluetooth/bluetooth.pro b/examples/bluetooth/bluetooth.pro index f7fe9d20..4576956f 100644 --- a/examples/bluetooth/bluetooth.pro +++ b/examples/bluetooth/bluetooth.pro @@ -2,11 +2,11 @@ TEMPLATE = subdirs qtHaveModule(widgets) { SUBDIRS += btchat \ btscanner \ - btfiletransfer \ - bttennis + btfiletransfer } qtHaveModule(quick): SUBDIRS += scanner \ picturetransfer \ + pingpong \ lowenergyscanner \ heartlistener diff --git a/examples/bluetooth/btchat/doc/src/btchat.qdoc b/examples/bluetooth/btchat/doc/src/btchat.qdoc index 77f73fd1..a78b9ede 100644 --- a/examples/bluetooth/btchat/doc/src/btchat.qdoc +++ b/examples/bluetooth/btchat/doc/src/btchat.qdoc @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt local connectivty modules. @@ -28,8 +28,9 @@ /*! \example btchat \title Bluetooth Chat Example + \brief An example showing communication through Bluetooth. - The Bluetooth Chat example shows how to use the Qt Connectivity Bluetooth API to communicate + The Bluetooth Chat example shows how to use the \l{Qt Bluetooth} API to communicate with another application on a remote device using Bluetooth. \image btchat-example.png @@ -38,6 +39,8 @@ application always acts as both a server and a client eliminating the need to determine who should connect to whom. + \include examples-run.qdocinc + \section1 Chat Server The chat server is implemented by the ChatServer class. The ChatServer class is declared as: diff --git a/examples/bluetooth/btchat/remoteselector.cpp b/examples/bluetooth/btchat/remoteselector.cpp index e6fd728f..79dc0564 100644 --- a/examples/bluetooth/btchat/remoteselector.cpp +++ b/examples/bluetooth/btchat/remoteselector.cpp @@ -75,7 +75,7 @@ void RemoteSelector::startDiscovery(const QBluetoothUuid &uuid) ui->remoteDevices->clear(); m_discoveryAgent->setUuidFilter(uuid); - m_discoveryAgent->start(); + m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery); } diff --git a/examples/bluetooth/btfiletransfer/doc/src/btfiletransfer.qdoc b/examples/bluetooth/btfiletransfer/doc/src/btfiletransfer.qdoc index aeeffffb..53832725 100644 --- a/examples/bluetooth/btfiletransfer/doc/src/btfiletransfer.qdoc +++ b/examples/bluetooth/btfiletransfer/doc/src/btfiletransfer.qdoc @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt local connectivty modules. @@ -28,6 +28,7 @@ /*! \example btfiletransfer \title Bluetooth File Transfer Example + \brief An example showing the use of Bluetooth Object Push Profile (OPP). The Bluetooth File Transfer example is an application to transfer files via a bluetooth connection. This example does not work on Android due to @@ -35,4 +36,8 @@ \image btfiletransfer-example.png + \include examples-run.qdocinc + + \sa {Qt Bluetooth} + */ diff --git a/examples/bluetooth/btfiletransfer/remoteselector.cpp b/examples/bluetooth/btfiletransfer/remoteselector.cpp index 53bf47f3..84619a4e 100644 --- a/examples/bluetooth/btfiletransfer/remoteselector.cpp +++ b/examples/bluetooth/btfiletransfer/remoteselector.cpp @@ -117,9 +117,14 @@ void RemoteSelector::startDiscovery(const QBluetoothUuid &uuid) m_discoveryAgent->setUuidFilter(uuid); m_discoveryAgent->start(); - ui->status->setText(tr("Scanning...")); - ui->busyWidget->show(); - ui->busyWidget->movie()->start(); + if (!m_discoveryAgent->isActive() || + m_discoveryAgent->error() != QBluetoothServiceDiscoveryAgent::NoError) { + ui->status->setText(tr("Cannot find remote services.")); + } else { + ui->status->setText(tr("Scanning...")); + ui->busyWidget->show(); + ui->busyWidget->movie()->start(); + } } QBluetoothServiceInfo RemoteSelector::service() const diff --git a/examples/bluetooth/btscanner/doc/src/btscanner.qdoc b/examples/bluetooth/btscanner/doc/src/btscanner.qdoc index e67b761a..e4d28ee2 100644 --- a/examples/bluetooth/btscanner/doc/src/btscanner.qdoc +++ b/examples/bluetooth/btscanner/doc/src/btscanner.qdoc @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt local connectivty modules. @@ -28,9 +28,14 @@ /*! \example btscanner \title Bluetooth Scanner Example + \brief An example showing how to locate Bluetooth devices. - An example of how to locate Bluetooth devices. + An example showing how to locate Bluetooth devices. \image btscanner-example.png + \include examples-run.qdocinc + + \sa {Qt Bluetooth} + */ diff --git a/examples/bluetooth/bttennis/board.cpp b/examples/bluetooth/bttennis/board.cpp deleted file mode 100644 index eb3c88d8..00000000 --- a/examples/bluetooth/bttennis/board.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "board.h" - -#include <QGraphicsItem> -#include <QGraphicsScene> -#include <QDebug> -#include <QTextDocument> -#include <QFontMetrics> -#include <QPropertyAnimation> - -const QColor fg = Qt::white; -const QColor bg = Qt::black; - -Board::Board(QWidget *parent) : - QGraphicsView(parent) -{ - scene = new QGraphicsScene(QRect(0, 0, 640, 360), this); - - scene->setBackgroundBrush(QBrush(bg)); - - ball = scene->addRect(-6, -6, 12, 12, QPen(Qt::SolidLine), QBrush(fg)); - ball->setPos(Width/2-6, Height/2-6); - - // why is y -1...otherwise we have a gap... - topWall = scene->addRect(0, -1, Width, 12, QPen(Qt::SolidLine), QBrush(fg)); - bottomWall = scene->addRect(0, Height-12, Width, 12, QPen(Qt::SolidLine), QBrush(fg)); - - leftPaddle = scene->addRect(0, 12, 12, Paddle, QPen(Qt::SolidLine), QBrush(fg)); - rightPaddle = scene->addRect(Width-12, 12, 12, Paddle, QPen(Qt::SolidLine), QBrush(fg)); - - QPen p; - p.setWidth(2); - p.setStyle(Qt::DotLine); - p.setBrush(QBrush(fg)); - scene->addLine(Width/2, 0, Width/2, Height, p); - - QFont f; - f.setStyleHint(QFont::OldEnglish); - f.setPixelSize(50); - f.setBold(true); - leftScore = scene->addText(QString("0"), f); - leftScore->setDefaultTextColor(fg); -// leftScore->setPos(120, 50); - - rightScore = scene->addText(QString("0"), f); -// rightScore->setPos(Width-140, 50); - rightScore->setDefaultTextColor(fg); - setScore(0, 0); - - f.setPixelSize(25); - status = scene->addText(QString(), f); - status->setDefaultTextColor(fg); - - ball->setCacheMode(QGraphicsItem::DeviceCoordinateCache); - leftPaddle->setCacheMode(QGraphicsItem::DeviceCoordinateCache); - rightPaddle->setCacheMode(QGraphicsItem::DeviceCoordinateCache); - - icon.load(QString(":/icons/connect.png")); - icon = icon.scaled(100, 100, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - qDebug() << "icon" << icon.isNull(); - connectIcon = scene->addPixmap(icon); - connectIcon->setPos(440,200); - connectIcon->setAcceptTouchEvents(true); - connectIcon->setTransformOriginPoint(50,50); - connectIcon->setTransformationMode(Qt::SmoothTransformation); - - connectAnimation = new QPropertyAnimation(this, "connectRotation"); - connectAnimation->setDuration(1000); - connectAnimation->setLoopCount(-1); - connectAnimation->setStartValue(0); - connectAnimation->setEndValue(360); - - setCacheMode(QGraphicsView::CacheBackground); - setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); - -// connect(scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(sceneChanged(QList<QRectF>))); - -} -void Board::setBall(int x, int y) -{ - ball->setPos(x, y); - checkBall(x, y); -} - -void Board::setLeftPaddle(int y) -{ - leftPaddle->setPos(0, y); -} - -void Board::setRightPaddle(int y) -{ - rightPaddle->setPos(0, y); -} - -void Board::sceneChanged(const QList<QRectF> ®ion) -{ - Q_UNUSED(region); - - QList<QGraphicsItem *>items = scene->collidingItems(ball); - while (!items.empty()) { - QGraphicsItem *i = items.takeFirst(); - if (i == topWall) - emit ballCollision(Top); - if (i == bottomWall) - emit ballCollision(Bottom); - if (i == leftPaddle) - emit ballCollision(Left); - if (i == rightPaddle) - emit ballCollision(Right); - } - -} - -void Board::checkBall(int x, int y) -{ - int ly = leftPaddle->y(); - int ry = rightPaddle->y(); - - if (x > 646) - emit scored(Right); - else if (x < -6) - emit scored(Left); - - if (y < 18) - emit ballCollision(Top); - else if (y > 360-18) - emit ballCollision(Bottom); - - if ((x < 18) && - (y > ly-6) && - (y < ly+Paddle+6)) - emit ballCollision(Left); - - if ((x > 640-18) && - (y > ry-6) && - (y < ry+Paddle+6)) - emit ballCollision(Right); -} - -void Board::setScore(int l, int r) -{ - QString left = QString("%1").arg(l); - QString right = QString("%1").arg(r); - leftScore->document()->setPlainText(left); - rightScore->document()->setPlainText(right); - QFontMetrics fm(leftScore->font()); - leftScore->setPos(Width/4 - fm.width(left)/2, 50); - rightScore->setPos(3*Width/4 - fm.width(right)/2, 50); - -} - -void Board::setStatus(QString text, int opacity_start, int opacity_end) -{ - - status->document()->setPlainText(text); - status->setPos(24, Height-25-25); - QPropertyAnimation *a = new QPropertyAnimation(status, "opacity"); - a->setDuration(2000); - a->setStartValue(opacity_start/100.0); - a->setEndValue(opacity_end/100.0); - a->start(QAbstractAnimation::DeleteWhenStopped); -} - -void Board::setConnectRotation(int rot) -{ - connectIcon->setRotation(rot); -// QTransform t; -// t.rotate(rot); -// connectIcon->setPixmap(icon.scaled(100, 100).transformed(t, Qt::SmoothTransformation)); -} - -void Board::setConnectOpacity(qreal op) -{ - connectIcon->setOpacity(op); -} - -void Board::animateConnect(bool start) -{ - if (start) { - connectAnimation->start(); - } - else { - connectAnimation->stop(); - QPropertyAnimation *a = new QPropertyAnimation(this, "connectRotation"); -// qDebug() << "currentTime" << connectAnimation->currentLoopTime() << "rotation" << connectAnimation->currentValue(); - a->setDuration(connectAnimation->currentLoopTime()/2); - a->setStartValue(connectAnimation->currentValue().toInt( )); - a->setEndValue(0); -// a->setDirection(QAbstractAnimation::Backward); - a->start(QAbstractAnimation::DeleteWhenStopped); - } -} - - -void Board::fadeConnect(bool out) -{ - qreal start = 100.0; - qreal end = 0.0; - - if (!out) { - start = 0.0; - end = 100.0; - } - - QPropertyAnimation *a = new QPropertyAnimation(this, "connectOpacity"); - a->setDuration(2000); - a->setStartValue(start); - a->setEndValue(end); - a->start(QAbstractAnimation::DeleteWhenStopped); -} diff --git a/examples/bluetooth/bttennis/board.h b/examples/bluetooth/bttennis/board.h deleted file mode 100644 index d94a5b21..00000000 --- a/examples/bluetooth/bttennis/board.h +++ /dev/null @@ -1,126 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BOARD_H -#define BOARD_H - -#include <QObject> -#include <QGraphicsScene> -#include <QGraphicsView> -#include <QGraphicsPixmapItem> -#include <QPixmap> -#include <QPropertyAnimation> - -class Board : public QGraphicsView -{ - Q_OBJECT - Q_PROPERTY(int connectRotation READ connectRotation WRITE setConnectRotation) - Q_PROPERTY(qreal connectOpacity READ connectOpacity WRITE setConnectOpacity) -public: - explicit Board(QWidget *parent = 0); - - enum Edge { - Top = 1, - Bottom, - Left, - Right - }; - - enum BoardSize { - Width = 640, - Height = 360, - Paddle = 50 - }; - - - QGraphicsScene *getScene() { - return scene; - } - - int connectRotation(){ - return connectIcon->rotation(); - } - - qreal connectOpacity(){ - return connectIcon->opacity(); - } - - void setConnectRotation(int rot); - void setConnectOpacity(qreal op); - -signals: - void ballCollision(Board::Edge pos); - void scored(Board::Edge pos); - -public slots: - void setBall(int x, int y); - void setLeftPaddle(int y); - void setRightPaddle(int y); - void setScore(int l, int r); - - void setStatus(QString text, int opacity_start, int opacity_end); - - void sceneChanged(const QList<QRectF> ®ion); - - void animateConnect(bool start = true); - void fadeConnect(bool out = true); - -private: - QGraphicsScene *scene; - QGraphicsRectItem *ball; - QGraphicsRectItem *topWall; - QGraphicsRectItem *bottomWall; - QGraphicsRectItem *leftPaddle; - QGraphicsRectItem *rightPaddle; - - QGraphicsTextItem *leftScore; - QGraphicsTextItem *rightScore; - - QGraphicsTextItem *status; - - QPixmap icon; - QGraphicsPixmapItem *connectIcon; - QPropertyAnimation *connectAnimation; - - void checkBall(int x, int y); -}; - -#endif // BOARD_H diff --git a/examples/bluetooth/bttennis/bttennis.pro b/examples/bluetooth/bttennis/bttennis.pro deleted file mode 100644 index 1c014784..00000000 --- a/examples/bluetooth/bttennis/bttennis.pro +++ /dev/null @@ -1,36 +0,0 @@ -TEMPLATE = app -TARGET = bttennis - -QT = core bluetooth widgets -#QT += nfc - -SOURCES = \ - main.cpp \ - board.cpp \ - tennis.cpp \ - controller.cpp \ - tennisserver.cpp \ - tennisclient.cpp \ - tennisview.cpp -# handover.cpp - -HEADERS = \ - board.h \ - tennis.h \ - controller.h \ - tennisserver.h \ - tennisclient.h \ - tennisview.h -# handover.h - -FORMS = \ - tennis.ui - -RESOURCES += \ - tennis.qrc - -OTHER_FILES = \ - connect.png - -target.path = $$[QT_INSTALL_EXAMPLES]/bluetooth/bttennis -INSTALLS += target diff --git a/examples/bluetooth/bttennis/connect.png b/examples/bluetooth/bttennis/connect.png Binary files differdeleted file mode 100644 index 70b64c6c..00000000 --- a/examples/bluetooth/bttennis/connect.png +++ /dev/null diff --git a/examples/bluetooth/bttennis/controller.cpp b/examples/bluetooth/bttennis/controller.cpp deleted file mode 100644 index 95163e66..00000000 --- a/examples/bluetooth/bttennis/controller.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "controller.h" - -#include <QDateTime> -#include <QDebug> - -#define FRAME_RATE 60 - -Controller::Controller(QObject *parent) : - QObject(parent), timer(new QTimer), elapsed(new QTime), score_left(0), score_right(0), - col_x(0), col_y(0), - rightPaddleForce(0), leftPaddleForce(0), - rightPaddleLast(0), leftPaddleLast(0), - rightPowerUp(0), leftPowerUp(0) -{ - - qsrand(QDateTime::currentDateTime().time().msec()); - - - timer->setInterval(1000/FRAME_RATE); -// timer->setInterval(0); - connect(timer, SIGNAL(timeout()), SLOT(tick())); - srand(QDateTime::currentDateTime().time().msec()); - - fpscntr = new QTime; - frames = 0; - - timer->start(); - restart_ball(); -} - -void Controller::tick() -{ - if (col_x) - col_x--; - if (col_y) - col_y--; - -// frames++; -// if (fpscntr->elapsed() > 1000){ -// int f = frames/(fpscntr->elapsed()/1000.0); -// emit fps(QString("FPS %1").arg(f)); -// frames = 0; -// fpscntr->restart(); -// } - - int msec = elapsed->elapsed(); - elapsed->restart(); - - ball_x += speed_x*msec/1000; - ball_y += speed_y*msec/1000; - - - const int decay = 5; - - if (leftPaddleForce > decay) - leftPaddleForce-=decay; - else if (leftPaddleForce < -decay) - leftPaddleForce+=decay; - if (rightPaddleForce > decay) - rightPaddleForce-=decay; - else if (rightPaddleForce < -decay) - rightPaddleForce+=decay; - - if (rightPaddleForce <= decay) - rightPowerUp++; - - if (leftPaddleForce <= decay) - leftPowerUp++; - - -// ttf++; -// if (msec > 1000/FRAME_RATE+2 || msec < 1000/FRAME_RATE-2) -// dev++; - -// if (!(i++%120)) { -// qDebug() << "powerUp: " << leftPowerUp << rightPowerUp << leftPaddleForce << rightPaddleForce << speed_x*msec/1000 << speed_y*msec/1000 << msec << dev; -// ttf = dev =0; -// } - - emit moveBall(ball_x, ball_y); -} - - -static inline int paddle_boost(int force){ - if (force > 30) - return -3*FRAME_RATE; - else if (force > 20) - return -2*FRAME_RATE; - else if (force > 6) - return -1*FRAME_RATE; - else if (force < -30) - return 3*FRAME_RATE; - else if (force < -20) - return 2*FRAME_RATE; - else if (force < -6) - return 1*FRAME_RATE; - return 0; -} - -void Controller::ballCollision(Board::Edge pos) -{ - - if ((pos == Board::Top || pos == Board::Bottom) && !col_y) { - speed_y *= -1; - col_y = 10; - } - - if (pos == Board::Left && !col_x) { - speed_x *= -1; - speed_y += paddle_boost(leftPaddleForce); - col_x = 10; - - if (leftPowerUp > 75 && speed_x < 8*FRAME_RATE){ - speed_x *= 2; - leftPowerUp = 0; - } - } - else if (pos == Board::Right && !col_x) { - speed_x *= -1; - speed_y += paddle_boost(rightPaddleForce); - col_x = 10; - - if (rightPowerUp > 75 && speed_x > -8*FRAME_RATE){ - speed_x *= 2; - rightPowerUp = 0; - } - - } -// tick(); -// QMetaObject::invokeMethod(this, "moveBall", Qt::QueuedConnection, Q_ARG(int, ball_x), Q_ARG(int, ball_y)); -// emit moveBall(ball_x, ball_y); - -} - -void Controller::scored(Board::Edge pos) -{ - if (!timer->isActive()) - return; - - if (pos == Board::Left) - emit score(score_left, ++score_right); - else if (pos == Board::Right) - emit score(++score_left, score_right); - - restart_ball(); -} - -void Controller::restart_ball() -{ - if (!timer->isActive()) - return; - - elapsed->start(); - - ball_x = Board::Width/2; - ball_y = Board::Height/2; - -// ball_y = (qrand()%(Board::Height/2))+Board::Height/4; - ball_y = (qrand()%(Board::Height-48))+24; - - // Speed in in pixels/second - - const int max = 4*FRAME_RATE; - const int min_x = 2*FRAME_RATE; - const int min_y = 1.5*FRAME_RATE; - - - speed_y = min_y+qrand()%(max-min_y); - if (speed_y%2) - speed_y *= -1; - - - speed_x = min_x+qrand()%(max-min_y); - if (speed_x%2) - speed_x *= -1; - - leftPowerUp = rightPowerUp = 0; - - emit moveBall(ball_x, ball_y); -} - - -void Controller::resetBoard() -{ - if (!timer->isActive()) - return; - - score_left = score_right = 0; - restart_ball(); -} - -void Controller::stop() -{ - timer->stop(); -} - -void Controller::start() -{ - timer->start(); - fpscntr->restart(); - frames = 0; -} - -void Controller::moveLeftPaddle(int y) -{ - leftPaddleForce += leftPaddleLast-y; - leftPaddleLast = y; - leftPowerUp = 0; -} - -void Controller::moveRightPaddle(int y) -{ - rightPaddleForce += rightPaddleLast-y; - rightPaddleLast =y; - rightPowerUp = 0; -} - -void Controller::refresh() -{ - emit moveBall(ball_x, ball_y); - emit score(score_left, score_right); -} diff --git a/examples/bluetooth/bttennis/controller.h b/examples/bluetooth/bttennis/controller.h deleted file mode 100644 index 5146ce43..00000000 --- a/examples/bluetooth/bttennis/controller.h +++ /dev/null @@ -1,100 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CONTROLLER_H -#define CONTROLLER_H - -#include <QObject> -#include <QTimer> -#include <QTime> -#include "board.h" - -class Controller : public QObject -{ - Q_OBJECT -public: - explicit Controller(QObject *parent = 0); - -signals: - void moveBall(int x, int y); - void score(int left, int right); - void fps(const QString &str); - -public slots: - void ballCollision(Board::Edge pos); - void scored(Board::Edge pos); - void resetBoard(); - void refresh(); - - void moveLeftPaddle(int y); - void moveRightPaddle(int y); - - void tick(); - - void start(); - void stop(); - -private: - QTimer *timer; - QTime *elapsed; - QTime *fpscntr; - int frames; - int ball_x; - int speed_x; - int ball_y; - int speed_y; - int score_left; - int score_right; - int col_x; - int col_y; - - int rightPaddleForce; - int leftPaddleForce; - int rightPaddleLast; - int leftPaddleLast; - int rightPowerUp; - int leftPowerUp; - - void restart_ball(); - -}; - -#endif // CONTROLLER_H diff --git a/examples/bluetooth/bttennis/doc/images/bttennis-example.png b/examples/bluetooth/bttennis/doc/images/bttennis-example.png Binary files differdeleted file mode 100644 index 53a5486b..00000000 --- a/examples/bluetooth/bttennis/doc/images/bttennis-example.png +++ /dev/null diff --git a/examples/bluetooth/bttennis/doc/src/bttennis.qdoc b/examples/bluetooth/bttennis/doc/src/bttennis.qdoc deleted file mode 100644 index 136b181d..00000000 --- a/examples/bluetooth/bttennis/doc/src/bttennis.qdoc +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the documentation of the Qt local connectivty modules. -** -** $QT_BEGIN_LICENSE:FDL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Free Documentation License Usage -** Alternatively, this file may be used under the terms of the GNU Free -** Documentation License version 1.3 as published by the Free Software -** Foundation and appearing in the file included in the packaging of -** this file. Please review the following information to ensure -** the GNU Free Documentation License version 1.3 requirements -** will be met: http://www.gnu.org/copyleft/fdl.html. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example bttennis - \title Bluetooth Tennis Example - - The Bluetooth Tennis example shows how to use the Qt Connectivity Bluetooth API - to implement real-time data transfer for interactive applications. The example - establishes a \l {QBluetoothServiceInfo::L2capProtocol}{L2CP} socket connection. - Since this protocol type is not supported on Android and BlackBerry the example - does not work on those platforms. - - \image bttennis-example.png - -*/ diff --git a/examples/bluetooth/bttennis/handover.cpp b/examples/bluetooth/bttennis/handover.cpp deleted file mode 100644 index dbd6cdb4..00000000 --- a/examples/bluetooth/bttennis/handover.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "handover.h" - -#include <qnearfieldmanager.h> -#include <qllcpserver.h> -#include <qllcpsocket.h> -#include <qbluetoothlocaldevice.h> - -#include <QtCore/QStringList> - -static const QLatin1String tennisUri("urn:nfc:sn:com.nokia.qtnfc.tennis"); - -Handover::Handover(quint16 serverPort, QObject *parent) -: QObject(parent), m_server(new QLlcpServer(this)), - m_client(new QLlcpSocket(this)), m_remote(0), m_serverPort(0), m_localServerPort(serverPort) -{ - connect(m_server, SIGNAL(newConnection()), this, SLOT(handleNewConnection())); - m_server->listen(tennisUri); - - connect(m_client, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); - connect(m_client, SIGNAL(readyRead()), this, SLOT(readBluetoothService())); - - m_client->connectToService(0, tennisUri); -} - -Handover::~Handover() -{ -} - -QBluetoothAddress Handover::bluetoothAddress() const -{ - return m_address; -} - -quint16 Handover::serverPort() const -{ - return m_serverPort; -} - -void Handover::handleNewConnection() -{ - if (m_remote) - m_remote->deleteLater(); - - m_remote = m_server->nextPendingConnection(); - - connect(m_remote, SIGNAL(disconnected()), this, SLOT(remoteDisconnected())); - - sendBluetoothService(); -} - -void Handover::remoteDisconnected() -{ - m_remote->deleteLater(); - m_remote = 0; -} - -void Handover::clientDisconnected() -{ - m_client->connectToService(0, tennisUri); -} - -void Handover::readBluetoothService() -{ - QByteArray rawData = m_client->readAll(); - QString data = QString::fromUtf8(rawData.constData(), rawData.size()); - QStringList split = data.split(QLatin1Char(' ')); - - QBluetoothAddress address = QBluetoothAddress(split.at(0)); - quint16 port = split.at(1).toUInt(); - - QBluetoothLocalDevice localDevice; - QBluetoothAddress localAddress = localDevice.address(); - - if (localAddress < address) { - m_address = address; - m_serverPort = port; - emit bluetoothServiceChanged(); - } -} - -void Handover::sendBluetoothService() -{ - QBluetoothLocalDevice localDevice; - const QString data = localDevice.address().toString() + QLatin1Char(' ') + - QString::number(m_localServerPort); - - m_remote->write(data.toUtf8()); -} - diff --git a/examples/bluetooth/bttennis/handover.h b/examples/bluetooth/bttennis/handover.h deleted file mode 100644 index 52d2fba6..00000000 --- a/examples/bluetooth/bttennis/handover.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef HANDOVER_H -#define HANDOVER_H - -#include <QtCore/QObject> - -#include <qbluetoothaddress.h> -#include <qbluetoothuuid.h> -#include <qnfcglobal.h> - -QT_FORWARD_DECLARE_CLASS(QNearFieldManager) -QT_FORWARD_DECLARE_CLASS(QNearFieldTarget) -QT_FORWARD_DECLARE_CLASS(QLlcpServer) -QT_FORWARD_DECLARE_CLASS(QLlcpSocket) - -QT_USE_NAMESPACE - -class Handover : public QObject -{ - Q_OBJECT - -public: - explicit Handover(quint16 serverPort, QObject *parent = 0); - ~Handover(); - - QBluetoothAddress bluetoothAddress() const; - quint16 serverPort() const; - -private slots: - void handleNewConnection(); - void remoteDisconnected(); - - void clientDisconnected(); - - void readBluetoothService(); - void sendBluetoothService(); - -signals: - void bluetoothServiceChanged(); - -private: - QLlcpServer *m_server; - QLlcpSocket *m_client; - QLlcpSocket *m_remote; - - QBluetoothAddress m_address; - quint16 m_serverPort; - quint16 m_localServerPort; -}; - -#endif // HANDOVER_H diff --git a/examples/bluetooth/bttennis/main.cpp b/examples/bluetooth/bttennis/main.cpp deleted file mode 100644 index c90807bd..00000000 --- a/examples/bluetooth/bttennis/main.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tennis.h" - -#include <QApplication> - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - Tennis d; - QObject::connect(&d, SIGNAL(accepted()), &app, SLOT(quit())); - - d.show(); - - app.exec(); - - return 0; -} - diff --git a/examples/bluetooth/bttennis/tennis.cpp b/examples/bluetooth/bttennis/tennis.cpp deleted file mode 100644 index acb58938..00000000 --- a/examples/bluetooth/bttennis/tennis.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tennis.h" - -#include <QTimer> -#include <QKeyEvent> -#include <QMouseEvent> - -#include <QDebug> - -#include <QSettings> -#include <QEvent> -#include <QResizeEvent> - -#include "tennisserver.h" -#include "tennisclient.h" -//#include "handover.h" - -#include <qbluetooth.h> -#include <qbluetoothdeviceinfo.h> -#include <qbluetoothsocket.h> -#include <qbluetoothservicediscoveryagent.h> -#include <qbluetoothlocaldevice.h> - -//#include <qnearfieldmanager.h> -//#include <qllcpserver.h> -//#include <qllcpsocket.h> - -Tennis::Tennis(QWidget *parent) -: QDialog(parent), ui(new Ui_Tennis), board(new Board), controller(new Controller), socket(0) - //, m_handover(0) -{ - // start Bluetooth if not started - QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); - device->powerOn(); - delete device; - device = 0; - - //Using default Bluetooth adapter - QBluetoothLocalDevice localDevice; - QBluetoothAddress adapterAddress = localDevice.address(); - - /* - * In case of multiple Bluetooth adapters it is possible to - * set which adapter will be used by providing MAC Address. - * Example code: - * - * QBluetoothAddress adapterAddress("XX:XX:XX:XX:XX:XX"); - * m_discoveryAgent = new QBluetoothServiceDiscoveryAgent(adapterAddress); - */ - - m_discoveryAgent = new QBluetoothServiceDiscoveryAgent(adapterAddress, this); - - //! [Construct UI] - ui->setupUi(this); - - isClient = false; - isConnected = false; - quickDiscovery = true; - - ui->pongView->setScene(board->getScene()); - - connect(ui->pongView, SIGNAL(mouseMove(int,int)), this, SLOT(mouseMove(int,int))); - ui->pongView->setMouseTracking(false); - - connect(board, SIGNAL(ballCollision(Board::Edge)), controller, SLOT(ballCollision(Board::Edge))); - connect(board, SIGNAL(scored(Board::Edge)), controller, SLOT(scored(Board::Edge))); - connect(controller, SIGNAL(moveBall(int,int)), board, SLOT(setBall(int,int))); - connect(this, SIGNAL(moveLeftPaddle(int)), board, SLOT(setLeftPaddle(int))); - connect(this, SIGNAL(moveRightPaddle(int)), board, SLOT(setRightPaddle(int))); - connect(controller, SIGNAL(score(int,int)), board, SLOT(setScore(int,int))); - connect(controller, SIGNAL(fps(QString)), this, SLOT(fps(QString))); - - setFocusPolicy(Qt::WheelFocus); - - paddle_pos = (Board::Height-12)/2-Board::Paddle/2; - endPaddlePos = paddle_pos; - - emit moveLeftPaddle(paddle_pos); - board->setRightPaddle(paddle_pos); - - server = new TennisServer(this); - - connect(controller, SIGNAL(moveBall(int,int)), server, SLOT(moveBall(int,int))); - connect(controller, SIGNAL(score(int,int)), server, SLOT(score(int,int))); - connect(this, SIGNAL(moveLeftPaddle(int)), server, SLOT(moveLeftPaddle(int))); - connect(server, SIGNAL(clientConnected(QString)), this, SLOT(serverConnected(QString))); - connect(server, SIGNAL(clientDisconnected(QString)), this, SLOT(serverDisconnected())); - connect(server, SIGNAL(moveRightPaddle(int)), board, SLOT(setRightPaddle(int))); - connect(server, SIGNAL(lag(int)), this, SLOT(lagReport(int))); - - connect(server, SIGNAL(clientConnected(QString)), controller, SLOT(refresh())); - - server->startServer(); - - client = new TennisClient(this); - - connect(client, SIGNAL(moveBall(int,int)), board, SLOT(setBall(int,int))); - connect(client, SIGNAL(moveLeftPaddle(int)), board, SLOT(setLeftPaddle(int))); - connect(client, SIGNAL(connected(QString)), this, SLOT(clientConnected(QString))); - connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); - connect(this, SIGNAL(moveRightPaddle(int)), client, SLOT(moveRightPaddle(int))); - connect(client, SIGNAL(score(int,int)), board, SLOT(setScore(int,int))); - connect(client, SIGNAL(lag(int)), this, SLOT(lagReport(int))); - - connect(this, SIGNAL(moveLeftPaddle(int)), controller, SLOT(moveLeftPaddle(int))); - connect(this, SIGNAL(moveRightPaddle(int)), controller, SLOT(moveRightPaddle(int))); - connect(server, SIGNAL(moveRightPaddle(int)), controller, SLOT(moveRightPaddle(int))); - - -// ui->pongView->setBackgroundBrush(QBrush(Qt::white)); - ui->pongView->setCacheMode(QGraphicsView::CacheBackground); - -/* QNearFieldManager nearFieldManager; - if (nearFieldManager.isAvailable()) { - m_handover = new Handover(server->serverPort(), this); - connect(m_handover, SIGNAL(bluetoothServiceChanged()), this, SLOT(nearFieldHandover())); - - connect(m_discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)), - this, SLOT(serviceDiscovered(QBluetoothServiceInfo))); - connect(m_discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished())); - }*/ - - - m_discoveryAgent->setUuidFilter(QBluetoothUuid(serviceUuid)); - - - QString address; - QString port; - QStringList args = QCoreApplication::arguments(); - if (args.length() >= 2){ - address = args.at(1); - if (args.length() >= 3){ - port = args.at(2); - } - } - - if (address.isEmpty()){ - QSettings settings("QtDF", "bttennis"); - address = settings.value("lastclient").toString(); - } - - if (!address.isEmpty()){ - qDebug() << "Connect to" << address << port; - QBluetoothDeviceInfo device = QBluetoothDeviceInfo(QBluetoothAddress(address), "", QBluetoothDeviceInfo::ComputerDevice); - QBluetoothServiceInfo service; - if (!port.isEmpty()) { - QBluetoothServiceInfo::Sequence protocolDescriptorList; - QBluetoothServiceInfo::Sequence protocol; - protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap)) - << QVariant::fromValue(port.toUShort()); - protocolDescriptorList.append(QVariant::fromValue(protocol)); - service.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, - protocolDescriptorList); - qDebug() << "port" << port.toUShort() << service.protocolServiceMultiplexer(); - } - else { - service.setServiceUuid(QBluetoothUuid(serviceUuid)); - } - service.setDevice(device); - client->startClient(service); - board->setStatus("Connecting", 100, 25); - } /*else if (nearFieldManager.isAvailable()) { - board->setStatus(tr("Touch to play"), 100, 25); - }*/ - - setEnabled(true); - - paddleAnimation = new QPropertyAnimation(this, "paddlePos", this); - paddleAnimation->setEasingCurve(QEasingCurve::InOutQuad); - - ui->pongView->installEventFilter(this); - -} - -Tennis::~Tennis() -{ -} - -void Tennis::keyPressEvent(QKeyEvent *event) -{ - if (event->matches(QKeySequence::MoveToNextLine)) { - moveDown(); - } - else if (event->matches(QKeySequence::MoveToPreviousLine)){ - moveUp(); - } -} - -void Tennis::wheelEvent(QWheelEvent *event) -{ - if (event->delta() > 0){ - moveUp(); - } - else { - moveDown(); - } -} - -void Tennis::moveUp(int px) -{ - endPaddlePos -= px; - if (endPaddlePos <= 0) - endPaddlePos = 0; - move(endPaddlePos); -} - -void Tennis::moveDown(int px) -{ - endPaddlePos += px; - if (endPaddlePos > Board::Height-Board::Paddle-24) - endPaddlePos = Board::Height-Board::Paddle-24; - move(endPaddlePos); - -} - -void Tennis::move(int px) -{ - int distance = abs(paddle_pos - endPaddlePos); - - paddleAnimation->stop(); - paddleAnimation->setStartValue(paddle_pos); - paddleAnimation->setEndValue(px); - paddleAnimation->setDuration((1000*distance)/350); - paddleAnimation->start(); -} - -void Tennis::setPaddlePos(int p) -{ - paddle_pos = p; - if (isClient) - emit moveRightPaddle(paddle_pos); - else - emit moveLeftPaddle(paddle_pos); -} - - -void Tennis::mouseMove(int x, int y) -{ - if (isConnected == false){ - // look for clicks in the bt connect icon - if (x > 440 && x < 540 && y > 200 && y < 300) { - qDebug() << "Got connect click!"; - if (m_discoveryAgent->isActive()) { - qDebug() << "stopping!"; - m_discoveryAgent->stop(); - board->animateConnect(false); - } - else { - qDebug() << "starting!"; - startDiscovery(); - } - } - - } - y-=12+Board::Paddle/2; - if (y <= 0) - y = 0; - else if (y > Board::Height-Board::Paddle-24) - y = Board::Height-Board::Paddle-24; - - endPaddlePos = y; - move(y); -} - -void Tennis::clientConnected(const QString &name) -{ - board->setStatus("Connected to " + name, 100, 0); - controller->stop(); - server->stopServer(); - isClient = true; - isConnected = true; - board->animateConnect(false); - board->fadeConnect(true); - emit moveRightPaddle(paddle_pos); -} - -void Tennis::clientDisconnected() -{ - board->setStatus("Disconnect", 100, 25); - controller->start(); - server->startServer(); - client->stopClient(); - isClient = false; - isConnected = false; - discoveryFinished(); -} - -void Tennis::serverConnected(const QString &name) -{ - board->setStatus("Server for " + name, 100, 0); - m_discoveryAgent->stop(); - isConnected = true; - board->animateConnect(false); - board->fadeConnect(true); - emit moveLeftPaddle(paddle_pos); -} - -void Tennis::serverDisconnected() -{ - board->setStatus("Disconnected", 100, 25); - isConnected = false; - discoveryFinished(); -} - -void Tennis::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo) -{ - qDebug() << "***** Discovered! " << serviceInfo.device().name() << serviceInfo.serviceName() << serviceInfo.serviceUuid(); - qDebug() << "Found one!" << serviceInfo.protocolServiceMultiplexer(); - m_discoveryAgent->stop(); - client->startClient(serviceInfo); - QSettings settings("QtDF", "bttennis"); - settings.setValue("lastclient", serviceInfo.device().address().toString()); -} - -void Tennis::discoveryFinished() -{ - if (!m_discoveryAgent->isActive()) { - if (!isConnected) { - board->setStatus("Waiting", 100, 25); - // QTimer::singleShot(60000, this, SLOT(startDiscovery())); - board->animateConnect(false); - board->fadeConnect(false); - } - } -} - -void Tennis::startDiscovery() -{ - qDebug() << "startDiscovery() called"; - if (!isConnected) { - qDebug() << "Scanning!"; - board->setStatus("Scanning", 100, 25); - board->fadeConnect(false); - board->animateConnect(true); - m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::MinimalDiscovery); -// if (quickDiscovery) -// m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::MinimalDiscovery); -// else -// m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery); -// quickDiscovery = !quickDiscovery; - } - else { - qDebug() << "Stop scanning!"; - board->setStatus("", 0, 0); - board->animateConnect(false); - board->fadeConnect(true); - } -} - -void Tennis::resizeEvent(QResizeEvent *re) -{ - if (re->oldSize().height() > 0){ - qreal x, y; - x = (re->size().width())/qreal(re->oldSize().width()); - y = (re->size().height())/qreal(re->oldSize().height()); - ui->pongView->scale(x, y); - } - ui->pongView->resize(re->size()); -} - -void Tennis::lagReport(int ms) -{ - if (ms > 250){ - board->setStatus(QString("Caution Lag %1ms").arg(ms), 100, 0); - } -} - -/*void Tennis::nearFieldHandover() -{ - qDebug() << "Connecting to NFC provided address" << m_handover->bluetoothAddress().toString(); - - QBluetoothDeviceInfo device = QBluetoothDeviceInfo(m_handover->bluetoothAddress(), QString(), - QBluetoothDeviceInfo::ComputerDevice); - - QBluetoothServiceInfo service; - service.setServiceUuid(QBluetoothUuid(serviceUuid)); - service.setDevice(device); - - QBluetoothServiceInfo::Sequence protocolDescriptorList; - QBluetoothServiceInfo::Sequence protocol; - protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap)) - << QVariant::fromValue(m_handover->serverPort()); - protocolDescriptorList.append(QVariant::fromValue(protocol)); - service.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, - protocolDescriptorList); - - client->startClient(service); - board->setStatus(tr("Connecting: %1 %2").arg(m_handover->bluetoothAddress().toString()).arg(m_handover->serverPort()), 100, 25); -}*/ - -void Tennis::fps(const QString &f) -{ - board->setStatus(f, 100, 100); -} - diff --git a/examples/bluetooth/bttennis/tennis.h b/examples/bluetooth/bttennis/tennis.h deleted file mode 100644 index 3b684dde..00000000 --- a/examples/bluetooth/bttennis/tennis.h +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "ui_tennis.h" - -#include <QDialog> - -#include <QResizeEvent> -#include <QMoveEvent> -#include <QPropertyAnimation> -#include <qbluetoothserviceinfo.h> -#include <qbluetoothsocket.h> -#include <qbluetoothdevicediscoveryagent.h> - -#include "board.h" -#include "controller.h" - -#include <QDebug> - -QT_FORWARD_DECLARE_CLASS(QBluetoothServiceDiscoveryAgent) - -QT_USE_NAMESPACE - -static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c9"); - -class TennisServer; -class TennisClient; -//class Handover; - -//! [declaration] -class Tennis : public QDialog -{ - Q_OBJECT - Q_PROPERTY(int paddlePos READ paddlePos WRITE setPaddlePos) - -public: - Tennis(QWidget *parent = 0); - ~Tennis(); - - int paddlePos() { return paddle_pos; } - void setPaddlePos(int p); - -signals: - void moveLeftPaddle(int y); - void moveRightPaddle(int y); - -protected: - void wheelEvent ( QWheelEvent * event ); - void keyPressEvent ( QKeyEvent * event ); - void resizeEvent(QResizeEvent *); - -private slots: - void serverConnected(const QString &name); - void serverDisconnected(); - - void clientConnected(const QString &name); - void clientDisconnected(); - - void serviceDiscovered(const QBluetoothServiceInfo &serviceInfo); - void discoveryFinished(); - - void startDiscovery(); - - void mouseMove(int x, int y); - - void lagReport(int ms); - -// void nearFieldHandover(); - - void fps(const QString &f); - -private: - - void moveUp(int px = 10); - void moveDown(int px = 10); - - void move(int px); - - Ui_Tennis *ui; - - Board *board; - Controller *controller; - - int paddle_pos; - int endPaddlePos; - - bool isClient; - bool isConnected; - bool quickDiscovery; - - QBluetoothSocket *socket; - TennisServer *server; - TennisClient *client; - - QPropertyAnimation *paddleAnimation; - - QBluetoothServiceDiscoveryAgent *m_discoveryAgent; -// Handover *m_handover; -}; -//! [declaration] diff --git a/examples/bluetooth/bttennis/tennis.qrc b/examples/bluetooth/bttennis/tennis.qrc deleted file mode 100644 index 12aa7464..00000000 --- a/examples/bluetooth/bttennis/tennis.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/icons"> - <file>connect.png</file> - </qresource> -</RCC> diff --git a/examples/bluetooth/bttennis/tennis.ui b/examples/bluetooth/bttennis/tennis.ui deleted file mode 100644 index d6625fa8..00000000 --- a/examples/bluetooth/bttennis/tennis.ui +++ /dev/null @@ -1,57 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>Tennis</class> - <widget class="QDialog" name="Tennis"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>640</width> - <height>360</height> - </rect> - </property> - <property name="windowTitle"> - <string>Bluetooth Tennis</string> - </property> - <widget class="TennisView" name="pongView"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>640</width> - <height>366</height> - </rect> - </property> - <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="frameShape"> - <enum>QFrame::NoFrame</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Plain</enum> - </property> - <property name="lineWidth"> - <number>0</number> - </property> - <property name="verticalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - <property name="horizontalScrollBarPolicy"> - <enum>Qt::ScrollBarAlwaysOff</enum> - </property> - </widget> - </widget> - <customwidgets> - <customwidget> - <class>TennisView</class> - <extends>QGraphicsView</extends> - <header>tennisview.h</header> - </customwidget> - </customwidgets> - <resources/> - <connections/> -</ui> diff --git a/examples/bluetooth/bttennis/tennisclient.cpp b/examples/bluetooth/bttennis/tennisclient.cpp deleted file mode 100644 index 080c3a07..00000000 --- a/examples/bluetooth/bttennis/tennisclient.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tennisclient.h" - -#include <qbluetoothsocket.h> - -#include <QtCore/QDataStream> -#include <QtCore/QByteArray> - -#include <QtCore/QStringList> - -TennisClient::TennisClient(QObject *parent) -: QObject(parent), socket(0), stream(0), elapsed(new QTime), lagTimeout(0) -{ - lagTimer.setInterval(1000); - connect(&lagTimer, SIGNAL(timeout()), this, SLOT(sendEcho())); -} - -TennisClient::~TennisClient() -{ - stopClient(); -} - -//! [startClient] -void TennisClient::startClient(const QBluetoothServiceInfo &remoteService) -{ - if (socket) - return; - - serviceInfo = remoteService; - - // Connect to service - socket = new QBluetoothSocket(QBluetoothServiceInfo::L2capProtocol); - qDebug() << "Create socket"; - socket->connectToService(remoteService); - qDebug() << "ConnecttoService done"; - - connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); - connect(socket, SIGNAL(connected()), this, SLOT(connected())); - connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected())); - connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); - connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(error(QBluetoothSocket::SocketError))); - - lagTimer.start(); -} -//! [startClient] - -//! [stopClient] -void TennisClient::stopClient() -{ - if (socket == 0) // already stopped - return; - - qDebug() << Q_FUNC_INFO << "closing client!"; - - lagTimer.stop(); - - delete stream; - stream = 0; - - socket->deleteLater(); - socket = 0; -} -//! [stopClient] - -//! [socketDisconnected] -void TennisClient::socketDisconnected() -{ - qDebug() << "Got socketDisconnected"; - stopClient(); -} -//! [socketDisconnected] - -//! [readSocket] -void TennisClient::readSocket() -{ - if (!socket) - return; - - while (socket->bytesAvailable()) { - QString str; - - *stream >> str; - - QStringList args = str.split(QChar(' ')); - QString s = args.takeFirst(); - - if (s == "m" && args.count() == 2) { - emit moveBall(args.at(0).toInt(), args.at(1).toInt()); - } - else if (s == "s" && args.count() == 2){ - emit score(args.at(0).toInt(), args.at(1).toInt()); - } - else if (s == "l" && args.count() == 1){ - emit moveLeftPaddle(args.at(0).toInt()); - } - else if (s == "e"){ // echo - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << str; - socket->write(b); - } - else if (s == "E"){ - lagTimeout = 0; - QTime then = QTime::fromString(args.at(0), "hh:mm:ss.zzz"); - if (then.isValid()) { - emit lag(then.msecsTo(QTime::currentTime())); -// qDebug() << "RTT: " << then.msecsTo(QTime::currentTime()) << "ms"; - } - } - else { - qDebug() << Q_FUNC_INFO << "Unknown command" << str; - } - } -} -//! [readSocket] - -//! [moveRightPaddle] -void TennisClient::moveRightPaddle(int y) -{ - int msec = elapsed->elapsed(); - - if (stream && msec > 50) { - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("r %1").arg(y); - socket->write(b); - elapsed->restart(); - } -} -//! [moveRightPaddle] - -//! [connected] -void TennisClient::connected() -{ - stream = new QDataStream(socket); - emit connected(socket->peerName()); -} -//! [connected] - -void TennisClient::error(QBluetoothSocket::SocketError err) -{ - qDebug() << "Got socket error" <<Q_FUNC_INFO << "error" << err; - emit disconnected(); -} - -void TennisClient::sendEcho() -{ - if (lagTimeout) { - lagTimeout--; - return; - } - - if (stream) { - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("E %1").arg(QTime::currentTime().toString("hh:mm:ss.zzz")); - socket->write(b); - lagTimeout = 10; - } -} diff --git a/examples/bluetooth/bttennis/tennisclient.h b/examples/bluetooth/bttennis/tennisclient.h deleted file mode 100644 index a6dd232e..00000000 --- a/examples/bluetooth/bttennis/tennisclient.h +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CHATCLIENT_H -#define CHATCLIENT_H - -#include <qbluetoothserviceinfo.h> -#include <qbluetoothsocket.h> - -#include <QtCore/QObject> -#include <QtCore/QTime> -#include <QtCore/QTimer> - -QT_FORWARD_DECLARE_CLASS(QBluetoothSocket) -QT_FORWARD_DECLARE_CLASS(QDataStream) - -QT_USE_NAMESPACE - -//! [declaration] -class TennisClient : public QObject -{ - Q_OBJECT - -public: - explicit TennisClient(QObject *parent = 0); - ~TennisClient(); - - void startClient(const QBluetoothServiceInfo &remoteService); - void stopClient(); - -public slots: - void moveRightPaddle(int y); - void error(QBluetoothSocket::SocketError); - -signals: - void moveBall(int x, int y); - void score(int left, int right); - void moveLeftPaddle(int y); - - void connected(const QString &name); - void disconnected(); - - void lag(int ms); - -private slots: - void readSocket(); - void connected(); - void sendEcho(); - void socketDisconnected(); - -private: - QBluetoothSocket *socket; - QDataStream *stream; - QBluetoothServiceInfo serviceInfo; - QTime *elapsed; - QTimer lagTimer; - int lagTimeout; -}; -//! [declaration] - -#endif // CHATCLIENT_H diff --git a/examples/bluetooth/bttennis/tennisserver.cpp b/examples/bluetooth/bttennis/tennisserver.cpp deleted file mode 100644 index be6a0370..00000000 --- a/examples/bluetooth/bttennis/tennisserver.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tennisserver.h" -#include "tennis.h" - -#include <qbluetoothserver.h> -#include <qbluetoothsocket.h> - -#include <QDebug> - -TennisServer::TennisServer(QObject *parent) -: QObject(parent), l2capServer(0), clientSocket(0), stream(0), lagReplyTimeout(0) -{ - elapsed.start(); - ballElapsed.start(); - lagTimer.setInterval(1000); - connect(&lagTimer, SIGNAL(timeout()), this, SLOT(sendEcho())); -} - -TennisServer::~TennisServer() -{ - if (stream){ - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("D"); - clientSocket->write(b); - } - - stopServer(); -} - -void TennisServer::startServer() -{ - if (l2capServer) - return; - - //! [Create the server] - l2capServer = new QBluetoothServer(QBluetoothServiceInfo::L2capProtocol, this); - connect(l2capServer, SIGNAL(newConnection()), this, SLOT(clientConnected())); - l2capServer->listen(); - //! [Create the server] - - serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010); - - //! [Class ServiceClass must contain at least 1 entry] - QBluetoothServiceInfo::Sequence classId; -// classId << QVariant::fromValue(QBluetoothUuid(serviceUuid)); - classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort)); - serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId); - //! [Class ServiceClass must contain at least 1 entry] - - - //! [Service name, description and provider] - serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Example Tennis Server")); - serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription, - tr("Example bluetooth tennis server")); - serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("Nokia, QtDF")); - //! [Service name, description and provider] - - //! [Service UUID set] - serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid)); - //! [Service UUID set] - - //! [Service Discoverability] - serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList, - QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup)); - //! [Service Discoverability] - - - //! [Protocol descriptor list] - QBluetoothServiceInfo::Sequence protocolDescriptorList; - QBluetoothServiceInfo::Sequence protocol; - protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap)) - << QVariant::fromValue(quint16(l2capServer->serverPort())); - protocolDescriptorList.append(QVariant::fromValue(protocol)); - serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, - protocolDescriptorList); - //! [Protocol descriptor list] - - //! [Register service] - serviceInfo.registerService(); - //! [Register service] - -} - -//! [stopServer] -void TennisServer::stopServer() -{ - qDebug() <<Q_FUNC_INFO; - // Unregister service - serviceInfo.unregisterService(); - - delete stream; - stream = 0; - - // Close sockets - delete clientSocket; - clientSocket = 0; - - // Close server - delete l2capServer; - l2capServer = 0; -} -//! [stopServer] - -quint16 TennisServer::serverPort() const -{ - return l2capServer->serverPort(); -} - -//! [moveBall] -void TennisServer::moveBall(int x, int y) -{ - int msec = ballElapsed.elapsed(); - - if (stream && msec > 30){ - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("m %1 %2").arg(x).arg(y); - //s << QLatin1String("m") << x << y; - clientSocket->write(b); - ballElapsed.restart(); - } -} -//! [moveBall] - -void TennisServer::score(int left, int right) -{ - if (stream){ - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("s %1 %2").arg(left).arg(right); -// s << QChar('s') << left << right; - clientSocket->write(b); - } -} - -void TennisServer::moveLeftPaddle(int y) -{ - - int msec = elapsed.elapsed(); - - if (stream && msec > 50) { - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("l %1").arg(y); -// s << QChar('l') << y; - clientSocket->write(b); - elapsed.restart(); - } -} - -void TennisServer::readSocket() -{ - if (!clientSocket) - return; - - while (clientSocket->bytesAvailable()) { - - QString str; - *stream >> str; - QStringList args = str.split(QChar(' ')); - QString s = args.takeFirst(); - - if (s == "r" && args.count() == 1){ - emit moveRightPaddle(args.at(0).toInt()); - } - else if (s == "e" && args.count() == 1){ - lagReplyTimeout = 0; - QTime then = QTime::fromString(args.at(0), "hh:mm:ss.zzz"); - if (then.isValid()) { - emit lag(then.msecsTo(QTime::currentTime())); -// qDebug() << "RTT: " << then.msecsTo(QTime::currentTime()) << "ms"; - } - } - else if (s == "E"){ - QByteArray b; - QDataStream st(&b, QIODevice::WriteOnly); - st << str; - clientSocket->write(b); - } - else if (s == "D"){ - qDebug() << Q_FUNC_INFO << "closing!"; - clientSocket->deleteLater(); - clientSocket = 0; - } - else { - qDebug() << Q_FUNC_INFO << "Unknown command" << str; - } - } -} - -//! [clientConnected] -void TennisServer::clientConnected() -{ - qDebug() << Q_FUNC_INFO << "connect"; - - QBluetoothSocket *socket = l2capServer->nextPendingConnection(); - if (!socket) - return; - - if (clientSocket){ - qDebug() << Q_FUNC_INFO << "Closing socket!"; - delete socket; - return; - } - - connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); - connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); - connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError))); - - stream = new QDataStream(socket); - - clientSocket = socket; - - qDebug() << Q_FUNC_INFO << "started"; - - emit clientConnected(clientSocket->peerName()); - lagTimer.start(); -} -//! [clientConnected] - -void TennisServer::socketError(QBluetoothSocket::SocketError err) -{ - qDebug() << Q_FUNC_INFO << err; -} - -//! [sendEcho] -void TennisServer::sendEcho() -{ - if (lagReplyTimeout) { - lagReplyTimeout--; - return; - } - - if (stream) { - QByteArray b; - QDataStream s(&b, QIODevice::WriteOnly); - s << QString("e %1").arg(QTime::currentTime().toString("hh:mm:ss.zzz")); - clientSocket->write(b); - lagReplyTimeout = 10; - } -} -//! [sendEcho] - -//! [clientDisconnected] -void TennisServer::clientDisconnected() -{ - qDebug() << Q_FUNC_INFO << "client closing!"; - - lagTimer.stop(); - lagReplyTimeout = 0; - QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender()); - if (!socket) - return; - - emit clientDisconnected(socket->peerName()); - - clientSocket->deleteLater(); - clientSocket = 0; - delete stream; - stream = 0; - -// socket->deleteLater(); -} -//! [clientDisconnected] - diff --git a/examples/bluetooth/bttennis/tennisserver.h b/examples/bluetooth/bttennis/tennisserver.h deleted file mode 100644 index 6bdb13cd..00000000 --- a/examples/bluetooth/bttennis/tennisserver.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TENNISSERVER_H -#define TENNISSERVER_H - -#include <qbluetoothserviceinfo.h> -#include <qbluetoothsocket.h> - -#include <QtCore/QObject> -#include <QtCore/QList> -#include <QtCore/QDataStream> -#include <QtCore/QTime> -#include <QtCore/QTimer> - -QT_FORWARD_DECLARE_CLASS(QBluetoothServer) -QT_FORWARD_DECLARE_CLASS(QBluetoothSocket) -QT_FORWARD_DECLARE_CLASS(QBluetoothServiceInfo) - -QT_USE_NAMESPACE - -//! [declaration] -class TennisServer : public QObject -{ - Q_OBJECT - -public: - explicit TennisServer(QObject *parent = 0); - ~TennisServer(); - - void startServer(); - void stopServer(); - - quint16 serverPort() const; - -public slots: - void moveBall(int x, int y); - void score(int left, int right); - void moveLeftPaddle(int y); - -signals: - void moveRightPaddle(int y); - void clientDisconnected(const QString &name); - void clientConnected(const QString &name); - void lag(int ms); - -private slots: - void clientConnected(); - void clientDisconnected(); - void readSocket(); - void sendEcho(); - void socketError(QBluetoothSocket::SocketError err); - -private: - QBluetoothServer *l2capServer; - QBluetoothServiceInfo serviceInfo; - QBluetoothSocket *clientSocket; - QDataStream *stream; - QTime elapsed; - QTime ballElapsed; - QTimer lagTimer; - int lagReplyTimeout; -}; -//! [declaration] - -#endif // CHATSERVER_H diff --git a/examples/bluetooth/bttennis/tennisview.cpp b/examples/bluetooth/bttennis/tennisview.cpp deleted file mode 100644 index 3ec75b84..00000000 --- a/examples/bluetooth/bttennis/tennisview.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "tennisview.h" - -#include <QMouseEvent> - -TennisView::TennisView(QWidget *parent) : - QGraphicsView(parent) -{ -} - -void TennisView::mousePressEvent(QMouseEvent *event) -{ - QPointF p = mapToScene(event->x(), event->y()); - emit mousePress(p.x(), p.y()); - emit mouseMove(p.x(), p.y()); - last_y = p.y(); -} - -void TennisView::mouseMoveEvent(QMouseEvent *event) -{ - if (event->buttons()) { - QPointF p = mapToScene(event->x(), event->y()); - if (10 < abs(last_y - event->y())) { -// emit mouseMove(p.x(), p.y()); - last_y = p.y(); - } - } -} diff --git a/examples/bluetooth/bttennis/tennisview.h b/examples/bluetooth/bttennis/tennisview.h deleted file mode 100644 index 4f7f0027..00000000 --- a/examples/bluetooth/bttennis/tennisview.h +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef TENNISVIEW_H -#define TENNISVIEW_H - -#include <QGraphicsView> - -class TennisView : public QGraphicsView -{ - Q_OBJECT -public: - explicit TennisView(QWidget *parent = 0); - -signals: - void mouseMove(int x, int y); - void mousePress(int x, int y); - -public slots: - -protected: - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *ev); - -private: - int last_y; - -}; - -#endif // TENNISVIEW_H diff --git a/examples/bluetooth/picturetransfer/DeviceDiscovery.qml b/examples/bluetooth/picturetransfer/DeviceDiscovery.qml index 1da77975..77391ec2 100644 --- a/examples/bluetooth/picturetransfer/DeviceDiscovery.qml +++ b/examples/bluetooth/picturetransfer/DeviceDiscovery.qml @@ -79,6 +79,14 @@ Item { //! [Discovery-2] model: BluetoothDiscoveryModel { discoveryMode: BluetoothDiscoveryModel.DeviceDiscovery + onErrorChanged: { + if (error == BluetoothDiscoveryModel.NoError) + return; + if (error == BluetoothDiscoveryModel.PoweredOffError) + titleLabel.text = "Bluetooth turned off"; + else + titleLabel.text = "Cannot find devices"; + } } delegate: Button { diff --git a/examples/bluetooth/picturetransfer/doc/src/picturetransfer.qdoc b/examples/bluetooth/picturetransfer/doc/src/picturetransfer.qdoc index 7a166121..3b0218d4 100644 --- a/examples/bluetooth/picturetransfer/doc/src/picturetransfer.qdoc +++ b/examples/bluetooth/picturetransfer/doc/src/picturetransfer.qdoc @@ -28,18 +28,20 @@ a/**************************************************************************** /*! \example picturetransfer \title QML Bluetooth Picture Push Example +\brief An example showing the use Bluetooth Object Push Profile (OPP). -The Bluetooth Picture Push example shows how to use the \l QBluetoothTransferManager -API. The example transfers a local image to a remote device. Unfortunately this example cannot be used on -Android as Qt does not support the Object Push Profile on this platform. +The Bluetooth Picture Push example shows how to use the \l +QBluetoothTransferManager API. The example transfers a local image to a remote +device. Unfortunately this example cannot be used on Android as Qt does not +support the Object Push Profile (OPP) on this platform. -On the first user interface page the application scans for remote Bluetooth devices. The user must select -the appropriate device to continue: +On the first user interface page the application scans for remote Bluetooth +devices. The user must select the appropriate device to continue: \image opp-example-1.png -The next page presents a list of image files on the device. The files must be located under -\l QStandardPaths::PicturesLocation}: +The next page presents a list of image files on the device. The files must be +located under \l QStandardPaths::PicturesLocation}: \image opp-example-2.png @@ -47,29 +49,35 @@ Once the picture was selected the UI shows the progress of the file transfer: \image opp-example-3.png +\include examples-run.qdocinc + +\sa {Qt Bluetooth} + \section1 Device Discovery -The device discovery uses the \l BluetoothDiscoveryModel to detect the remote devices. Each discovery is displayed -as an entry in a list. Once a device was selected the device address is stored in the \c root element. More -details about the \c root element will follow further below. +The device discovery uses the \l BluetoothDiscoveryModel to detect the remote +devices. Each discovery is displayed as an entry in a list. Once a device was +selected the device address is stored in the \c root element. More details about +the \c root element will follow further below. \snippet picturetransfer/DeviceDiscovery.qml Discovery-1 \snippet picturetransfer/DeviceDiscovery.qml Discovery-2 \section1 File Selection -The file is selected with the help of \l FolderListModel. Once again the selected file is stored in the \c root -element: +The file is selected with the help of \l FolderListModel. Once again the +selected file is stored in the \c root element: \snippet picturetransfer/PictureSelector.qml FileSelect-1 \snippet picturetransfer/PictureSelector.qml FileSelect-2 \snippet picturetransfer/PictureSelector.qml FileSelect-3 \snippet picturetransfer/PictureSelector.qml FileSelect-4 -\section1 The root element +\section1 Root Element -The already mentioned \c root element collects the necessary pieces of data for the picture transfer. -Once the file name has been set it triggers the file transfer: +The already mentioned \c root element collects the necessary pieces of data for +the picture transfer. Once the file name has been set it triggers the file +transfer: \snippet picturetransfer/bttransfer.qml Root-1 @@ -77,7 +85,7 @@ Once the file name has been set it triggers the file transfer: \snippet picturetransfer/bttransfer.qml Root-3 \snippet picturetransfer/bttransfer.qml Root-3 -\section1 The File Transfer +\section1 File Transfer The file transfer is implemented in C++: diff --git a/examples/bluetooth/picturetransfer/filetransfer.cpp b/examples/bluetooth/picturetransfer/filetransfer.cpp index 7cfd041d..6f0a25b2 100644 --- a/examples/bluetooth/picturetransfer/filetransfer.cpp +++ b/examples/bluetooth/picturetransfer/filetransfer.cpp @@ -63,5 +63,5 @@ void FileTransfer::initTransfer(QString address, QString fileName) void FileTransfer::updateProgress(qint64 transferred, qint64 total) { m_progress = ((float)transferred)/((float)total); - Q_EMIT progressChanged(); + emit progressChanged(); } diff --git a/examples/bluetooth/picturetransfer/main.cpp b/examples/bluetooth/picturetransfer/main.cpp index 7db3053e..cad9c66c 100644 --- a/examples/bluetooth/picturetransfer/main.cpp +++ b/examples/bluetooth/picturetransfer/main.cpp @@ -58,7 +58,7 @@ int main(int argc, char *argv[]) QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first()); qDebug() << QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); - view.setSource(QUrl(QLatin1String("qrc:/bttransfer.qml"))); + view.setSource(QUrl(QStringLiteral("qrc:/bttransfer.qml"))); view.setResizeMode(QQuickView::SizeRootObjectToView); QObject::connect(view.engine(), SIGNAL(quit()), qApp, SLOT(quit())); view.show(); diff --git a/examples/bluetooth/pingpong/assets/Board.qml b/examples/bluetooth/pingpong/assets/Board.qml new file mode 100644 index 00000000..bd78c18b --- /dev/null +++ b/examples/bluetooth/pingpong/assets/Board.qml @@ -0,0 +1,180 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 +import QtQuick.Window 2.1 + +Rectangle { + id: board + width: 600 + height: 300 + + // 1 - server role; left pedal + // 2 - client role; right pedal + property int roleSide: pingPong.role + onRoleSideChanged: { + if (pingPong.role == 1) { + rightMouse.opacity = 0.7 + rightMouse.enabled = false + } + else if (pingPong.role == 2) { + leftMouse.opacity = 0.7 + leftMouse.enabled = false + } + } + + property bool deviceMessage: pingPong.showDialog + onDeviceMessageChanged: { + if (pingPong.showDialog) { + info.visible = true; + board.opacity = 0.5; + } else { + info.visible = false; + board.opacity = 1; + } + } + + property double leftBlockUpdate: pingPong.leftBlockY + onLeftBlockUpdateChanged: leftblock.y = pingPong.leftBlockY + + property double rightBlockUpdate: pingPong.rightBlockY + onRightBlockUpdateChanged: rightblock.y = pingPong.rightBlockY + + property double leftBlockY: leftblock.y + onLeftBlockYChanged: pingPong.updateLeftBlock(leftblock.y) + + property double rightBlockY: rightblock.y + onRightBlockYChanged: pingPong.updateRightBlock(rightblock.y) + + // Left pedal - server role + Rectangle { + id: leftblock + y: (parent.height/2) + width: (parent.width/27) + height: (parent.height/5) + anchors.left: parent.left + color: "#363636" + radius: 10 + + MouseArea { + id: leftMouse + anchors.fill: parent + acceptedButtons: Qt.LeftButton + drag.target: leftblock + drag.axis: Drag.YAxis + drag.minimumY: 0 + drag.maximumY: (board.height - leftblock.height) + } + } + + // Right pedal - client role + Rectangle { + id: rightblock + y: (parent.height/2) + width: (parent.width/27) + height: (parent.height/5) + anchors.right: parent.right + color: "#363636" + radius: 10 + + MouseArea { + id: rightMouse + anchors.fill: parent + acceptedButtons: Qt.LeftButton + drag.target: rightblock + drag.axis: Drag.YAxis + drag.minimumY: 0 + drag.maximumY: (board.height - rightblock.height) + } + } + + Rectangle { + id: splitter + color: "#363636" + anchors.horizontalCenter: parent.horizontalCenter + height: parent.height + width: parent.width/100 + } + + Text { + id: leftResult + text: pingPong.leftResult + font.bold: true + font.pixelSize: 30 + anchors.right: splitter.left + anchors.top: parent.top + anchors.margins: 15 + } + + Text { + id: rightResult + text: pingPong.rightResult + font.bold: true + font.pixelSize: 30 + anchors.left: splitter.right + anchors.top: parent.top + anchors.margins: 15 + } + + Rectangle { + id: ball + width: leftblock.width/2 + height: leftblock.width/2 + radius: width + color: "#363636" + x: pingPong.ballX + y: pingPong.ballY + + SequentialAnimation { + running: true + NumberAnimation { target: ball; property: "x"; duration: 50 } + NumberAnimation { target: ball; property: "y"; duration: 50 } + } + } + + Component.onCompleted: { + if (menulist.height == Screen.height && menulist.width == Screen.width) + pingPong.setSize(Screen.width, Screen.height) + else + pingPong.setSize(board.width, board.height) + pingPong.updateLeftBlock(leftblock.y) + pingPong.updateRightBlock(rightblock.y) + } +} diff --git a/examples/bluetooth/pingpong/assets/Dialog.qml b/examples/bluetooth/pingpong/assets/Dialog.qml new file mode 100644 index 00000000..da7f09d2 --- /dev/null +++ b/examples/bluetooth/pingpong/assets/Dialog.qml @@ -0,0 +1,61 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 + +Rectangle { + width: parent.width/2 + height: 100 + z: 50 + border.width: 2 + border.color: "#363636" + radius: 10 + + Text { + id: message + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + anchors.fill: parent + wrapMode: Text.WordWrap + elide: Text.ElideMiddle + text: pingPong.message + color: "#363636" + } +} diff --git a/examples/bluetooth/pingpong/assets/Menu.qml b/examples/bluetooth/pingpong/assets/Menu.qml new file mode 100644 index 00000000..719cac3a --- /dev/null +++ b/examples/bluetooth/pingpong/assets/Menu.qml @@ -0,0 +1,119 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 + +Rectangle { + width: 600 + height: 300 + + + Rectangle { + width: parent.width + height: 70 + border.width: 1 + border.color: "#363636" + radius: 5 + + Text { + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + anchors.fill: parent + text: "Welcome to PingPong Game \n Please select an option" + font.pixelSize: 20 + elide: Text.ElideMiddle + color: "#363636" + } + } + + Rectangle { + id: startServer + anchors.centerIn: parent + width: parent.width/2 + height: parent.height/5 + color: "#363636" + + Text { + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + anchors.fill: parent + font.bold: true + text: "Start PingPong server" + color: "#E3E3E3" + elide: Text.ElideMiddle + } + + MouseArea { + anchors.fill: parent + onClicked: { + pageLoader.source = "Board.qml"; + pingPong.startServer(); + } + } + } + + Rectangle { + id: startClient + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: startServer.bottom + anchors.topMargin: 10 + width: parent.width/2 + height: parent.height/5 + color: "#363636" + + Text { + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + anchors.fill: parent + font.bold: true + text: "Start PingPong client" + color: "#E3E3E3" + elide: Text.ElideMiddle + } + + MouseArea { + anchors.fill: parent + onClicked: { + pageLoader.source = "Board.qml"; + pingPong.startClient() + } + } + } +} diff --git a/examples/bluetooth/pingpong/assets/main.qml b/examples/bluetooth/pingpong/assets/main.qml new file mode 100644 index 00000000..2a155662 --- /dev/null +++ b/examples/bluetooth/pingpong/assets/main.qml @@ -0,0 +1,62 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 +import QtQuick.Window 2.1 + +Window { + id: menulist + width: 600 + height: 300 + visible: true + + Dialog { + id: info + anchors.centerIn: parent + visible: false + } + + Component.onCompleted: pageLoader.source = "Menu.qml" + + Loader { + id: pageLoader + anchors.fill: parent + } +} diff --git a/examples/bluetooth/pingpong/doc/images/intro.png b/examples/bluetooth/pingpong/doc/images/intro.png Binary files differnew file mode 100644 index 00000000..062b8ea0 --- /dev/null +++ b/examples/bluetooth/pingpong/doc/images/intro.png diff --git a/examples/bluetooth/pingpong/doc/images/intro1.png b/examples/bluetooth/pingpong/doc/images/intro1.png Binary files differnew file mode 100644 index 00000000..c1cedae2 --- /dev/null +++ b/examples/bluetooth/pingpong/doc/images/intro1.png diff --git a/examples/bluetooth/pingpong/doc/src/pingpong.qdoc b/examples/bluetooth/pingpong/doc/src/pingpong.qdoc new file mode 100644 index 00000000..0e82a71a --- /dev/null +++ b/examples/bluetooth/pingpong/doc/src/pingpong.qdoc @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: http://www.gnu.org/copyleft/fdl.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example pingpong + \title Bluetooth QML Ping Pong example + \brief A QML example showing Bluetooth communication. + + The Bluetooth QML Ping Pong example presents the socket communication between two + Bluetooth devices. The basic concept is the ping pong game where two players + communicate via sockets. + + \image intro.png + + \include examples-run.qdocinc + + At the beginning, the user selects the role. One device acts as a server and the second + one as a client. After selecting the role, adjustments to the screen size are done + (two devices might have different screen sizes). The server side starts a service named + "PingPong server". + + \snippet pingpong/pingpong.cpp Starting the server + + On the client side, the full service discovery on the nearby Bluetooth devices is done. + + \snippet pingpong/pingpong.cpp Searching for the service + + When the ping pong service is discovered, the client connects to the server using the socket. + + \snippet pingpong/pingpong.cpp Connecting the socket + + On the server side, the connected signal is emitted initiating that the client is connected. + The necessary signals and slots on the server side are connected. + + \snippet pingpong/pingpong.cpp Initiating server socket + + The game starts after the devices are connected and the screen is adjusted. + + \snippet pingpong/pingpong.cpp Start the game + + The server updates the ball direction and coordinates. The coordinates of pedals are sent + to each other every 50ms. + + \snippet pingpong/pingpong.cpp Updating coordinates + + The coordinates are updated and exchanged via sockets. As presented, the server sends its + pedal's y coordinate and the ball coordinates whereas, the client sends only its pedal + y coordinate. + + \snippet pingpong/pingpong.cpp Checking the boundaries + + In the code above, it was shown how the server checks whether the ball has reached + the boundaries of the board. In the case of the goal, the server updates + the results via its socket. + + \image intro1.png + +*/ diff --git a/examples/bluetooth/pingpong/main.cpp b/examples/bluetooth/pingpong/main.cpp new file mode 100644 index 00000000..86cbb8bf --- /dev/null +++ b/examples/bluetooth/pingpong/main.cpp @@ -0,0 +1,54 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QQmlContext> +#include <QGuiApplication> +#include <QQmlApplicationEngine> +#include "pingpong.h" + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + PingPong pingPong; + QQmlApplicationEngine engine; + engine.rootContext()->setContextProperty("pingPong", &pingPong); + engine.load(QUrl("qrc:/assets/main.qml")); + return app.exec(); +} diff --git a/examples/bluetooth/pingpong/pingpong.cpp b/examples/bluetooth/pingpong/pingpong.cpp new file mode 100644 index 00000000..6d9466e9 --- /dev/null +++ b/examples/bluetooth/pingpong/pingpong.cpp @@ -0,0 +1,463 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "pingpong.h" +#include <QDebug> + +PingPong::PingPong(): + m_serverInfo(0), socket(0), discoveryAgent(0), interval(5), m_resultLeft(0), m_resultRight(0), + m_showDialog(false), m_role(0), m_proportionX(0), m_proportionY(0), m_serviceFound(false) +{ + m_timer = new QTimer(this); + connect(m_timer, SIGNAL(timeout()), this, SLOT(update())); +} + +PingPong::~PingPong() +{ + delete m_timer; + delete m_serverInfo; + delete socket; + delete discoveryAgent; +} + +void PingPong::startGame() +{ + m_showDialog = false; + emit showDialogChanged(); + //! [Start the game] + if (m_role == 1) + updateDirection(); + + m_timer->start(50); + //! [Start the game] +} + +void PingPong::update() +{ + QByteArray size; + // Server is only updating the coordinates + //! [Updating coordinates] + if (m_role == 1) { + checkBoundaries(); + m_ballPreviousX = m_ballX; + m_ballPreviousY = m_ballY; + m_ballY = m_direction*(m_ballX+interval) - m_direction*m_ballX + m_ballY; + m_ballX = m_ballX + interval; + + size.setNum(m_ballX); + size.append(' '); + QByteArray size1; + size1.setNum(m_ballY); + size.append(size1); + size.append(' '); + size1.setNum(m_leftBlockY); + size.append(size1); + size.append(" \n"); + socket->write(size.constData()); + emit ballChanged(); + } + else if (m_role == 2) { + size.setNum(m_rightBlockY); + size.append(" \n"); + socket->write(size.constData()); + } + //! [Updating coordinates] +} + + + +void PingPong::setSize(const float &x, const float &y) +{ + m_boardWidth = x; + m_boardHeight = y; + m_targetX = m_boardWidth; + m_targetY = m_boardHeight/2; + m_ballPreviousX = m_ballX = m_boardWidth/2; + m_ballPreviousY = m_ballY = m_boardHeight - m_boardWidth/54; + emit ballChanged(); +} + +void PingPong::updateBall(const float &bX, const float &bY) +{ + m_ballX = bX; + m_ballY = bY; +} + +void PingPong::updateLeftBlock(const float &lY) +{ + m_leftBlockY = lY; +} + +void PingPong::updateRightBlock(const float &rY) +{ + m_rightBlockY = rY; +} + +void PingPong::checkBoundaries() +{ + float ballWidth = m_boardWidth/54; + float blockSize = m_boardWidth/27; + float blockHeight = m_boardHeight/5; + //! [Checking the boundaries] + if (((m_ballX + ballWidth) > (m_boardWidth - blockSize)) && ((m_ballY + ballWidth) < (m_rightBlockY + blockHeight)) + && (m_ballY > m_rightBlockY)) { + m_targetY = 2 * m_ballY - m_ballPreviousY; + m_targetX = m_ballPreviousX; + interval = -5; + updateDirection(); + } + else if ((m_ballX < blockSize) && ((m_ballY + ballWidth) < (m_leftBlockY + blockHeight)) + && (m_ballY > m_leftBlockY)) { + m_targetY = 2 * m_ballY - m_ballPreviousY; + m_targetX = m_ballPreviousX; + interval = 5; + updateDirection(); + } + else if (m_ballY < 0 || (m_ballY + ballWidth > m_boardHeight)) { + m_targetY = m_ballPreviousY; + m_targetX = m_ballX + interval; + updateDirection(); + } + //! [Checking the boundaries] + else if ((m_ballX + ballWidth) > m_boardWidth) { + m_resultLeft++; + m_targetX = m_boardWidth; + m_targetY = m_boardHeight/2; + m_ballPreviousX = m_ballX = m_boardWidth/2; + m_ballPreviousY = m_ballY = m_boardHeight - m_boardWidth/54; + + updateDirection(); + checkResult(); + QByteArray result; + result.append("result "); + QByteArray res; + res.setNum(m_resultLeft); + result.append(res); + result.append(' '); + res.setNum(m_resultRight); + result.append(res); + result.append(" \n"); + socket->write(result); + qDebug() << result; + emit resultChanged(); + } + else if (m_ballX < 0) { + m_resultRight++; + m_targetX = 0; + m_targetY = m_boardHeight/2; + m_ballPreviousX = m_ballX = m_boardWidth/2; + m_ballPreviousY = m_ballY = m_boardHeight - m_boardWidth/54; + updateDirection(); + checkResult(); + QByteArray result; + result.append("result "); + QByteArray res; + res.setNum(m_resultLeft); + result.append(res); + result.append(' '); + res.setNum(m_resultRight); + result.append(res); + result.append(" \n"); + socket->write(result); + emit resultChanged(); + } +} + +void PingPong::checkResult() +{ + if (m_resultRight == 10 && m_role == 2) { + setMessage("Game over. You win!"); + m_timer->stop(); + } + else if (m_resultRight == 10 && m_role == 1) { + setMessage("Game over. You lose!"); + m_timer->stop(); + } + else if (m_resultLeft == 10 && m_role == 1) { + setMessage("Game over. You win!"); + m_timer->stop(); + } + else if (m_resultLeft == 10 && m_role == 2) { + setMessage("Game over. You lose!"); + m_timer->stop(); + } +} + +void PingPong::updateDirection() +{ + m_direction = (m_targetY - m_ballY)/(m_targetX - m_ballX); +} + +void PingPong::startServer() +{ + setMessage(QStringLiteral("Starting the server")); + //! [Starting the server] + m_serverInfo = new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, this); + connect(m_serverInfo, SIGNAL(newConnection()), this, SLOT(clientConnected())); + connect(m_serverInfo, SIGNAL(error(QBluetoothServer::Error)), + this, SLOT(serverError(QBluetoothServer::Error))); + const QBluetoothUuid uuid(serviceUuid); + + m_serverInfo->listen(uuid, QStringLiteral("PingPong server")); + //! [Starting the server] + setMessage(QStringLiteral("Server started, waiting for the client. You are the left player.")); + // m_role is set to 1 if it is a server + m_role = 1; + emit roleChanged(); +} + +void PingPong::startClient() +{ + //! [Searching for the service] + discoveryAgent = new QBluetoothServiceDiscoveryAgent(QBluetoothAddress()); + + connect(discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)), + this, SLOT(addService(QBluetoothServiceInfo))); + connect(discoveryAgent, SIGNAL(finished()), this, SLOT(done())); + connect(discoveryAgent, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)), + this, SLOT(serviceScanError(QBluetoothServiceDiscoveryAgent::Error))); + discoveryAgent->setUuidFilter(QBluetoothUuid(serviceUuid)); + discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery); + //! [Searching for the service] + setMessage(QStringLiteral("Starting server discovery. You are the right player")); + // m_role is set to 2 if it is a client + m_role = 2; + emit roleChanged(); +} + +void PingPong::clientConnected() +{ + //! [Initiating server socket] + if (!m_serverInfo->hasPendingConnections()) { + setMessage("FAIL: expected pending server connection"); + return; + } + socket = m_serverInfo->nextPendingConnection(); + if (!socket) + return; + socket->setParent(this); + connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); + connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); + connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), + this, SLOT(socketError(QBluetoothSocket::SocketError))); + //! [Initiating server socket] + setMessage(QStringLiteral("Client connected.")); + + QByteArray size; + size.setNum(m_boardWidth); + size.append(' '); + QByteArray size1; + size1.setNum(m_boardHeight); + size.append(size1); + size.append(" \n"); + socket->write(size.constData()); + +} + +void PingPong::clientDisconnected() +{ + setMessage(QStringLiteral("Client disconnected")); + m_timer->stop(); +} + +void PingPong::socketError(QBluetoothSocket::SocketError error) +{ + Q_UNUSED(error); + m_timer->stop(); +} + +void PingPong::serverError(QBluetoothServer::Error error) +{ + Q_UNUSED(error); + m_timer->stop(); +} + +void PingPong::done() +{ + qDebug() << "Service scan done"; + if (!m_serviceFound) + setMessage("PingPong service not found"); +} + +void PingPong::addService(const QBluetoothServiceInfo &service) +{ + setMessage("Service found. Setting parameters..."); + //! [Connecting the socket] + socket = new QBluetoothSocket(QBluetoothServiceInfo::L2capProtocol); + socket->connectToService(service); + + connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); + connect(socket, SIGNAL(connected()), this, SLOT(serverConnected())); + connect(socket, SIGNAL(disconnected()), this, SLOT(serverDisconnected())); + //! [Connecting the socket] + m_serviceFound = true; +} + +void PingPong::serviceScanError(QBluetoothServiceDiscoveryAgent::Error error) +{ + setMessage(QStringLiteral("Scanning error") + error); +} + +bool PingPong::showDialog() const +{ + return m_showDialog; +} + +QString PingPong::message() const +{ + return m_message; +} + +void PingPong::serverConnected() +{ + setMessage("Server Connected"); + QByteArray size; + size.setNum(m_boardWidth); + size.append(' '); + QByteArray size1; + size1.setNum(m_boardHeight); + size.append(size1); + size.append(" \n"); + socket->write(size.constData()); +} + +void PingPong::serverDisconnected() +{ + setMessage("Server Disconnected"); + m_timer->stop(); +} + +void PingPong::readSocket() +{ + if (!socket) + return; + const char sep = ' '; + QByteArray line; + while (socket->canReadLine()) { + line = socket->readLine(); + //qDebug() << QString::fromUtf8(line.constData(), line.length()); + if (line.contains("result")) { + QList<QByteArray> result = line.split(sep); + if (result.size() > 2) { + QByteArray leftSide = result.at(1); + QByteArray rightSide = result.at(2); + m_resultLeft = leftSide.toInt(); + m_resultRight = rightSide.toInt(); + emit resultChanged(); + checkResult(); + } + } + } + if ((m_proportionX == 0 || m_proportionY == 0)) { + QList<QByteArray> boardSize = line.split(sep); + if (boardSize.size() > 1) { + QByteArray boardWidth = boardSize.at(0); + QByteArray boardHeight = boardSize.at(1); + m_proportionX = m_boardWidth/boardWidth.toFloat(); + m_proportionY = m_boardHeight/boardHeight.toFloat(); + setMessage("Screen adjusted. Get ready!"); + QTimer::singleShot(3000, this, SLOT(startGame())); + } + } + else if (m_role == 1) { + QList<QByteArray> boardSize = line.split(sep); + if (boardSize.size() > 1) { + QByteArray rightBlockY = boardSize.at(0); + m_rightBlockY = m_proportionY * rightBlockY.toFloat(); + emit rightBlockChanged(); + } + } + else if (m_role == 2) { + QList<QByteArray> boardSize = line.split(sep); + if (boardSize.size() > 2) { + QByteArray ballX = boardSize.at(0); + QByteArray ballY = boardSize.at(1); + QByteArray leftBlockY = boardSize.at(2); + m_ballX = m_proportionX * ballX.toFloat(); + m_ballY = m_proportionY * ballY.toFloat(); + m_leftBlockY = m_proportionY * leftBlockY.toFloat(); + emit leftBlockChanged(); + emit ballChanged(); + } + } +} + +void PingPong::setMessage(const QString &message) +{ + m_showDialog = true; + m_message = message; + emit showDialogChanged(); +} + +int PingPong::role() const +{ + return m_role; +} + +int PingPong::leftResult() const +{ + return m_resultLeft; +} + +int PingPong::rightResult() const +{ + return m_resultRight; +} + +float PingPong::ballX() const +{ + return m_ballX; +} + +float PingPong::ballY() const +{ + return m_ballY; +} + + +float PingPong::leftBlockY() const +{ + return m_leftBlockY; +} + +float PingPong::rightBlockY() const +{ + return m_rightBlockY; +} diff --git a/examples/bluetooth/pingpong/pingpong.h b/examples/bluetooth/pingpong/pingpong.h new file mode 100644 index 00000000..17fe176b --- /dev/null +++ b/examples/bluetooth/pingpong/pingpong.h @@ -0,0 +1,139 @@ +/*************************************************************************** +** +** Copyright (C) 2014 BlackBerry Limited. All rights reserved. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the QtBluetooth module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PINGPONG_H +#define PINGPONG_H + +#include <QTimer> +#include <QObject> +#include <qbluetoothserver.h> +#include <qbluetoothserviceinfo.h> +#include <qbluetoothlocaldevice.h> +#include <qbluetoothservicediscoveryagent.h> + +static const QString serviceUuid(QStringLiteral("e8e10f95-1a70-4b27-9ccf-02010264e9c9")); + +class PingPong: public QObject +{ + Q_OBJECT + Q_PROPERTY(float ballX READ ballX NOTIFY ballChanged) + Q_PROPERTY(float ballY READ ballY NOTIFY ballChanged) + Q_PROPERTY(float leftBlockY READ leftBlockY NOTIFY leftBlockChanged) + Q_PROPERTY(float rightBlockY READ rightBlockY NOTIFY rightBlockChanged) + Q_PROPERTY(bool showDialog READ showDialog NOTIFY showDialogChanged) + Q_PROPERTY(QString message READ message NOTIFY showDialogChanged) + Q_PROPERTY(int role READ role NOTIFY roleChanged) + Q_PROPERTY(int leftResult READ leftResult NOTIFY resultChanged) + Q_PROPERTY(int rightResult READ rightResult NOTIFY resultChanged) +public: + PingPong(); + ~PingPong(); + float ballX() const; + float ballY() const; + float leftBlockY() const; + float rightBlockY() const; + void checkBoundaries(); + void updateDirection(); + bool showDialog() const; + QString message() const; + void setMessage(const QString &message); + int role() const; + int leftResult() const; + int rightResult() const; + void checkResult(); + +public slots: + void startGame(); + void update(); + void setSize(const float &x, const float &y); + void updateBall(const float &bX, const float &bY); + void updateLeftBlock(const float &lY); + void updateRightBlock(const float &rY); + void startServer(); + void startClient(); + void clientConnected(); + void clientDisconnected(); + void serverConnected(); + void serverDisconnected(); + void socketError(QBluetoothSocket::SocketError); + void serverError(QBluetoothServer::Error); + void serviceScanError(QBluetoothServiceDiscoveryAgent::Error); + void done(); + void addService(const QBluetoothServiceInfo &); + void readSocket(); + +Q_SIGNALS: + void ballChanged(); + void leftBlockChanged(); + void rightBlockChanged(); + void showDialogChanged(); + void roleChanged(); + void resultChanged(); + +private: + QBluetoothServer *m_serverInfo; + QBluetoothServiceInfo m_serviceInfo; + QBluetoothSocket *socket; + QBluetoothServiceDiscoveryAgent *discoveryAgent; + + float m_ballX; + float m_ballY; + float m_ballPreviousX; + float m_ballPreviousY; + float m_leftBlockY; + float m_rightBlockY; + QTimer *m_timer; + float m_boardWidth; + float m_boardHeight; + float m_direction; + float m_targetX; + float m_targetY; + int interval; + int m_resultLeft; + int m_resultRight; + bool m_showDialog; + QString m_message; + int m_role; + float m_proportionX; + float m_proportionY; + bool m_serviceFound; +}; + +#endif // PINGPONG_H diff --git a/examples/bluetooth/pingpong/pingpong.pro b/examples/bluetooth/pingpong/pingpong.pro new file mode 100644 index 00000000..07675f27 --- /dev/null +++ b/examples/bluetooth/pingpong/pingpong.pro @@ -0,0 +1,19 @@ +TEMPLATE = app +TARGET = pingpong + +QT += quick bluetooth + +# Input +SOURCES += main.cpp \ + pingpong.cpp + +OTHER_FILES += assets/*.qml + +RESOURCES += \ + resource.qrc + +HEADERS += \ + pingpong.h + +target.path = $$[QT_INSTALL_EXAMPLES]/bluetooth/pingpong +INSTALLS += target diff --git a/examples/bluetooth/pingpong/resource.qrc b/examples/bluetooth/pingpong/resource.qrc new file mode 100644 index 00000000..1475a7f3 --- /dev/null +++ b/examples/bluetooth/pingpong/resource.qrc @@ -0,0 +1,8 @@ +<RCC> + <qresource prefix="/"> + <file>assets/main.qml</file> + <file>assets/Board.qml</file> + <file>assets/Dialog.qml</file> + <file>assets/Menu.qml</file> + </qresource> +</RCC> diff --git a/examples/bluetooth/scanner/doc/src/scanner.qdoc b/examples/bluetooth/scanner/doc/src/scanner.qdoc index 62b9680c..f4e292a8 100644 --- a/examples/bluetooth/scanner/doc/src/scanner.qdoc +++ b/examples/bluetooth/scanner/doc/src/scanner.qdoc @@ -1,5 +1,6 @@ /**************************************************************************** ** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Copyright (C) 2013 Aaron McCarthy <mccarthy.aaron@gmail.com> ** Contact: http://www.qt-project.org/legal ** @@ -28,6 +29,7 @@ /*! \example scanner \title QML Bluetooth Scanner Example +\brief A QML example about locating Bluetooth devices. This is an example on how to locate Bluetooth devices in QML. @@ -50,4 +52,7 @@ from local cache information and may not always be complete and accurate. The pr perform a minimal discovery are time constraints. A full service discovery can take up to two minutes. Note that not every platform supports a minimal discovery. In such cases the API performs a full discovery. +\include examples-run.qdocinc + +\sa {Qt Bluetooth} */ diff --git a/examples/bluetooth/scanner/qmlscanner.cpp b/examples/bluetooth/scanner/qmlscanner.cpp index 47d0bb26..5c09c8f3 100644 --- a/examples/bluetooth/scanner/qmlscanner.cpp +++ b/examples/bluetooth/scanner/qmlscanner.cpp @@ -47,7 +47,7 @@ int main(int argc, char *argv[]) { //QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true")); QGuiApplication application(argc, argv); - const QString mainQmlApp = QLatin1String("qrc:/scanner.qml"); + const QString mainQmlApp(QStringLiteral("qrc:/scanner.qml")); QQuickView view; view.setSource(QUrl(mainQmlApp)); view.setResizeMode(QQuickView::SizeRootObjectToView); |