EN VI

C++ - How to detect the type of data or file being sent in QBluetoothSocket?

2024-03-10 03:00:07
C++ - How to detect the type of data or file being sent in QBluetoothSocket?

I was building a bluetooth controlled display using Qt and raspberrypi.The raspberrypi will have a bluetooth service running on it and when I connect to the BluetoothServer. The user can choose to either a display a message or upload and display an image. I use QBluetoothSocket to send the message or Image file to be displayed to the server. So how do I detect which kind of data is being sent? if it's a plain text or image file and act on the data accordingly.

For sending Files

// sendText to the service
void BSocket::sendMessage(const QString &message)
{
    QByteArray text = message.toUtf8() + '\n';
    socket->write(text);
}

// sendImage to the service
void BSocket::sendFile(const QString &fileName)
{
    QImage img(fileName);
    img.save(socket);
}

For Recieving Data

void trialSocket::read_data()
{
    if (socket->bytesAvailable()) {
        QByteArray ba = socket->readAll();
        QMimeType dataType = db.mimeTypeForData(ba);
        if (dataType.inherits(QString("text/plain"))) {
            emit displayMessage(QString(ba));
        } else if (QImageReader::supportedMimeTypes().contains(dataType.name().toUtf8())) {
            QImage img = QImage::fromData(ba);
            emit displayImage(img);
        } else {
            qDebug() << "An error occured";
        }
    }
}

I was using the above code for reading the data from socket on the raspberrypi and I don't know why but qt cannot cannot identify the mimetype and instead returns the generic application/octet-stream mimetype.

Is there a better way to identify the data being sent?

Solution:

how do I detect which kind of data is being sent?

The easiest way to do so would be to reserve the first byte (or n bytes) of your message for the type of message being sent.

Here's your code with the minimal modifications required to achieve it.

void trialSocket::read_data()
{
    if (socket->bytesAvailable()) {
        char dataType = socket->read(1)[0];
        QByteArray ba = socket->readAll();

        if (dataType == 's') {
            emit displayMessage(QString(ba));
        } else if (dataType == 'i') {
            QImage img = QImage::fromData(ba);
            emit displayImage(img);
        } else {
            qDebug() << "An error occured";
        }
    }
}
// sendText to the service
void BSocket::sendMessage(const QString &message)
{
    QByteArray text = message.toUtf8() + '\n';
    text.prepend('s');
    socket->write(text);
}
// sendImage to the service
void BSocket::sendFile(const QString &fileName)
{
    QImage img(fileName);
    socket->write('i');
    img.save(socket);
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login