Connect and read data automatically from BLE weight scale in Qt application - qt

I'm developing a Qt app which need to read data from weight scale model and can't quite understand how exactly the Bluetooth Low Energy works and how to implement it in Qt.
I have a UC-352BLE weight scale which uses BLE to send data. What I want to achieve is this:
After initial pairing the scale with my Raspberry Pi on which my app is running, when the scale sends data (it does it automatically when you take a measurement), my app receive it. For example I have a blood pressure monitor which uses normal Bluetooth and here it's easy. In my app, I create a QBluetoothServer and call its listen() method. Then when the (already paired) device sends a measurement, it connects with my app automatically, then I create QBluetoothSocket and read the data. But with the scale and it's BLE it seems that you can't do it that way. I tried to follow the Qt documentation on this and right now I just have to manually press the button which connects to the scale when it's sending the data. And every time it connects to the device it discovers it's characteristics and services etc. Don't know if I can do it so the app automatically receives a connection and reads a data when the scale sends a measurement. And even when I try to connects like that sometimes it connects and sometimes don't (I get Unknown error form QLowEnergyController::Error when connecting). Here is what I already have:
Bletest::Bletest(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::Bletest)
{
ui->setupUi(this);
if (localDevice.isValid()) {
localDevice.powerOn();
localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
connect(&localDevice, &QBluetoothLocalDevice::deviceConnected, this, &Bletest::deviceConnected);
connect(&localDevice, &QBluetoothLocalDevice::deviceDisconnected, this, &Bletest::deviceDisconnected);
connect(&localDevice, &QBluetoothLocalDevice::pairingFinished, this, &Bletest::pairingFinished);
}
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &Bletest::addDevice);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &Bletest::scanFinished);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::canceled, this, &Bletest::scanFinished);
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
}
Bletest::~Bletest()
{
delete ui;
}
// Local device slots
void Bletest::deviceConnected(const QBluetoothAddress &address)
{
qDebug() << address.toString() << " connected";
}
void Bletest::deviceDisconnected(const QBluetoothAddress &address)
{
qDebug() << address.toString() << " disconnected";
}
void Bletest::pairingFinished(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
}
// Agent slots
void Bletest::addDevice(const QBluetoothDeviceInfo &device)
{
if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
if (device.name().contains("352")) {
bleDevice = device;
qDebug() << "Found: " + device.name() + "\t" + device.address().toString();
}
}
}
void Bletest::scanFinished()
{
qDebug() << "Devices scan finished";
}
///////////
void Bletest::on_connectButton_clicked()
{
controller = QLowEnergyController::createCentral(bleDevice, this);
connect(controller, &QLowEnergyController::serviceDiscovered, this, &Bletest::serviceDiscovered);
connect(controller, &QLowEnergyController::discoveryFinished, this, &Bletest::serviceScanFinished);
connect(controller, static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, [this](QLowEnergyController::Error error) {
qDebug() << "Cannot connect to device: " + QString::number(error);
});
connect(controller, &QLowEnergyController::connected, this, [this]() {
qDebug() << "Connected to device";
controller->discoverServices();
});
connect(controller, &QLowEnergyController::disconnected, this, [this]() {
qDebug() << "Disconnected";
});
controller->connectToDevice();
}
// Controller slots
void Bletest::serviceDiscovered(const QBluetoothUuid &gatt)
{
qDebug() << "Service discovered: " << gatt.toString();
if (gatt.toString().contains("0000181d-0000-1000-8000-00805f9b34fb")) {
service = controller->createServiceObject(QBluetoothUuid(QBluetoothUuid::WeightScale));
if (service) {
qDebug() << "Found weight scale service";
connect(service, &QLowEnergyService::stateChanged, this, &Bletest::serviceStateChanged);
connect(service, &QLowEnergyService::characteristicChanged, this, &Bletest::updateWeight);
connect(service, &QLowEnergyService::characteristicRead, this, &Bletest::updateWeight);
service->discoverDetails();
}
}
}
void Bletest::serviceScanFinished()
{
qDebug() << "Service scan finished";
}
////////////////////////////
// Service slots
void Bletest::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
if (controller->state() == QLowEnergyController::UnconnectedState)
return;
if (newState == QLowEnergyService::DiscoveringServices) {
qDebug() << "Discovering services state";
} else if (QLowEnergyService::ServiceDiscovered) {
qDebug() << "Service discovered.";
const QLowEnergyCharacteristic weightChar = service->characteristic(QBluetoothUuid(QBluetoothUuid::WeightMeasurement));
if (!weightChar.isValid()) {
qDebug() << "Weight data not found";
return;
}
qDebug() << "Weight data found";
//service->readCharacteristic(weightChar);
desc = weightChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (desc.isValid()) {
qDebug() << "Writing descriptor";
service->writeDescriptor(desc, QByteArray::fromHex("0100"));
}
}
}
void Bletest::updateWeight(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
qDebug() << "Updating weight";
if (c.uuid() != QBluetoothUuid(QBluetoothUuid::WeightMeasurement))
return;
double weight = qFromLittleEndian<qint16>(value.mid(1, 2).data()) * RESOLUTION;
qDebug() << "New weight: " << value.mid(1, 2);
qDebug() << "New weight: " + QString::number(weight, 'f', 2);
}
///////////////////////////
Can someone point me in the right direction with this? Is is even possible with BLE to automatically connects to my app and receive data?
Thanks.

