×

Discussion Board

Results 1 to 10 of 10
  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    5

    QtQuick+Bluetooth: stringData is empty

    Hello everyone,

    I got my Arduino BT connected to my N9 and I am able to send instructions from my Qt application to my bluetooth, a LED is turned on and after that it will response by sending a byte to the N9.

    I'm using QtQuick and the event 'onDataAvailable' is triggered. However if I read my console the stringData is empty, no matter what I do on my Arduino I am unable to retrieve any data.

    Do anyone got any idea why I am not receiving any bytes? misconfiguration in bit rate? (rfcomm uses 9600 and Arduino uses 115200?) or is it a bug??

    BlueToothScreen.qml:
    Code:
    import QtQuick 1.1
    import QtMobility.connectivity 1.2
    import QtMobility.systeminfo 1.1
    import com.nokia.meego 1.0
    
    Item {
    
        function sendData(theString) {
            blueSocket.sendStringData(theString);
        }
        property string btAddress: "00:07:MY:MAC:MASKED"
        property bool connceted: false
    
        BluetoothSocket {
            id: blueSocket
    
            connected: true
            service: blueService    // This is defined in BluetoothService element
    
            onErrorChanged: {
                console.log("Error: " + blueSocket.error) //Errors are printed in Application Output underneeth.
                blueToothText.text = blueSocket.error;
                blueSocket.connected = false;
            }
            onDataAvailable: {
                console.log("Alone: "+stringData);
                console.log("toString: "+stringData.toString());
                console.log("Length: "+stringData.length);
                if(stringData == "B" || stringData == 66) {
                    console.log("WE GOT THE B, YO!");
                }
            }
    
            onConnectedChanged: {
                console.log("Connection: " + connected);
            }
        }
    
        BluetoothService {
            id: blueService
    
            deviceAddress: btAddress                                //This is MAC address of your bluetooth module connected to Arduino
            serviceUuid: "00001101-0000-1000-8000-00805F9B34FB"     //famous UUID for serial port
            serviceProtocol: "rfcomm"                               //rfcomm emulates RS-232 serial ports. It uses 9600 baudrate, none parity, 8 bits, 1 stop bit
        }
    
        Timer {
            interval: 2500; running: true; repeat: true
            onTriggered: {
                if (blueSocket.connected == true) {
                    if(blueToothScreen.visible == true) {
                        hideBlueScreen.start();
                    }
                    connceted = true;
                } else {
                    if(blueToothScreen.visible == false) {
                        showBlueScreen.start();
                    }
                    connceted = false;
                }
            }
        }
    
        MouseArea {
            id: reconnectBlue
            width: 952; height: 507
            y: -14; x: -44; z: 2
            onReleased: {
                blueToothText.text = "Trying to connect to device...";
                blueSocket.connected = true;
            }
        }
    
        Image {
            y: -14; x: -44
            width: 952; height: 507
            fillMode: Image.Tile
            smooth: true
            source: "pics/bluetooth.png";
    
            Text {
                id: blueToothTitle
                x: 307; y: 225
                width: 410; height: 40
                text: "Bleutooth connection lost"
                wrapMode: Text.WordWrap
                color: "#ffffff"
                font { family: nokiaBold.name; pixelSize: 32; bold: true }
            }
    
            Text {
                id: blueToothText
                x: 307; y: 264
                width: 410; height: 40
                text: "Trying to connect to device..."
                wrapMode: Text.WordWrap
                color: "#ffffff"
                font { family: nokiaBold.name; pixelSize: 24 }
            }
        }
        PropertyAnimation {
           id: showBlueScreen
           target: blueToothScreen
           property: "opacity"
           easing.type: Easing.OutBack; duration: 1200
           from: 0; to: 1
           onStarted: {
               blueToothScreen.visible = true;
           }
        }
        PropertyAnimation {
           id: hideBlueScreen
           target: blueToothScreen
           property: "opacity"
           easing.type: Easing.OutBack; duration: 1200
           from: 1; to: 0
           onCompleted: {
               blueToothScreen.visible = false;
           }
        }
    }
    Response in console from (onDataAvailable):
    Code:
    Alone: 
    toString: 
    Length: 0

  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    5

    Re: QtQuick+Bluetooth: stringData is empty

    I'm losing my mind.. 4 days working on this problem and still no progress in receiving data....

    Should I try it in QML?
    Is it a BUG?
    Can I see (in my terminal) if there are bytes coming in?
    Somebody?

  3. #3
    Super Contributor
    Join Date
    Oct 2008
    Location
    INDIA
    Posts
    2,326

    Re: QtQuick+Bluetooth: stringData is empty

    I suggest you to use : QDataStream

    Data is sent and received via a QDataStream allowing type safe transfer of string data.

    Read this : QML BluetoothSocket Element

    regards,
    rahul

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    5

    Re: QtQuick+Bluetooth: stringData is empty

    Thanks a billion times champ! I was feeling alone!
    So the best practice now is just to build a QML (.h & .cpp) class and write that to my QtQuick application?

    I also forgot to mention I'm new to developing and this is a home brew app for my motor!
    I already got the rest of my application working (GPS speed, animations, notifications etc.etc.) the bluetooth commands is my last steps to get this project done
    The BT will eventually control relay's and send the GPS speed to a modified speedometer!

  5. #5
    Super Contributor
    Join Date
    Oct 2008
    Location
    INDIA
    Posts
    2,326

    Re: QtQuick+Bluetooth: stringData is empty

    Yes, Now, try to implement that, and If you face any problem in between, then again post your question here.

  6. #6
    Registered User
    Join Date
    Dec 2011
    Posts
    5

    Re: QtQuick+Bluetooth: stringData is empty

    Thanks again a billion time rahulvala!

    I got it working now including the signals and connection. I can retrieve data by sending the println function in Arduino to retrieve that data in C++. So I think I can say QtQuick's bluetooth is buggy.

  7. #7
    Registered User
    Join Date
    Jan 2010
    Posts
    272

    Re: QtQuick+Bluetooth: stringData is empty

    Quote Originally Posted by DragoslaV View Post
    Thanks again a billion time rahulvala!

    I got it working now including the signals and connection. I can retrieve data by sending the println function in Arduino to retrieve that data in C++. So I think I can say QtQuick's bluetooth is buggy.
    Care to share some code on how you did it? I have the same problem, I can send data but I cannot receive anything with stringData.

    Cheers
    http://www.ic-mobile.com/

  8. #8
    Registered User
    Join Date
    Dec 2011
    Posts
    5

    Re: QtQuick+Bluetooth: stringData is empty

    Yeah ofcourse I can! But I do got to say this codes are made for a single device, if you want to connect to variable devices you need to extend the connection function, however I saw example codes of that where I based my codes on )

    Please do note I am not an official developer so this codes can be optimized and the functions displayState needs to be removed.

    1. make a new .h file (I named this one bluetoothcontroller.h)
    Code:
    #ifndef BLUETOOTHCONTROLLER_H
    #define BLUETOOTHCONTROLLER_H
    
    #include <QtCore/QObject>
    #include <QIODevice>
    #include <QDataStream>
    #include <QBluetoothSocket>
    #include <QBluetoothAddress>
    #include <QBluetoothUuid>
    #include <QDateTime>
    #include <qmdisplaystate.h>
    #include "qmlapplicationviewer.h"
    
    QTM_BEGIN_NAMESPACE
    class QBluetoothSocket;
    QTM_END_NAMESPACE
    
    QTM_USE_NAMESPACE
    
    class BTController : public QObject
    {
        Q_OBJECT
    
    public:
        explicit BTController(QObject *parent = 0);
        ~BTController();
    
        MeeGo::QmDisplayState displayState;
    
        Q_INVOKABLE void printDisplayState();
        Q_INVOKABLE void turnOffDisplay();
        Q_INVOKABLE void turnOnDisplay();
    
        Q_INVOKABLE void startConnection();
        Q_INVOKABLE void stopConnection();
        Q_INVOKABLE void send(const QString &message);
    
    signals:
        void retrieve(const QString &sender, const QString &message);
        void btConnected(const QString &name);
        void btDisconnected();
        void btError(const QString &errorMessage);
    
    private slots:
        void readSocket();
        void connectSocket();
        void disconnectSocket();
        void socketError(QBluetoothSocket::SocketError errorMessage);
    
    private:
        QDataStream *stream;
        QBluetoothSocket *socket;
        BTController *bt;
    };
    
    #endif // BLUETOOTHCONTROLLER_H
    Make an new .cpp file (I named this one bluetoothcontroller.cpp)
    Code:
    #include <QtGui/QApplication>
    #include <QCoreApplication>
    #include <QDeclarativeEngine>
    #include <QDeclarativeComponent>
    #include <QIODevice>
    #include <QDataStream>
    #include <QBluetoothSocket>
    #include <QBluetoothAddress>
    #include <QBluetoothUuid>
    
    #include <qplatformdefs.h> // MEEGO_EDITION_HARMATTAN
    
    #ifdef HARMATTAN_BOOSTER
    #include <MDeclarativeCache>
    #endif
    
    #include <bluetoothcontroller.h>
    
    BTController::BTController(QObject *parent)
    :   QObject(parent), socket(0) {}
    
    BTController::~BTController() {
        startConnection();
    }
    
    void BTController::printDisplayState() {
        if (displayState.get() == MeeGo::QmDisplayState::On) {
            qDebug() << "The display is on!";
        }
        else if(displayState.get() == MeeGo::QmDisplayState::Off) {
            qDebug() << "The display is off!";
        }
    }
    void BTController::turnOffDisplay() {
        qDebug() << "Turning off display";
        displayState.set(MeeGo::QmDisplayState::Off);
    }
    
    void BTController::turnOnDisplay() {
        qDebug() << "Turning on display";
        displayState.set(MeeGo::QmDisplayState::On);
    }
    
    void BTController::startConnection() {
    
        const QBluetoothUuid uuid = QBluetoothUuid::SerialPort;
        //qDebug() << "C: uuid.toString" << uuid.toString();
    
        const QString myMacAdress = "YOUR:MAC:ADRESS";
        const QBluetoothAddress service(myMacAdress);
        //qDebug() << "C: service.toString" << service.toString();
    
        socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket);
        qDebug() << "C: Create socket";
        socket->connectToService(service,uuid,QIODevice::ReadWrite);
        qDebug() << "C: ConnecttoService done";
    
        connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
        connect(socket, SIGNAL(connected()), this, SLOT(connectSocket()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectSocket()));
        connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError)));
    
    }
    
    void BTController::stopConnection() {
        delete socket;
        socket = 0;
    }
    
    void BTController::readSocket() {
        if (!socket)
            return;
    
        while (socket->canReadLine()) {
            QByteArray line = socket->readLine();
    
            emit retrieve(socket->peerName(),
                                 QString::fromUtf8(line.constData(), line.length()));
        }
    }
    
    void BTController::send(const QString &message) {
        if (!socket)
            return;
    
        QByteArray text = message.toUtf8();
        socket->write(text);
        qDebug() << "C: Wrote: '"+text+"'";
    }
    
    void BTController::connectSocket() {
        qDebug() << "C: "+socket->peerName()+" connected";
        emit btConnected(socket->peerName());
    }
    
    void BTController::disconnectSocket() {
        qDebug() << "C: Disconnected";
        emit btDisconnected();
    }
    
    void BTController::socketError(QBluetoothSocket::SocketError errorMessage) {
        qDebug() << "C: Error: "+ errorMessage;
        emit btError(socket->errorString());
    }
    Now comes the tricky part, you want to add the C++ class to your QtQuick document
    First this is my main.cpp file:
    Code:
    #include <QtGui/QApplication>
    #include <QCoreApplication>
    #include <QDeclarativeView>
    #include <QDeclarativeContext>
    #include <QDeclarativeEngine>
    #include <QDeclarativeComponent>
    #include <QIODevice>
    #include <QDataStream>
    #include <QBluetoothSocket>
    #include "bluetoothcontroller.h"
    #include "qmlapplicationviewer.h"
    
    Q_DECL_EXPORT int main(int argc, char *argv[])
    {
        QScopedPointer<QApplication> app(createApplication(argc, argv));
        QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
    
        QDeclarativeContext *ctxt = viewer->rootContext();
    
        BTController bt;
        ctxt->setContextProperty("blueTooth", &bt);
    
        viewer->setOrientation(QmlApplicationViewer::ScreenOrientationLockLandscape);
        viewer->setMainQmlFile(QLatin1String("qml/ZoomerDashboard/main.qml"));
        viewer->showExpanded();
    
        bt.startConnection();//call function for auto-start BT 
    
        return app->exec();
    }
    However, to make setContextProperty work we need to update qmlapplicationviewer.h and qmlapplicationviewer.cpp
    This is my qmlapplicationviewer.h file (note that all that was add'd is the QDeclarativeContext)
    Code:
    // checksum 0x82ed version 0x60010
    /*
      This file was generated by the Qt Quick Application wizard of Qt Creator.
      QmlApplicationViewer is a convenience class containing mobile device specific
      code such as screen orientation handling. Also QML paths and debugging are
      handled here.
      It is recommended not to modify this file, since newer versions of Qt Creator
      may offer an updated version of it.
    */
    
    #ifndef QMLAPPLICATIONVIEWER_H
    #define QMLAPPLICATIONVIEWER_H
    
    #include <QtDeclarative/QDeclarativeView>
    #include <QtDeclarative/QDeclarativeComponent>
    #include <QtDeclarative/QDeclarativeEngine>
    #include <QtDeclarative/QDeclarativeContext>
    
    class QmlApplicationViewer : public QDeclarativeView
    {
        Q_OBJECT
    
    public:
        QDeclarativeContext *rootContext();
    
        enum ScreenOrientation {
            ScreenOrientationLockPortrait,
            ScreenOrientationLockLandscape,
            ScreenOrientationAuto
        };
    
        explicit QmlApplicationViewer(QWidget *parent = 0);
        virtual ~QmlApplicationViewer();
    
        static QmlApplicationViewer *create();
    
        void setMainQmlFile(const QString &file);
        void addImportPath(const QString &path);
    
        // Note that this will only have an effect on Symbian and Fremantle.
        void setOrientation(ScreenOrientation orientation);
    
        void showExpanded();
    
    private:
        explicit QmlApplicationViewer(QDeclarativeView *view, QWidget *parent);
        class QmlApplicationViewerPrivate *d;
    };
    
    QApplication *createApplication(int &argc, char **argv);
    
    #endif // QMLAPPLICATIONVIEWER_H
    This is my qmlapplicationviewer.cpp file (note that all that was add'd is the QDeclarativeContext)
    Code:
    ....default codes....
    
    #include <QtCore/QDir>
    #include <QtCore/QFileInfo>
    #include <QtDeclarative/QDeclarativeComponent>
    #include <QtDeclarative/QDeclarativeEngine>
    #include <QtDeclarative/QDeclarativeContext>
    #include <QtGui/QApplication>
    
    ....default codes....
    
    class QmlApplicationViewerPrivate
    {
        QmlApplicationViewerPrivate(QDeclarativeView *view_) : view(view_) {}
    
        QString mainQmlFile;
        QDeclarativeView *view;
        friend class QmlApplicationViewer;
        QString adjustPath(const QString &path);
    };
    
    ....default codes....
    
    QDeclarativeContext *QmlApplicationViewer::rootContext()
    {
        return d->view->rootContext();
    }
    
    ...... default codes....
    With that, you can access "blueTooth" within your QtQuick document, for example the Connections:
    Code:
        Connections {
            target: blueTooth
            onBtConnected: {
                console.log("QT: The connection changed: connected!");
            }
            onBtDisconnected: {
                console.log("QT: The connection changed: disconnected!");
            }
            onRetrieve: {
                var messageNew = message;
                messageNew = messageNew.replace("\n", "");
                messageNew = messageNew.replace("\r", "");
    
                console.log("dataRetrieved message: "+messageNew);
            }
            onBtError: {
                console.log("QT: Error: " + errorMessage);
            }
        }
    or manually connect by using 'blueTooth.startConnection();' or send by 'blueTooth.send(STRING);'

    One issue I still haven't resolved:
    * The error message within the onBtError will never show the right error, its always empty.

    Another note:
    * Once you changed the 'qmlapplicationviewer' files, QtCreator will check this files on startup, once you press 'Yes' in the revert files dialog, you will loose your rootContext function. So once you have it working make a backup of those files!

  9. #9
    Registered User
    Join Date
    Jun 2012
    Posts
    2

    Re: QtQuick+Bluetooth: stringData is empty

    Hi, you got this working with the codes above. I tried to implement it to my project without any luck.
    Would you want to be so nice that you would share the full project files with me so that i can test this.
    I have a problem with even sending data with the quick component. It is sending something but my dspic can't read the strings sent from N9.
    My Pc terminal can read the strings and my dspic can send strings to PC terminal but N9 => to dspic through BT module is non-functional.
    This works with E72 to dspic with bluetoothzero library. I just am not sure what the problem is. Is it the string format or... When i turn my dspic terminal to Hex mode, i see that it receives (if i send "AA\r\n")

    00 00 00 41 00 02 00 41 00 00 02... bla bla where the 0x41 is char 'A' and there is also the 0D and 0A i.e. char 13 and 10 respectively. There is just some freakin null characters sent also...

    If you are nice => peter@lydman.fi

    I'm working on a timelapse controller. It works on E72 but as i got a N9 it would be nice not to have to carry around 2 phones

  10. #10
    Registered User
    Join Date
    Jun 2012
    Posts
    2

    Re: QtQuick+Bluetooth: stringData is empty

    Actually i now have problems when trying to build project:

    ...\qmlapplicationviewer.cpp:84: error: no matching function for call to 'QmlApplicationViewerPrivate::QmlApplicationViewerPrivate()'
    ...\qmlapplicationviewer.cpp:32: candidates are: QmlApplicationViewerPrivate::QmlApplicationViewerPrivate(QDeclarativeView*)
    ...\qmlapplicationviewer.cpp:31: note: QmlApplicationViewerPrivate::QmlApplicationViewerPrivate(const QmlApplicationViewerPrivate&)

    Can someone say whats wrong. Im very bad at coding QT...

Similar Threads

  1. how to make qtquick mutiplatform
    By vladest in forum [Archived] Qt Quick
    Replies: 3
    Last Post: 2011-10-19, 05:46
  2. QtQuick 1.1 available?? Help please
    By lukakiarelli in forum [Archived] Qt Quick
    Replies: 4
    Last Post: 2011-06-21, 07:01
  3. QtQuick and QWebFrame::toPlainText()
    By ad5xj in forum [Archived] Qt Quick
    Replies: 1
    Last Post: 2011-04-17, 17:24
  4. QtQuick/QML or Native
    By bluechrism in forum [Archived] Qt Quick
    Replies: 1
    Last Post: 2011-02-27, 22:26

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •