-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobdhandler.cpp
72 lines (56 loc) · 2.03 KB
/
obdhandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "obdhandler.h"
#include <QDebug>
#include <QTimer>
ObdHandler::ObdHandler(QObject *parent)
: QObject(parent), socket(nullptr) {}
void ObdHandler::init() {
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
QObject::connect(socket, &QBluetoothSocket::connected, []() {
qDebug() << "Connected to ELM327 device";
});
QObject::connect(socket, &QBluetoothSocket::errorOccurred, [](QBluetoothSocket::SocketError error) {
qDebug() << "Socket error:" << error;
});
QObject::connect(socket, &QBluetoothSocket::readyRead, this, [this]() {
QByteArray response = socket->readAll();
if (response.startsWith("41 0D")) {
qint64 speed = parseHexToDecimal(response, 6, 2);
qDebug() << "Speed: " << speed;
emit speedUpdated(speed);
}
if (response.startsWith("41 0C")) {
qint64 rawRPM = parseHexToDecimal(response, 6, 5);
qint64 rpm = (rawRPM / 4);
qDebug() << "RPM: " << rpm;
emit rpmUpdated(rpm);
}
});
socket->connectToService(QBluetoothAddress("00:10:cc:4f:36:03"), 2); // Example Bluetooth MAC Address of ELM327
}
void ObdHandler::sendCommand(const QString &command) {
QByteArray byteArray = QByteArray(command.toUtf8() + "\r", command.length() + 1);
if (socket && socket->isOpen()) {
qDebug() << "Sending command as bytes:" << byteArray.toHex(' ');
socket->write(byteArray);
} else {
qWarning() << "Socket not connected!";
}
}
qint64 ObdHandler::parseHexToDecimal(const QByteArray &data, int startByte, int byteCount) {
if (data.size() < startByte + byteCount) {
qWarning() << "Invalid data length for parsing!";
return -1;
}
QByteArray hexValue = data.mid(startByte, byteCount);
hexValue.replace(" ", "");
bool ok;
return hexValue.toUInt(&ok, 16);
}
qint64 ObdHandler::getRPM() {
sendCommand("010C");
return 0;
}
qint64 ObdHandler::getSpeed() {
sendCommand("010D");
return 0;
}