Related

Qt - Cannot read descriptor of the characteristic - BLE

I have a problem with reading characteristic using Bluetooth Low Energy Qt api. The device I'm communicating with is a Decawave DWM1001 module. I was following the tutorial from the documentation. I managed to connect to the device, read and creates it's service successfully. The device has "network node service" with UUID: 680c21d9-c946-4c1f-9c11-baa1c21329e7, which I'm trying to read characteristics from. I call QLowEnergyController::connectToDevice() method, it finds the service and I create a QLowEnergyService object for it, named nodeService.
void BluetoothConnector::serviceDiscovered(const QBluetoothUuid &newService)
{
qDebug() << "Service discovered: " << newService.toString();
if (newService == QBluetoothUuid(nodeServiceUUID)) {
nodeService = controller->createServiceObject(QBluetoothUuid(nodeServiceUUID), this);
if (nodeService) {
qDebug() << "Node service created";
connect(nodeService, &QLowEnergyService::stateChanged, this, &BluetoothConnector::serviceStateChanged);
connect(nodeService, &QLowEnergyService::characteristicChanged, this, &BluetoothConnector::updateCharacteristic);
//connect(nodeService, &QLowEnergyService::descriptorWritten, this, &BLTest::confirmedDescriptorWrite);
nodeService->discoverDetails();
} else {
qDebug() << "Node service not found.";
}
}
}
nodeService is created successfully (I get "Node service created" log), then I connect the signals and slots for the service and then call discoverDetails() on nodeService. The serviceStateChanged() slot looks like this:
void BluetoothConnector::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
if (newState == QLowEnergyService::DiscoveringServices) {
qDebug() << "Discovering services";
} else if (newState == QLowEnergyService::ServiceDiscovered) {
qDebug() << "Service discovered";
const QLowEnergyCharacteristic networkIdChar = nodeService->characteristic(QBluetoothUuid(networkIdUUID));
const QLowEnergyCharacteristic dataModeChar = nodeService->characteristic(QBluetoothUuid(dataModeUUID));
const QLowEnergyCharacteristic locationChar = nodeService->characteristic(QBluetoothUuid(locationUUID));
if (networkIdChar.isValid() && dataModeChar.isValid() && locationChar.isValid()) {
auto idValue = networkIdChar.value();
auto modeValue = dataModeChar.value();
auto locValue = locationChar.value();
qDebug() << "Network ID: " << idValue;
qDebug() << "Mode: " << modeValue;
qDebug() << "Location: " << locValue;
auto notificationDesc = locationChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (notificationDesc.isValid()) {
qDebug() << "Notification desc valid";
nodeService->writeDescriptor(notificationDesc, QByteArray::fromHex("0100"));
}
} else {
qDebug() << "Characteristic invalid";
}
}
}
I get the "Discovering services" log and after that the app hangs for a bit and then I get:
"Cannot read descriptor (onDescReadFinished 3): \"{00002902-0000-1000-8000-00805f9b34fb}\" \"{3f0afd88-7770-46b0-b5e7-9fc099598964}\" \"org.freedesktop.DBus.Error.NoReply\" \"Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.\""
"LowEnergy controller disconnected"
"Aborting onCharReadFinished due to disconnect"
It can't read the 00002902-0000-1000-8000-00805f9b34fb which is CCCD descriptor for the 3f0afd88-7770-46b0-b5e7-9fc099598964 characteristic (vendor specific).
Can't figure out what's wrong and why it can't read characteristics from the device. Do I need to do something else to make it work?
Thanks.
---UPDATE---
BluetoothConnector class:
#include "bluetoothconnector.h"
#include <QTimer>
BluetoothConnector::BluetoothConnector(QObject *parent) : QObject(parent)
{
configureDiscoveryAgent();
}
void BluetoothConnector::scan()
{
agent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
}
void BluetoothConnector::connectToDevice(QString &addr)
{
auto it = std::find_if(devices.begin(), devices.end(),
[&] (const QBluetoothDeviceInfo& d) { return d.address().toString() == addr; });
if (it == devices.end())
return;
device = *it;
controller = QLowEnergyController::createCentral(device, this);
connect(controller, &QLowEnergyController::serviceDiscovered, this, &BluetoothConnector::serviceDiscovered);
connect(controller, &QLowEnergyController::discoveryFinished, this, &BluetoothConnector::serviceScanDone);
connect(controller, static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, [this](QLowEnergyController::Error error) {
Q_UNUSED(error);
qDebug() << "Controller error: " << error;
emit controllerError();
});
connect(controller, &QLowEnergyController::connected, this, [this]() {
qDebug() << "Controller connected. Search services...";
controller->discoverServices();
});
connect(controller, &QLowEnergyController::disconnected, this, [this]() {
qDebug() << "LowEnergy controller disconnected";
});
controller->connectToDevice();
}
void BluetoothConnector::configureDiscoveryAgent()
{
agent = new QBluetoothDeviceDiscoveryAgent(this);
agent->setLowEnergyDiscoveryTimeout(5000);
connect(agent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothConnector::addDevice);
connect(agent, static_cast<void (QBluetoothDeviceDiscoveryAgent::*)(QBluetoothDeviceDiscoveryAgent::Error)>(&QBluetoothDeviceDiscoveryAgent::error),
this, &BluetoothConnector::scanError);
connect(agent, &QBluetoothDeviceDiscoveryAgent::finished, this, &BluetoothConnector::scanFinished);
connect(agent, &QBluetoothDeviceDiscoveryAgent::canceled, this, &BluetoothConnector::scanFinished);
}
void BluetoothConnector::addDevice(const QBluetoothDeviceInfo &info)
{
if (!devices.contains(info)) {
qDebug() << "Found device: " << info.name();
devices.append(info);
emit deviceFound(info);
}
}
void BluetoothConnector::scanError(QBluetoothDeviceDiscoveryAgent::Error error)
{
qDebug() << "Scan error: " << error;
}
void BluetoothConnector::scanFinished()
{
emit scanFinishedSignal();
}
void BluetoothConnector::serviceDiscovered(const QBluetoothUuid &newService)
{
qDebug() << "Service discovered: " << newService.toString();
if (newService == QBluetoothUuid(nodeServiceUUID)) {
nodeService = controller->createServiceObject(QBluetoothUuid(nodeServiceUUID), this);
qDebug() << "State: " << nodeService->state();
if (nodeService) {
qDebug() << "Node service created";
connect(nodeService, &QLowEnergyService::stateChanged, this, &BluetoothConnector::serviceStateChanged);
connect(nodeService, &QLowEnergyService::characteristicChanged, this, &BluetoothConnector::updateCharacteristic);
connect(nodeService, &QLowEnergyService::characteristicWritten, this, &BluetoothConnector::characteristicWritten);
connect(nodeService, QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::error),
[=](QLowEnergyService::ServiceError newError){ qDebug() << newError; });
//connect(nodeService, &QLowEnergyService::descriptorWritten, this, &BLTest::confirmedDescriptorWrite);
nodeService->discoverDetails();
} else {
qDebug() << "Node service not found.";
}
}
}
void BluetoothConnector::serviceScanDone()
{
qDebug() << "Services scan done";
}
void BluetoothConnector::characteristicWritten(const QLowEnergyCharacteristic &info, const QByteArray &value)
{
qDebug() << "Characteristic written: " << info.name();
}
void BluetoothConnector::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
qDebug() << "State changed: " << newState;
if (newState == QLowEnergyService::ServiceDiscovered) {
qDebug() << "Service discovered";
const QLowEnergyCharacteristic networkIdChar = nodeService->characteristic(QBluetoothUuid(networkIdUUID));
const QLowEnergyCharacteristic dataModeChar = nodeService->characteristic(QBluetoothUuid(dataModeUUID));
const QLowEnergyCharacteristic locationChar = nodeService->characteristic(QBluetoothUuid(locationUUID));
if (networkIdChar.isValid() && dataModeChar.isValid() && locationChar.isValid()) {
auto idValue = networkIdChar.value();
auto modeValue = dataModeChar.value();
auto locValue = locationChar.value();
qDebug() << "Network ID: " << idValue;
qDebug() << "Mode: " << modeValue;
qDebug() << "Location: " << locValue;
auto notificationDesc = locationChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (notificationDesc.isValid()) {
qDebug() << "Notification desc valid";
nodeService->writeDescriptor(notificationDesc, QByteArray::fromHex("0100"));
}
} else {
qDebug() << "Characteristic invalid";
}
}
}
void BluetoothConnector::updateCharacteristic(const QLowEnergyCharacteristic &info, const QByteArray &value)
{
if (info.uuid() == QBluetoothUuid(networkIdUUID)) {
qDebug() << "Update ID: " << value;
} else if (info.uuid() == QBluetoothUuid(dataModeUUID)) {
qDebug() << "Update mode: " << value;
} else if (info.uuid() == QBluetoothUuid(locationUUID)) {
qDebug() << "Update location: " << value;
}
}
I think, the problem is located on the remote side (your GATT server).
Check the QLowEnergyService::error() and QLowEnergyService::charcteristicWritten() signal and see if you get any response.
What kind of Bluetooth stack you are use on the remote side?
Might be, you don't have the rights to change the CCCD due to a implementation failure. Please check the implementation on the remote side.

