From c118b2823529f0140a164b946bd3e2efe243e9bf Mon Sep 17 00:00:00 2001 From: dplimin Date: Thu, 1 Feb 2024 14:27:06 +0300 Subject: [PATCH] first commit --- .gitignore | 74 +++++ 1D801Desktop.pro | 35 +++ 1D801Desktop_ru_RU.ts | 3 + bluetooth1d801.cpp | 128 ++++++++ bluetooth1d801.h | 64 ++++ main.cpp | 23 ++ mainwindow.cpp | 179 +++++++++++ mainwindow.h | 67 ++++ mainwindow.ui | 700 ++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 1273 insertions(+) create mode 100644 .gitignore create mode 100644 1D801Desktop.pro create mode 100644 1D801Desktop_ru_RU.ts create mode 100644 bluetooth1d801.cpp create mode 100644 bluetooth1d801.h create mode 100644 main.cpp create mode 100644 mainwindow.cpp create mode 100644 mainwindow.h create mode 100644 mainwindow.ui diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a0b530 --- /dev/null +++ b/.gitignore @@ -0,0 +1,74 @@ +# This file is used to ignore files which are generated +# ---------------------------------------------------------------------------- + +*~ +*.autosave +*.a +*.core +*.moc +*.o +*.obj +*.orig +*.rej +*.so +*.so.* +*_pch.h.cpp +*_resource.rc +*.qm +.#* +*.*# +core +!core/ +tags +.DS_Store +.directory +*.debug +Makefile* +*.prl +*.app +moc_*.cpp +ui_*.h +qrc_*.cpp +Thumbs.db +*.res +*.rc +/.qmake.cache +/.qmake.stash + +# qtcreator generated files +*.pro.user* +CMakeLists.txt.user* + +# xemacs temporary files +*.flc + +# Vim temporary files +.*.swp + +# Visual Studio generated files +*.ib_pdb_index +*.idb +*.ilk +*.pdb +*.sln +*.suo +*.vcproj +*vcproj.*.*.user +*.ncb +*.sdf +*.opensdf +*.vcxproj +*vcxproj.* + +# MinGW generated files +*.Debug +*.Release + +# Python byte code +*.pyc + +# Binaries +# -------- +*.dll +*.exe + diff --git a/1D801Desktop.pro b/1D801Desktop.pro new file mode 100644 index 0000000..9488e53 --- /dev/null +++ b/1D801Desktop.pro @@ -0,0 +1,35 @@ +QT += core gui +QT += bluetooth +QT += charts + + + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport + +CONFIG += c++17 + +# You can make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + bluetooth1d801.cpp \ + main.cpp \ + mainwindow.cpp + +HEADERS += \ + bluetooth1d801.h \ + mainwindow.h + +FORMS += \ + mainwindow.ui + +TRANSLATIONS += \ + 1D801Desktop_ru_RU.ts +CONFIG += lrelease +CONFIG += embed_translations + +# Default rules for deployment. +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target diff --git a/1D801Desktop_ru_RU.ts b/1D801Desktop_ru_RU.ts new file mode 100644 index 0000000..743f57f --- /dev/null +++ b/1D801Desktop_ru_RU.ts @@ -0,0 +1,3 @@ + + + diff --git a/bluetooth1d801.cpp b/bluetooth1d801.cpp new file mode 100644 index 0000000..32b01fd --- /dev/null +++ b/bluetooth1d801.cpp @@ -0,0 +1,128 @@ +#include "bluetooth1d801.h" + +using namespace Qt::StringLiterals; + +Bluetooth1d801::Bluetooth1d801(QObject *parent):QObject(parent) { + + + if (localDevice.isValid()) { //при создании экземпляра класса он подключается к свистку + localDevice.powerOn(); + localDeviceName = localDevice.name(); + qDebug() < remotes; + remotes = localDevice.connectedDevices(); // если например наушники подключены и готовы выплевывает их адрес + // с другими, например сопряженными не работает + qDebug() <<"Подключенные устройства:"<start(); + + if (discoveryAgent->isActive()) + discoveryAgent->stop(); + discoveredServices.clear(); + // m_discoveryAgent->setUuidFilter(uuid); // можно отфильтровать конкретный сервис + discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery); + qDebug()<<"Сейчас, я тебе что-нибудь найду"; +} + +void Bluetooth1d801::stopDiscovery() +{ + if (discoveryAgent->isActive()) discoveryAgent->stop(); + else { + qDebug()<<"Нечего останавливать"; + } + +} + +void Bluetooth1d801::connectTo(const QBluetoothServiceInfo &service) +{ + +} + + +void Bluetooth1d801::GetParam() +{ + +} + +void Bluetooth1d801::SetParam() +{ + +} + +void Bluetooth1d801::GetMeas() +{ + +} + +void Bluetooth1d801::GetWave() +{ + +} + +void Bluetooth1d801::GetSpectrum() +{ + +} + +void Bluetooth1d801::GetStatus() +{ + +} + +void Bluetooth1d801::SetTime() +{ + +} + +void Bluetooth1d801::GetSpectrumEnv() +{ + +} + +void Bluetooth1d801::GetWaveEnv() +{ + +} + +void Bluetooth1d801::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo) +{ + +} + +void Bluetooth1d801::readSocket() +{ + +} + +void Bluetooth1d801::connected() +{ + +} + +void Bluetooth1d801::onSocketErrorOccurred(QBluetoothSocket::SocketError error) +{ + +} diff --git a/bluetooth1d801.h b/bluetooth1d801.h new file mode 100644 index 0000000..3f0f237 --- /dev/null +++ b/bluetooth1d801.h @@ -0,0 +1,64 @@ +#ifndef BLUETOOTH1D801_H +#define BLUETOOTH1D801_H + +#include +#include +#include + +#include +#include +#include +#include +#include + + + + + +class Bluetooth1d801 : public QObject +{ + + Q_OBJECT + +public: + explicit Bluetooth1d801(QObject *parent = nullptr); // туду сюда вкорячить из конструктора мэйна + ~Bluetooth1d801(); // туду сделать деструктор. Мы же не быдлокодеры!!! + +public slots: + void startDiscovery(); //запускаем bluetooth поиск + void stopDiscovery(); //прерываем его + void connectTo(QBluetoothServiceInfo); // подключится к сервису + + //команды для модуля в первородном виде + void GetParam(); //получить параметры измерения + void SetParam(); // запись параметров измерения + + void GetMeas(); //Чтение измеренных значений + void GetWave(); //Чтение временного сигнала виброускорения /виброскорости /виброперемещения + void GetSpectrum();//Чтение спектра виброускорения /виброскорости /виброперемещения + void GetStatus();//Cтатус прибора + void SetTime();//Синхронизация часов + void GetSpectrumEnv(); //Чтение спектра огибающей виброускорения + void GetWaveEnv();//Чтение сигнала огибающей виброускорения + + +private slots: + void serviceDiscovered(const QBluetoothServiceInfo &serviceInfo); //отрабатываю сигнал обнаруженного сервиса + void readSocket(); //отработка сигнала прибывших данных + void connected(); // отработка подключения + void onSocketErrorOccurred(QBluetoothSocket::SocketError error);//отработка ошибки + + +signals: + void discoveryFinished(QMap); //возвращаем обнаруженные сервисы + void rawDataRecived(QByteArray); // прилетели какие то данные! + +private: + QBluetoothSocket *socket = nullptr; // объект сокета для порта + QBluetoothLocalDevice localDevice; // обьект локального устройства + QString localDeviceName; // имя свистка + QMap discoveredServices; // обнаруженные сервисы + QBluetoothServiceDiscoveryAgent *discoveryAgent; +}; + +#endif // BLUETOOTH1D801_H diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..fb504a1 --- /dev/null +++ b/main.cpp @@ -0,0 +1,23 @@ +#include "mainwindow.h" + +#include +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + + QTranslator translator; + const QStringList uiLanguages = QLocale::system().uiLanguages(); + for (const QString &locale : uiLanguages) { + const QString baseName = "1D801Desktop_" + QLocale(locale).name(); + if (translator.load(":/i18n/" + baseName)) { + a.installTranslator(&translator); + break; + } + } + MainWindow w; + w.show(); + return a.exec(); +} diff --git a/mainwindow.cpp b/mainwindow.cpp new file mode 100644 index 0000000..bb3cac2 --- /dev/null +++ b/mainwindow.cpp @@ -0,0 +1,179 @@ +#include "mainwindow.h" + +#include "ui_mainwindow.h" + + +#include +#include + + + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) +{ + ui->setupUi(this); +/* + if (localDevice.isValid()) { //при создании экземпляра класса он подключается к сввистку + localDevice.powerOn(); + localDeviceName = localDevice.name(); + qDebug() < remotes; + remotes = localDevice.connectedDevices(); // если например наушники подключены и готовы выплевывает их адрес + // с другими, например сопряженными не работает + qDebug() <start(); + + if (discoveryAgent->isActive()) + discoveryAgent->stop(); + ui->listWidgetDevice->clear(); + // m_discoveryAgent->setUuidFilter(uuid); // подумай? может стоит впиздячить его на релизе + discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery); + ui->labelConnect->setText("Сейчас, я тебе что-нибудь найду"); +} + + +void MainWindow::stopDiscovery() +{/* + if (m_discoveryAgent){ + m_discoveryAgent->stop(); + } +*/ +} + + +void MainWindow::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo) +{ + + qDebug() << "Discovered service on" + << serviceInfo.device().name() << serviceInfo.device().address().toString(); + qDebug() << "\tService name:" << serviceInfo.serviceName(); + qDebug() << "\tDescription:" + << serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString(); + qDebug() << "\tProvider:" + << serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString(); + qDebug() << "\tL2CAP protocol service multiplexer:" + << serviceInfo.protocolServiceMultiplexer(); + qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel(); + + + const QBluetoothAddress address = serviceInfo.device().address(); + /* // если находятся много сервисов в одной железке, то названия не дублируются + for (const QBluetoothServiceInfo &info : std::as_const(m_discoveredServices)) { + if (info.device().address() == address) + return; // + } + */ + //! [serviceDiscovered] + QString remoteName; + if (serviceInfo.device().name().isEmpty()) + remoteName = address.toString(); + else + remoteName = serviceInfo.device().name(); + QListWidgetItem *item =new QListWidgetItem(QString::fromLatin1("%1 %2").arg(remoteName, serviceInfo.serviceName())); + discoveredServices.insert(item, serviceInfo); + ui->listWidgetDevice->addItem(item); + //! [serviceDiscovered] +} + +void MainWindow::discoveryFinished() +{ + ui->labelConnect->setText("Я сделал всё, что мог"); +} + +void MainWindow::deviceDiscovered(const QBluetoothDeviceInfo &device) +{ + ui->listWidgetDevice->addItem(device.name()); + qDebug() << "Found new device:" << device.name() << '(' << device.address().toString() << ')'; +} + +void MainWindow::on_pushButton_2_clicked() +{ + auto items = ui->listWidgetDevice->selectedItems(); + if (items.size()) { + QListWidgetItem *item = items[0]; + QBluetoothServiceInfo service = discoveredServices.value(item); + qDebug() << "Connecting to service" << service.serviceName() //валим инфу в дебаг + << "on" << service.device().name(); + socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol); //создание сокета + qDebug() << "Create socket"; + socket->connectToService(service); + connect(socket, &QBluetoothSocket::readyRead, this, &MainWindow::readSocket); + connect(socket, &QBluetoothSocket::connected, this, QOverload<>::of(&MainWindow::connected)); + connect(socket, &QBluetoothSocket::disconnected, this, &MainWindow::disconnected); + connect(socket, &QBluetoothSocket::errorOccurred, this, &MainWindow::onSocketErrorOccurred); + qDebug() << "ConnectToService done"; + ui->labelConnect->setText("Похоже получилось подключится"); + } +} + + +void MainWindow::readSocket() +{ + if (!socket) + return; + + while (socket->canReadLine()) { + QByteArray line = socket->readLine().trimmed(); + qDebug() << line; + ui->listWidgetResponse->addItem(line.toHex()); + emit messageReceived(socket->peerName(), + QString::fromUtf8(line.constData(), line.length())); + } +} + +void MainWindow::onSocketErrorOccurred(QBluetoothSocket::SocketError error) +{ + if (error == QBluetoothSocket::SocketError::NoSocketError) + return; + + QMetaEnum metaEnum = QMetaEnum::fromType(); + QString errorString = socket->peerName()// + ' '_L1 + + metaEnum.valueToKey(static_cast(error)) + " occurred"; //_L1; + + emit socketErrorOccurred(errorString); +} + +void MainWindow::connected() +{ + emit connected(socket->peerName()); +} + + +void MainWindow::on_pushButtonGetParam_clicked() +{ + if (!socket){ + qDebug()<< "Ты не создал подходящий сокет!!! Я не буду работать!!!"; + return; + } + QString message = "Get_Param"; + QByteArray text = message.toUtf8() + '\r' + '\n'; + + socket->write(text); + +} + diff --git a/mainwindow.h b/mainwindow.h new file mode 100644 index 0000000..dbbeac0 --- /dev/null +++ b/mainwindow.h @@ -0,0 +1,67 @@ +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +// namespace QtCharts; + +namespace Ui { +class MainWindow; +} +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + +private slots: + void on_pushButton_clicked(); + void deviceDiscovered(const QBluetoothDeviceInfo &device); + void on_pushButton_2_clicked(); + void stopDiscovery(); + void serviceDiscovered(const QBluetoothServiceInfo &serviceInfo); + void discoveryFinished(); + void readSocket(); + void connected(); + void onSocketErrorOccurred(QBluetoothSocket::SocketError error); + void on_pushButtonGetParam_clicked(); + +signals: + void messageReceived(const QString &sender, const QString &message); + void connected(const QString &name); + void disconnected(); + void socketErrorOccurred(const QString &errorString); + +private: + Ui::MainWindow *ui; + + QBluetoothSocket *socket = nullptr; + QBluetoothLocalDevice localDevice; + QString localDeviceName; + QMap discoveredServices; + +}; +#endif // MAINWINDOW_H diff --git a/mainwindow.ui b/mainwindow.ui new file mode 100644 index 0000000..0341e29 --- /dev/null +++ b/mainwindow.ui @@ -0,0 +1,700 @@ + + + MainWindow + + + + 0 + 0 + 1300 + 793 + + + + + + + + + 0 + 0 + 0 + + + + + + + 229 + 133 + 255 + + + + + + + 255 + 255 + 255 + + + + + + + 242 + 194 + 255 + + + + + + + 114 + 66 + 127 + + + + + + + 153 + 89 + 170 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + 229 + 133 + 255 + + + + + + + 0 + 0 + 0 + + + + + + + 242 + 194 + 255 + + + + + + + 255 + 255 + 220 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + + + 0 + 0 + 0 + + + + + + + 229 + 133 + 255 + + + + + + + 255 + 255 + 255 + + + + + + + 242 + 194 + 255 + + + + + + + 114 + 66 + 127 + + + + + + + 153 + 89 + 170 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + 229 + 133 + 255 + + + + + + + 0 + 0 + 0 + + + + + + + 242 + 194 + 255 + + + + + + + 255 + 255 + 220 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 255 + 255 + 255 + + + + + + + + + 114 + 66 + 127 + + + + + + + 229 + 133 + 255 + + + + + + + 255 + 255 + 255 + + + + + + + 242 + 194 + 255 + + + + + + + 114 + 66 + 127 + + + + + + + 153 + 89 + 170 + + + + + + + 114 + 66 + 127 + + + + + + + 255 + 255 + 255 + + + + + + + 114 + 66 + 127 + + + + + + + 229 + 133 + 255 + + + + + + + 229 + 133 + 255 + + + + + + + 0 + 0 + 0 + + + + + + + 229 + 133 + 255 + + + + + + + 255 + 255 + 220 + + + + + + + 0 + 0 + 0 + + + + + + + 114 + 66 + 127 + + + + + + + 245 + 209 + 255 + + + + + + + + + 9 + + + + MainWindow + + + + + + 20 + 20 + 131 + 24 + + + + Поиск устройств + + + + + + 150 + 20 + 111 + 24 + + + + Подключение + + + + + + 20 + 67 + 251 + 111 + + + + + + + 23 + 46 + 251 + 16 + + + + Ну может начнем?? + + + + + + 20 + 190 + 201 + 24 + + + + 1) Чтение параметров измерения + + + + + + 20 + 220 + 201 + 24 + + + + 2) Запись параметров измерения + + + + + + 20 + 250 + 201 + 24 + + + + 3) Чтение измеренных значений + + + + + + 20 + 280 + 491 + 31 + + + + 4) Чтение временного сигнала виброускорения/виброскорости /виброперемещения + + + + + + 20 + 315 + 491 + 31 + + + + 5)Чтение спектра виброускорения/виброскорости/виброперемещения + + + + + + 20 + 350 + 281 + 31 + + + + 6) Cтатус прибора + + + + + + 20 + 380 + 281 + 31 + + + + 7) Синхронизация часов + + + + + + 20 + 410 + 281 + 31 + + + + 8) Чтение спектра огибающей виброускорения + + + + + + 20 + 440 + 281 + 31 + + + + 9) Чтение сигнала огибающей виброускорения + + + + + + 20 + 500 + 281 + 231 + + + + + + + 30 + 475 + 71 + 21 + + + + + 14 + + + + Ответы + + + + + + + 0 + 0 + 1300 + 21 + + + + + + + +