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?
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);
}