Qt: RFCOMM BluetoothSocket Connection Problems after switching Pages in QML

I'm developing an cross plattform Application in Qt Creator, which has the exercise to control a device via Classic Bluetooth. I have a communication protocol. FIRST: I can connect to device and write Data to it with BluetoothSocket. If I put the startMotor() function into the socketConnected SLOT after beepBuzzor() command then it works fine and I get state() connected.
My problem is if I switch the page in my Application on Android and click on the "start motor" button, I get the state() unconnected, but I am still connected to the device because the LED on the device shows connected. My app does not crash. I think the problem is in the line with socket->connectToService(...), but I'm unsure what to change. The beepBuzzor command works fine, startMotor command too. But if I call the function after successfully connectToService() it does not work because the state is unconnected.
BluetoothManager::BluetoothManager(QObject *parent) : QObject(parent)
{
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
}
void BluetoothManager::startDiscovery()
{
// Check if Bluetooth is available on this device
if (localDevice.isValid()) {
qDebug() << "Bluetooth is available on this device";
//Turn BT on
localDevice.powerOn();
// Make it visible to others
localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
//Read local device name & address
qDebug() << "Local Device:" << localDevice.name() << "(" << "Address:" << localDevice.address() << ")";
// Create a discovery agent and connect to its signals
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, SIGNAL(finished()), this, SLOT(deviceDiscoverFinished()));
// Start a discovery
// Trick: da es kein DiscoveryTimer für Classic gibt, suchen wir nach LE devices, da BT121 BLE unterstützt.
// Die Verbindung erfolgt jedoch über RFCOMM sobald man sich mit dem Gerät verbindet.
discoveryAgent->setLowEnergyDiscoveryTimeout(5000);
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
qDebug() << "Device discover started";
}
else
{
qDebug() << "Bluetooth is not available on this device";
}
}
//SLOT for the finish of device Discovery
void BluetoothManager::deviceDiscoverFinished()
{
qDebug() << "Device discover finished";
listOfDevices = discoveryAgent->discoveredDevices();
qDebug() << "Found new devices:";
for (int i = 0; i < listOfDevices.size(); i++)
{
//Q_OS_IOS / MAC do not need here cuz the run is on android device, delete later
//We do not find galileo device on MacBook
#if defined (Q_OS_IOS) || defined (Q_OS_MAC)
// On MacOS and iOS we get no access to device address,
// only unique UUIDs generated by Core Bluetooth.
qDebug() << "getting address from deviceUuid()" << listOfDevices.at(i).name().trimmed()
<< " ( " << listOfDevices.at(i).deviceUuid().toString().trimmed() << " ) ";
setDevice(listOfDevices.at(i).name().trimmed() + " (" + listOfDevices.at(i).deviceUuid().toString().trimmed() + ")");
#else
qDebug() << listOfDevices.at(i).name().trimmed()
<< " ("
<< listOfDevices.at(i).address().toString().trimmed()
<< ")";
setDevice(listOfDevices.at(i).name().trimmed() + " (" + listOfDevices.at(i).address().toString().trimmed() + ")");
#endif
}
}
/**
* In GUI (QML) user select a device with index i.
* Create a new socket, using Rfcomm protocol to communicate
*/
void BluetoothManager::deviceSelected(int i)
{
selectedDevice = listOfDevices.at(i);
#if defined (Q_OS_IOS) || defined (Q_OS_MAC)
qDebug() << "User select a device: " << selectedDevice.name() << " ("
<< selectedDevice.deviceUuid().toString().trimmed() << ")";
#else
qDebug() << "User select a device: " << selectedDevice.name() << " ("
<< selectedDevice.address().toString().trimmed() << ")";
#endif
if (localDevice.pairingStatus(selectedDevice.address())== QBluetoothLocalDevice::Paired)
{
qDebug() << "Pairing is allready done";
}
else
{
qDebug() << "Not paired. Please do pairing first for communication with device!";
}
selecDevAdress = selectedDevice.address();
connectToSvc();
//Connect SIGNALS with SLOTS
connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError)));
connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(socketRead()));
connect(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState)), this, SLOT(socketStateChanged()));
}
void BluetoothManager::connectToSvc()
{
qDebug() << "Create socket";
//socket->connectToService(selecDevAdress, QBluetoothUuid(QString("00001101-0000-1000-8000-00805F9B34FB")), QIODevice::ReadWrite);
//static const QString serviceUuid(QStringLiteral("00001101-0000-1000-8000-00805F9B34FB"));
socket->connectToService(selectedDevice.address(), QBluetoothUuid(QString("00001101-0000-1000-8000-00805F9B34FB")), QIODevice::ReadWrite);
//Also works with this line instead of the two above (with declaration of serviceUuid)
//socket->connectToService(QBluetoothAddress(selectedDevice.address()),QBluetoothUuid(QBluetoothUuid::SerialPort));
socket->open(QIODevice::ReadWrite);
socket->openMode();
}
//SLOT wenn Socket verbunden ist
void BluetoothManager::socketConnected()
{
//qDebug() << ("Connected to: "+socket->peerAddress().toString() +":"+socket->peerPort());
qDebug() << ("Connected to: "+socket->peerAddress().toString());
qDebug() << "Socket connected";
qDebug() << "Local: "
<< socket->localName()
<< socket->localAddress().toString()
<< socket->localPort();
qDebug() << "Peer: "
<< socket->peerName()
<< socket->peerAddress().toString()
<< socket->peerPort();
//Do "beep" sound commando after succesfull connection to Galileo device
beepBuzzor();
}
/**
* Socket disconnected.
* Delete socket, free the memory.
*/
//SLOT für Verbindungsabbruch von Socket
void BluetoothManager::socketDisconnected()
{
qDebug() << "Socket disconnected";
socket->deleteLater();
}
void BluetoothManager::socketError(QBluetoothSocket::SocketError error)
{
qDebug() << "Socket error: " << error;
}
void BluetoothManager::socketStateChanged()
{
int socketState = socket->state();
if(socketState == QAbstractSocket::UnconnectedState)
{
qDebug() << "unconnected";
}
else if(socketState == QAbstractSocket::HostLookupState)
{
qDebug() << "host lookup";
}
else if(socketState == QAbstractSocket::ConnectingState )
{
qDebug() << "connecting";
}
else if(socketState == QAbstractSocket::ConnectedState)
{
qDebug() << "connected";
}
else if(socketState == QAbstractSocket::BoundState)
{
qDebug() << "bound";
}
else if(socketState == QAbstractSocket::ClosingState)
{
qDebug() << "closing";
}
else if(socketState == QAbstractSocket::ListeningState)
{
qDebug() << "listening";
}
}
// SLOT when data ready on bluetooth socket
void BluetoothManager::socketRead()
{
qDebug() << "socketRead()";
QByteArray recievedData = socket->readAll();
emit dataRecieved(recievedData);
}
/**
* Get a string with device info
*/
const QString &BluetoothManager::device() const
{
return deviceInfo;
}
void BluetoothManager::setDevice(const QString &newDevice)
{
if (newDevice != deviceInfo) {
deviceInfo = newDevice;
emit deviceChanged();
}
}
void BluetoothManager::beepBuzzor()
{
QByteArray beep;
beep.append(QByteArray::fromRawData("\x04\x00\x09\xD0\x07\x32\x00", 7));
command(beep);
}
void BluetoothManager::startMotor()
{
qDebug() << "startMotor slot";
if(socket->state() == QBluetoothSocket::UnconnectedState){
qDebug() << "Socket Unconnected";
}
else{
qDebug() << "Socket Unonnected";
}
socketStateChanged();
//command(start);
}
void BluetoothManager::command(QByteArray &cmdBuf)
{
socket->write(cmdBuf);
}

