Program using QBluetoothSocket (in RFComm mode) stops working after receicing fine a few incoming messages



  • The programs is originally from : http://grimaldi.univ-tln.fr/communiquer-en-bluetooth-avec-un-systeme-arduino-sous-qt.html (in French)

    I've compiled the program with Qt 5.7 and I am running it on a MAC 10.11 (El Capitan).
    The program starts OK and finds the BlueTooth ARDUINO MEGA (with HC-05 module) device sending the informations and connects to it. A few incoming message are received and displayed in the log QTextEdit but the program stops working after a while (a few seconds).

    //your code here
    Here is the main window code ```
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QMessageBox>
    #include <QDebug>
    
    
    #define MYARDUINO_ADDRESS "98:D3:31:FD:18:FC"
    #define MYARDUINO_NAME "GUIT-BLUE"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        // Check if Bluetooth is available on this device
        if( !localDevice.isValid() ) {
                    QMessageBox::critical(this, "Erreur fatale","Bluetooth local inactif!");
                    return;
                    }
        // Turn Bluetooth on
        localDevice.powerOn();
    
        // Read local device name
        localDeviceName = localDevice.name();
    
        // Make it visible to others
        localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
    
        // Create a discovery agent and connect to its signals
        discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
        connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
                    this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));
    
        // Start a discovery
        discoveryAgent->start();
    
        // Get connected devices, not used here!
        remotes = localDevice.connectedDevices();
    
        // Connect to service
        socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
        connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
        connect(socket, SIGNAL(readyRead()), this, SLOT(dataReady2Read()));
        //    interface
        this->setCursor(Qt::WaitCursor);
        ui->toolButton->setEnabled(false);
    }
    
    
    //          bluetooth device discovery
    void MainWindow::deviceDiscovered(const QBluetoothDeviceInfo device)
    {
    qDebug() << "Found new device:" << device.name() << '(' << device.address().toString() << ')';
    QString br ="Found: "+device.address().toString();
    ui->textEdit->append(br);                   // show on interface
    
    if (localDevice.pairingStatus(device.address())== QBluetoothLocalDevice::Paired) qDebug()<<"paired";
    
    // device information not used here
    int classes = device.serviceClasses();
    QList<QBluetoothUuid> uidd = device.serviceUuids();
    int rssi = device.rssi();
    
    // we proceed only our remote device (Arduino/HC05 address), nothing for others...
    if (device.address().toString()!= MYARDUINO_ADDRESS) return;
    
    // this is my Arduino device
    //socket->connectToService(device.address(), 1);      //   works under Android but not on Desktop
    // here is a misterious ????
    socket->connectToService(device.address(),QBluetoothUuid(QBluetoothUuid::SerialPort));      // only on Desktop
    
    socket->open(QIODevice::ReadWrite);
    if (socket->isOpen()){          // write on interface
                    ui->textEdit->append("open "+device.address().toString());
                    }
    
    this->setCursor(Qt::ArrowCursor);
    }
    
    //____________________________________________________________________________________________________
    //   SLOT when data ready on bluetooth socket
    void MainWindow::dataReady2Read(){
        //static int count =0;
        QByteArray data;
        data = socket->readLine(30);
        // juste show on interface
        //if( count++ > 10 ) { ui->textEdit->clear(); count = 0;}
        ui->textEdit->append("receive:"+QString(data));
    }
    
    //____________________________________________________________________________________________________
    //  SLOT when socket Connected
    void MainWindow::socketConnected(){
       // show on interface
       ui->textEdit->append("Connected to: "+socket->peerAddress().toString()+":"+socket->peerPort());
       ui->toolButton->setIcon(QIcon(":/interOff.png"));
       socket->write("OFF\n");
       // enable the Button
       ui->toolButton->setEnabled(true);
    }
    
    //____________________________________________________________________________________________________
    //  destructor
    MainWindow::~MainWindow()
    {
        if (socket && socket->isOpen()) {
                            socket->close();
                            delete socket;
                            }
        delete ui;
    }
    
    //____________________________________________________________________________________________________
    // SLOT button pushed
    void MainWindow::on_toolButton_clicked()
    {
        static bool state = false;
    
    if (!socket->isOpen() || !socket->isWritable())return;      // a problem
    
    if (state) {        // make the remote led on, writing "ON"
            ui->toolButton->setIcon(QIcon(":/interOn.png"));
            socket->write("ON\n");
            ui->textEdit->append("Send: on");
            }
    else    {           // make the remote led off, writing "OFF"
        ui->toolButton->setIcon(QIcon(":/interOff.png"));
        socket->write("OFF\n");
        ui->textEdit->append("Send: off");
        }
    state = ! state;    // get the remote led state
    }
    

    The reception of the incoming messages appends here :

    //   SLOT when data ready on bluetooth socket
    void MainWindow::dataReady2Read(){
        //static int count =0;
        QByteArray data;
        data = socket->readLine(30);
        // juste show on interface
        //if( count++ > 10 ) { ui->textEdit->clear(); count = 0;}
        ui->textEdit->append("receive:"+QString(data));
    }
    

    and the code on the ARDUINO MEGA :

    //This sketch will use bluetooth to send info
    // to a Raspberry PI using bluetooth
    // Arduino -> bluetooth
    
    // Here, we exchange them -
    const int LEDPin = 13;    //LED PIN on Arduino
    const int joyX = A8;        // L/R Parallax Thumbstick
    const int joyY = A9;   
    const int THeSwitch = 7;
    
    void setup() {
      
      Serial.begin(9600);
      Serial.println("Started");
      Serial1.begin(115200);
      
      pinMode(LEDPin, OUTPUT);
      pinMode(THeSwitch, INPUT);
    }
    
    
    int X,Y;
    int Sw;
    
    void loop() {
        X = analogRead(joyX);
        Y = analogRead(joyY);
        Sw = digitalRead(THeSwitch);
        
    /*    Serial.print("X = " + String(X) );
        Serial.print("   Y = " + String(Y));
        Serial.println("   Sw = " + String(Sw));
    */    
        Serial1.print (String(X) + "," + String(Y));
        Serial1.print("\n");
        
        //delay (200); //prepare for data (0.2s)
    }
    

    I am wondering wether it is a speed problem since the data is being send at 115200 bauds from the ARDUINO MEGA.

    Anyboby has experience with QT bluetooth that could help with this problem ? And is there a "packet sniffer tool" for BlueTooth on MAC ?

    Thanks in advance for the help.



  • I tried setting the sending rate of the ARDUINO MEGA to 9600 bauds. The program works for a bit longer but eventually stops. There is a huge (more than 10 seconds) delay between the time the value sent are changed (by moving the joystick connected to the 2 Analog input of the Arduino) and the time these changed value are displayed in the Qt program. Seems the message are delayed at the reception end by either the MAC BlueTooth system or Qt even loop (maybe). Tried to disconnect the Bluetooth mouse on the MAC but that did not changed the delay at the receiving end. Any ideas on what going on here ? Some kind of even queue or buffer most get filled up when the program eventually stops working.



  • Does not seems like so many people are using BlueTooth Qt lib looking at the number of replyes to this suject : 0 so far.

    This WE I will try to get it to work "better" by adding a Start message send from the MAC to the ARDUINO and get the ARDUINO to pnly start sending messages after the Qt prog on the MAC set-up and ready to receive the messages. Who knows that might sort out the huge delay in receiving the messages.



  • So I gave it a new try with a START and a STOP signal coming from the QT prog on the MAC. The delay is still there altough a bit shorter (say 3 to 5 seconds) but unusable for the application I want to build that need a short delay (say a few ms). I'll see If I can get the Bluetooth reception part to run in a different thread. But maybe it is just the Qt BlueTooth library that does not have good performance on MAC ?



  • bump. Anybody using Qt Bluetooth on MAC ?



  • You can use Wireshark to sniff the bluetooth packages.

    https://www.wireshark.org/download.html

    It helped me a lot when i tried different bluetooth profiles.



  • Thanks for the info. I'll give it a go this WE.

    One thing I did not mention up to now is that I got the bluetooth message reception to work "real time" on a RPI 3. The ARDUINO program is the same but on RPi 3 I run the follolwing PYTHON program (not the QT program cause I can't compile it) :

    bd_addr = "98:D3:31:50:0A:CE" //The address from the HC-05 sensor
    port = 1
    sock = bluetooth.BluetoothSocket (bluetooth.RFCOMM)
    sock.connect((bd_addr,port))
     
    data = ""
    while 1:
    	try:
    		data += sock.recv(1024)
    		data_end = data.find('\n')
    		if data_end != -1:
    			rec = data[:data_end]
    			print data
    			data = data[data_end+1:]
    	except KeyboardInterrupt:
    		break
    sock.close()
    

    from link text

    With that set-up it runs at 57600 bauds.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.