NFC initiated Bluetooth chat application in QML
Article Metadata
Code Example
Tested with
Article
Contents |
Introduction
This code snippet shows how to use QML to find an NFC enabled device and connect to it using Bluetooth.
The application allows us to start a chat over Bluetooth initiated by NFC. When our application is running in the foreground on two devices we connect simply by touching the devices together. Once connected we send data over Bluetooth using sockets (as usual!)
How it data is available QML
The QDeclarativeItem class provides the most basic of all visual items in QML. So we need to derive our class from QDeclarativeItem.
class ConnectionNotifier : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY( QString msg READ msg WRITE setMsg )
public:
// Allow call directly C++ method from QML
Q_INVOKABLE void QuitApplication();
Q_INVOKABLE void SendMessage(const QString &aData);
public Q_SLOTS:
void showMessage(const QString & aMsg, const QString & aDevice);
void newDeviceFound();
Q_SIGNALS:
void notConnected();
void messageReceived(const QString & message);
private:
QString mMsg;
ConnectionEngine * mEngine;
};
QML Code
In this application we have created several rectangle element and all other items such as images, TextEdit are part of separate rectangle. Chat window is implemented as list box with model. When new message arrived we append the message to model.
ConnectionNotifier
{
id: myBtConnotifier
onNotConnected:
{
textEdit.text = "Not connected"
}
onMessageReceived:
{
nfcbtchat.append({"myself": "", "other": "Other:"+ myBtConnotifier.msg})
}
onServiceDiscoveredMsg:
{
textEdit.text = "Service Found, Connecting..."
}
onNewConnection:
{
textEdit.text = "Device connected..."
}
onNewDeviceFoundMsg:
{
textEdit.text = "Device found, looking service..."
}
onConnectionClosed:
{
textEdit.text = "Connection Closed"
}
}
How to use this example
There is a self signed sis file (debug version) in this project and that can be installed directly. At the bottom there are 3 icons. First one for sending message, second one is for clearing messages and the third one is for exiting the application. We can install the sis file to C7 and touch with each other and wait a bit then the hello world text will be changed to connected. After connection we can start chat. Following screenshot was taken with C7 devices.
Example Code
The following code was used to test and pass message from one phone to other over Bluetooth with two C7 devices with Belle. It looks there are some performance issues with mobility. It takes a significantly longer time than using a native socket for Bluetooth.
Download the example for C7: File:NFCBtChat.zip