QTcpSocket data arrives late

I am using QTCPSockets to talk to a program I've written in Qt for Raspberry Pi. The same software runs on my Mac (or Windows, whatever). The Pi is running a QTCPServer.
I send JSON data to it and most of the time this goes ok.
But sometimes, the Pi is not responding, the data does not seem to arrive. But then, when I send some more data, that data is not being handled, but the previous Json message is! And this stays like this. All the messages are now off by 1. Sending a new messages, triggers the previous one.
It feels a bit connected to this bugreport: https://bugreports.qt.io/browse/QTBUG-58262
But I'm not sure if it is the same.
I've tried waitForBytesWritten and flush and it seemed to work at first, but later I saw the issue again.
I expect that the TCP buffer on the Pi is not being flushed, but I do now know how to make sure that all data is handled right away.
As asked, here is some sourcecode:
This is the client software:
Client::Client() : tcpSocket(new QTcpSocket(this)), in(tcpSocket)
{
connect(tcpSocket, &QIODevice::readyRead, this, &Client::readData);
connect(tcpSocket, &QTcpSocket::connected, this, &Client::connected);
connect(tcpSocket, &QTcpSocket::stateChanged, this, &Client::onConnectionStateChanged);
void (QAbstractSocket:: *sig)(QAbstractSocket::SocketError) = &QAbstractSocket::error;
connect(tcpSocket, sig, this, &Client::error);
}
void Client::connectTo(QString ip, int port) {
this->ip = ip;
this->port = port;
tcpSocket->connectToHost(ip, port);
}
void Client::reconnect() {
connectTo(ip, port);
}
void Client::disconnect()
{
tcpSocket->disconnectFromHost();
}
void Client::connected()
{
qDebug() << TAG << "connected!";
}
void Client::error(QAbstractSocket::SocketError error)
{
qDebug() << TAG << error;
}
void Client::sendData(const QString& data)
{
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << "NOT CONNECTED!";
return;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
tcpSocket->write(block);
tcpSocket->flush();
}
void Client::sendData(const QByteArray& data) {
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << " is NOT connected!";
return;
}
tcpSocket->write(data);
tcpSocket->flush();
}
void Client::readData()
{
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
emit dataReceived(data);
}
void Client::onConnectionStateChanged(QAbstractSocket::SocketState state)
{
switch (state) {
case QAbstractSocket::UnconnectedState:
connectionState = "Not connected";
break;
case QAbstractSocket::ConnectingState:
connectionState = "connecting";
break;
case QAbstractSocket::ConnectedState:
connectionState = "connected";
break;
default:
connectionState = QString::number(state);
}
qDebug() << TAG << " connecting state: " << state;
emit connectionStateChanged(connectionState);
if (state == QAbstractSocket::UnconnectedState) {
QTimer::singleShot(1000, this, &Client::reconnect);
}
}
and here the server part:
Server::Server()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &Server::handleConnection);
tcpServer->listen(QHostAddress::Any, 59723);
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
qDebug() << TAG << "ip " << ipAddress << " serverport: " << tcpServer->serverPort();
}
void Server::clientDisconnected()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
int idx = clients.indexOf(client);
if (idx != -1) {
clients.removeAt(idx);
}
qDebug() << TAG << "client disconnected: " << client;
client->deleteLater();
}
void Server::handleConnection()
{
qDebug() << TAG << "incoming!";
QTcpSocket* clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, &QAbstractSocket::disconnected, this, &Server::clientDisconnected);
connect(clientConnection, &QIODevice::readyRead, this, &Server::readData);
clients.append(clientConnection);
broadcastUpdate(Assets().toJson());
}
void Server::readData()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
QDataStream in(client);
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
...
// here I do something with the data. I removed that code as it is
// not necessary for this issue
...
broadcastUpdate(data);
}
void Server::broadcastUpdate(const QString& data)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
foreach(QTcpSocket* client, clients) {
bool connected = (client->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << client << " is NOT connected!";
continue;
}
client->write(block);
}
}
I think the problem is with your void Client::readData(): you have to write it in such a way that you read all available data from the socket inside it (usually it's written with while (socket->bytesAvailable() > 0) { ... } loop).
It is because of the way the readyRead() signal is emitted: the remote peer may send any non-zero number of packets to you, and your socket will emit any non-zero number of readyRead() signals. In your case, it seems that the server sends two messages but they only cause one readyRead() signal to be emitted on the client.

QDialog show is does not happen immediately

I have a sever client application and in the beginning client loads data from server. I have a dialog showing status of getting data from server (has progress bar). But when I call the function the dialog appears with no contents in it with white background and suddenly changes to completed status.
void SystemScreen::loadServerData()
{
qDebug() << Q_FUNC_INFO << "Invoked";
if (NULL != mpDataManagerDlg)
{
qDebug() << Q_FUNC_INFO << "show progres screen";
mpDataManagerDlg->showScreen();
}
loadData();
qDebug() << Q_FUNC_INFO << "Exits";
}
void SystemScreen::loadData()
{
qDebug() << Q_FUNC_INFO << "Invoked";
if (NULL != mpDataManager)
{
mpDataManager->loadDataFromServer();
}
qDebug() << Q_FUNC_INFO << "Exits";
}
I feel that dialog is displayed only after loadData() function is completed. Is there any alternative to do this?
I used a timer to start
QTimer::singleShot(100, this, SLOT(loadData()));
But then I have some trouble in getting data. ie data is empty if I read suddenly.
EDIT:
void DataManagerDialog::setDefault()
{
qDebug() << Q_FUNC_INFO << "Invoked";
setProgressBar(0);
setProgressBarColor(false);
ui->deptFailButton->hide();
ui->deptOkButton->hide();
ui->deptLabel->setStyleSheet("color:gray");
ui->subGroupFailButton->hide();
ui->subGroupOkButton->hide();
ui->subGroupLabel->setStyleSheet("color:gray");
ui->itemFailButton->hide();
ui->itemOkButton->hide();
ui->itemLabel->setStyleSheet("color:gray");
ui->salesBtnFailButton->hide();
ui->salesBtnOkButton->hide();
ui->salesBtnLabel->setStyleSheet("color:gray");
qDebug() << Q_FUNC_INFO << "Exits";
}
void DataManagerDialog::alignCenter()
{
qDebug() << Q_FUNC_INFO << "Invoked";
QWidget *par = parentWidget();
if (par)
{
int x = width()/2;
int y = height()/2;
QPoint mid(mapToGlobal(QPoint(x, y)));
int px = par->width()/2;
int py = par->height()/2;
QPoint parMid(mapToGlobal(QPoint(px, py)));
move(parMid.x()-mid.x(), parMid.y()-mid.y());
}
qDebug() << Q_FUNC_INFO << "Exits";
}
void DataManagerDialog::showScreen()
{
setDefault();
alignCenter();
show();
}
You probably do not enter the event loop.
Try to call QCoreApplication::processEvents() from time to time in mpDataManager->loadDataFromServer() to update the GUI.
From the processEvents documentation :
You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file).
Edit added after getting feedback from the comments
A better approach would be to send signals in your loadDataFromServer() method with the status information and have a slot listen to the signal and update the GUI.
Here a prototype illustrating the idea :
void mpDataManagerDlg::loadDataFromServer() {
while(true) {
// do some work
int progress = // some value
emit updateDialogSignal(progress);
}
}
// in your dialog class
public slots:
void DataManagerDialog::updateDialog(int progress) {
// update gui
}
More about signals and slots can be found here.

unable to establish two way communication using qt

I have used QTcpSocket and QTcpServer class of qt to establish two way communication. I am able to send data from client to server. But am not getting the response back from server i.e my client.cpp never fires readyRead() signal. I have checked using Wireshark that my data from the server is available in specifed port.
I am posting my client.cpp code( Please help) :
Client::Client(QObject* parent): QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),
this, SLOT(startTransfer()));
connect(socket, SIGNAL(readyRead()),this, SLOT(startRead()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)) );
}
Client::~Client()
{
socket->close();
}
void Client::start(QString address, quint16 port)
{
addr.setAddress(address);
socket->connectToHost(addr,port,QTcpSocket::ReadWrite);
}
void Client::startTransfer()
{
printf("Connection established.\n");
char buffer[1024];
forever
{
printf(">> ");
gets(buffer);
int len = strlen(buffer);
buffer[len] = '\n';
buffer[len+1] = '\0';
socket->write(buffer);
socket->flush();
}
}
void Client::startRead()
{
cout<<"inside startRead()<<endl";
while(socket->canReadLine())
{
QByteArray ba = socket->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
socket->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
}
}
void Client::socketError(QAbstractSocket::SocketError )
{
qDebug()<<"error" ;
}
Looks like you have forever loop here. This means that your Qt main eventloop never gets the control back after you call startTransfer(). How do you suppose the Qt should run the startRead() code if you block your execution thread with infinite loop?
For Amartel adding the server code:
Server::Server(QObject* parent): QObject(parent)
{
// cout << "Before connect" << endl;
connect(&server, SIGNAL(newConnection()),
this, SLOT(acceptConnection()));
cout << "Listening.." << endl;
server.listen(QHostAddress::Any, 9999);
// cout << "Server started.." << endl;
}
Server::~Server()
{
server.close();
}
void Server::acceptConnection()
{
// cout << "In acceptConnection" << endl;
client = server.nextPendingConnection();
connect(client, SIGNAL(readyRead()),
this, SLOT(startRead()));
}
void Server::startRead()
{
while(client->canReadLine())
{
QByteArray ba = client->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
client->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
int result = 0;
bool ack = true;
result = client->write("I Reached");
cout<<result<<endl;
if(result <= 0)
qDebug("Ack NOT sent to client!!!");
else
qDebug("Ack sent to client.");
// client->write("I Reached");
client->flush();
}
}

Resources