diff --git a/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.cpp b/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.cpp deleted file mode 100644 index ca9a85e1..00000000 --- a/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.cpp +++ /dev/null @@ -1,15 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsCanBusStudio.h" - -xToolsCanBusStudio::xToolsCanBusStudio(QObject* parent) - : QThread(parent) -{} - -xToolsCanBusStudio::~xToolsCanBusStudio() {} diff --git a/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.h b/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.h deleted file mode 100644 index 3d3714b3..00000000 --- a/Source/CANBusStudio/CANBusStudio/xToolsCanBusStudio.h +++ /dev/null @@ -1,19 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include - -class xToolsCanBusStudio : public QThread -{ - Q_OBJECT -public: - xToolsCanBusStudio(QObject *parent = nullptr); - ~xToolsCanBusStudio(); -}; diff --git a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.cpp b/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.cpp deleted file mode 100644 index 93fd1764..00000000 --- a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.cpp +++ /dev/null @@ -1,550 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsCanBusStudioUi.h" -#include "ui_xToolsCanBusStudioUi.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "xToolsSettings.h" - -const QLoggingCategory gLC("sak.canstudio"); - -xToolsCanBusStudioUi::xToolsCanBusStudioUi(QWidget* parent) - : QWidget{parent} - , ui(new Ui::xToolsCanBusStudioUi) - , mDevice(Q_NULLPTR) -{ - if (!mSettings) { - mSettings = xToolsSettings::instance(); - } - - ui->setupUi(this); - initUi(); - initSetting(); - - // Device is not connected. - updateUiState(false); -} - -xToolsCanBusStudioUi::~xToolsCanBusStudioUi() -{ - delete ui; -} - -void xToolsCanBusStudioUi::initUi() -{ - initUiSelectPlugin(); - initUiSpecifyConfiguration(); - initUiCanFrame(); - initUiSendCanFrame(); -} - -void xToolsCanBusStudioUi::initUiSelectPlugin() -{ - ui->pluginComboBox->clear(); - ui->pluginComboBox->addItems(QCanBus::instance()->plugins()); - ui->disconnectPushButton->setEnabled(false); - ui->connectPushButton->setEnabled(true); - - connect(ui->pluginComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onPluginChanged); - connect(ui->disconnectPushButton, - &QPushButton::clicked, - this, - &xToolsCanBusStudioUi::onDisconnectClicked); - connect(ui->connectPushButton, &QPushButton::clicked, this, &xToolsCanBusStudioUi::onConnectClicked); -} - -void xToolsCanBusStudioUi::initUiSpecifyConfiguration() -{ - setOptions(ui->loopbackComboBox, true); - setOptions(ui->receivOwnComboBox, true); - setOptions(ui->canFdComboBox, false); - setBitRates(ui->bitrateComboBox, false); - setBitRates(ui->dataBitrateComboBox, true); - - ui->interfaceNameComboBox->lineEdit()->setPlaceholderText(tr("can0")); - - connect(ui->customConfigurationCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onCustomConfigurationChanged); - connect(ui->loopbackComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onLoopbackIndexChanged); - connect(ui->receivOwnComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onReceiveOwnIndexChanged); - connect(ui->canFdComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onCanFdIndexChanged); - connect(ui->bitrateComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onBitrateChanged); - connect(ui->dataBitrateComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onDataBitrateChanged); - connect(ui->customBitrateCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onCustomBitrateChanged); - connect(ui->customDataBitrateCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onCustomDataBitrateChanged); -} - -void xToolsCanBusStudioUi::initUiCanFrame() -{ - ui->frameTypeComboBox->clear(); - ui->frameTypeComboBox->addItem(tr("DataFrame"), QCanBusFrame::DataFrame); - ui->frameTypeComboBox->addItem(tr("ErrorFrame"), QCanBusFrame::ErrorFrame); - ui->frameTypeComboBox->addItem(tr("RemoteRequestFrame"), QCanBusFrame::RemoteRequestFrame); - - connect(ui->frameTypeComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsCanBusStudioUi::onFrameTypeChanged); - connect(ui->extendedFormatCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onExtendedFormatChanged); - connect(ui->flexibleDataRateCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onFlexibleDataRateChanged); - connect(ui->bitrateSwitchCheckBox, - &QCheckBox::clicked, - this, - &xToolsCanBusStudioUi::onBitrateSwitchChanged); -} - -void xToolsCanBusStudioUi::initUiSendCanFrame() -{ - const QString inputTips = tr("Hex"); - ui->frameIdComboBox->lineEdit()->setPlaceholderText(inputTips); - ui->payloadComboBox->lineEdit()->setPlaceholderText(inputTips); - - connect(ui->sendPushButton, &QPushButton::clicked, this, &xToolsCanBusStudioUi::onSendButtonClicked); -} - -void xToolsCanBusStudioUi::initSetting() -{ - initSettingSelectPlugin(); - initSettingSpecifyConfiguration(); - initSettingCanFrame(); - initSettingSendCanFrame(); -} - -void xToolsCanBusStudioUi::initSettingSelectPlugin() -{ - setCurrentIndex(ui->pluginComboBox, mSettingKeyCtx.pluginIndex); -} - -void xToolsCanBusStudioUi::initSettingSpecifyConfiguration() -{ - QString name = mSettings->value(mSettingKeyCtx.interfaceName).toString(); - ui->interfaceNameComboBox->lineEdit()->setText(name); - - setChecked(ui->customConfigurationCheckBox, mSettingKeyCtx.customConfiguration); - setCurrentIndex(ui->loopbackComboBox, mSettingKeyCtx.loopback); - setCurrentIndex(ui->receivOwnComboBox, mSettingKeyCtx.receiveOwn); - setCurrentIndex(ui->bitrateComboBox, mSettingKeyCtx.bitrate); - setCurrentIndex(ui->canFdComboBox, mSettingKeyCtx.canFd); - setCurrentIndex(ui->dataBitrateComboBox, mSettingKeyCtx.dataBitRate); - setChecked(ui->customBitrateCheckBox, mSettingKeyCtx.customBitRate); - setChecked(ui->customDataBitrateCheckBox, mSettingKeyCtx.customDataBitRate); - - bool enable = mSettings->value(mSettingKeyCtx.customConfiguration).toBool(); - setCustomConfigurationEnable(enable); -} - -void xToolsCanBusStudioUi::initSettingCanFrame() -{ - setCurrentIndex(ui->frameTypeComboBox, mSettingKeyCtx.frameTypeIndex); - setChecked(ui->extendedFormatCheckBox, mSettingKeyCtx.extendedFormat); - setChecked(ui->flexibleDataRateCheckBox, mSettingKeyCtx.flexibleDataRate); - setChecked(ui->bitrateSwitchCheckBox, mSettingKeyCtx.bitrateSwitch); - - onFrameTypeChanged(); -} - -void xToolsCanBusStudioUi::initSettingSendCanFrame() {} - -void xToolsCanBusStudioUi::onPluginChanged() -{ - int index = ui->pluginComboBox->currentIndex(); - mSettings->setValue(mSettingKeyCtx.pluginIndex, index); -} - -void xToolsCanBusStudioUi::onDisconnectClicked() -{ - if (mDevice) { - mDevice->disconnectDevice(); - mDevice->deleteLater(); - mDevice = Q_NULLPTR; - } - - updateUiState(false); -} - -void xToolsCanBusStudioUi::onConnectClicked() -{ - const QString pluginName = ui->pluginComboBox->currentText(); - const QString interfaceName = ui->interfaceNameComboBox->currentText(); - - if (interfaceName.isEmpty()) { - QMessageBox::warning(this, - tr("Interface Name is Empty"), - tr("Interface name is empty, " - "please input the name then try again!")); - return; - } - - QString errorString; -#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) - mDevice = QCanBus::instance()->createDevice(pluginName, interfaceName, &errorString); - if (!mDevice) { - qCWarning(gLC) << errorString; - return; - } -#else - mDevice = QCanBus::instance()->createDevice(pluginName.toLatin1(), interfaceName); - if (!mDevice) { - qCWarning(gLC) << tr("Create device failed!"); - return; - } -#endif - - connect(mDevice, &QCanBusDevice::errorOccurred, this, &xToolsCanBusStudioUi::onErrorOccure); - connect(mDevice, &QCanBusDevice::framesReceived, this, &xToolsCanBusStudioUi::onFrameReceived); - connect(mDevice, &QCanBusDevice::framesWritten, this, &xToolsCanBusStudioUi::onFrameWritten); - - auto items = configurationItems(); - for (auto& item : items) { - mDevice->setConfigurationParameter(item.first, item.second); - } - - if (!mDevice->connectDevice()) { - qCWarning(gLC) << tr("Connection error: %1").arg(mDevice->errorString()); - QMessageBox::warning(this, - tr("Connection Error"), - tr("Connection error: %1").arg(mDevice->errorString())); - mDevice->deleteLater(); - mDevice = Q_NULLPTR; - return; - } - - mSettings->setValue(mSettingKeyCtx.interfaceName, interfaceName); - updateUiState(true); -} - -void xToolsCanBusStudioUi::onLoopbackIndexChanged(int index) -{ - mSettings->setValue(mSettingKeyCtx.loopback, index); -} - -void xToolsCanBusStudioUi::onCustomConfigurationChanged() -{ - bool checked = ui->customConfigurationCheckBox->isChecked(); - setCustomConfigurationEnable(checked); - mSettings->setValue(mSettingKeyCtx.customConfiguration, checked); -} - -void xToolsCanBusStudioUi::onReceiveOwnIndexChanged(int index) -{ - mSettings->setValue(mSettingKeyCtx.receiveOwn, index); -} - -void xToolsCanBusStudioUi::onCanFdIndexChanged(int index) -{ - mSettings->setValue(mSettingKeyCtx.canFd, index); -} - -void xToolsCanBusStudioUi::onBitrateChanged(int index) -{ - mSettings->setValue(mSettingKeyCtx.bitrate, index); -} - -void xToolsCanBusStudioUi::onDataBitrateChanged(int index) -{ - mSettings->setValue(mSettingKeyCtx.dataBitRate, index); -} - -void xToolsCanBusStudioUi::onCustomBitrateChanged() -{ - bool checked = ui->customBitrateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.customBitRate, checked); - - ui->bitrateComboBox->setEditable(checked); -} - -void xToolsCanBusStudioUi::onCustomDataBitrateChanged() -{ - bool checked = ui->customDataBitrateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.customDataBitRate, checked); - - ui->dataBitrateComboBox->setEditable(true); -} - -void xToolsCanBusStudioUi::onFrameTypeChanged() -{ - int index = ui->frameTypeComboBox->currentIndex(); - mSettings->setValue(mSettingKeyCtx.frameTypeIndex, index); - - int type = ui->frameTypeComboBox->currentData().toInt(); - if (type == QCanBusFrame::DataFrame) { - ui->flexibleDataRateCheckBox->setEnabled(true); - bool checked = ui->flexibleDataRateCheckBox->isChecked(); - ui->bitrateSwitchCheckBox->setEnabled(checked); - } else { - ui->flexibleDataRateCheckBox->setEnabled(false); - ui->bitrateSwitchCheckBox->setEnabled(false); - } -} - -void xToolsCanBusStudioUi::onExtendedFormatChanged() -{ - bool checked = ui->extendedFormatCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.extendedFormat, checked); -} - -void xToolsCanBusStudioUi::onFlexibleDataRateChanged() -{ - bool checked = ui->flexibleDataRateCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.flexibleDataRate, checked); - - ui->bitrateSwitchCheckBox->setEnabled(checked); -} - -void xToolsCanBusStudioUi::onBitrateSwitchChanged() -{ - bool checked = ui->bitrateSwitchCheckBox->isChecked(); - mSettings->setValue(mSettingKeyCtx.bitrateSwitch, checked); -} - -void xToolsCanBusStudioUi::onSendButtonClicked() -{ - if (!mDevice) { - QString title = tr("Device is Not Ready"); - QString msg = tr("Device is not ready," - " please connect the device then try angin!"); - QMessageBox::warning(this, title, msg); - return; - } - - const uint frameId = ui->frameIdComboBox->currentText().toUInt(Q_NULLPTR, 16); - QString data = ui->payloadComboBox->currentText().trimmed(); - const QByteArray payload = QByteArray::fromHex(data.remove(QLatin1Char(' ')).toLatin1()); - - QCanBusFrame frame = QCanBusFrame(frameId, payload); - frame.setExtendedFrameFormat(ui->extendedFormatCheckBox->isChecked()); - - if (ui->flexibleDataRateCheckBox->isEnabled()) { - frame.setFlexibleDataRateFormat(ui->flexibleDataRateCheckBox->isChecked()); - } - - if (ui->bitrateSwitchCheckBox->isEnabled()) { - frame.setBitrateSwitch(ui->bitrateSwitchCheckBox); - } - - if (mDevice->writeFrame(frame)) { - QString view; - if (frame.frameType() == QCanBusFrame::ErrorFrame) { - view = mDevice->interpretErrorFrame(frame); - } else { - view = frame.toString(); - } - - QString flag = QString("[Tx] "); - outputMessage(flag + view); - } else { - qCWarning(gLC) << mDevice->errorString(); - } -} - -void xToolsCanBusStudioUi::onErrorOccure(QCanBusDevice::CanBusError error) -{ - if (mDevice) { - Q_UNUSED(error); - QMessageBox::warning(this, tr("Error Occure"), mDevice->errorString()); - onDisconnectClicked(); - } -} - -void xToolsCanBusStudioUi::onFrameReceived() -{ - if (!mDevice) { - return; - } - - while (mDevice->framesAvailable()) { - const QCanBusFrame frame = mDevice->readFrame(); - - QString view; - if (frame.frameType() == QCanBusFrame::ErrorFrame) { - view = mDevice->interpretErrorFrame(frame); - } else { - view = frame.toString(); - } - - QString flag = QString("[Rx] "); - outputMessage(flag + view); - } -} - -void xToolsCanBusStudioUi::onFrameWritten(qint64 framesCount) -{ - qCInfo(gLC) << framesCount; -} - -void xToolsCanBusStudioUi::setOptions(QComboBox* cb, bool usingUnspecified) -{ - if (cb) { - cb->clear(); - if (usingUnspecified) { - cb->addItem(tr("unspecified"), QVariant()); - } - cb->addItem(tr("false"), QVariant(false)); - cb->addItem(tr("true"), QVariant(true)); - } -} - -void xToolsCanBusStudioUi::setCurrentIndex(QComboBox* cb, const QString& key) -{ - int index = mSettings->value(key).toInt(); - if (index >= 0 && index <= cb->count() - 1) { - cb->setCurrentIndex(index); - } -} - -void xToolsCanBusStudioUi::setChecked(QCheckBox* cb, const QString& key) -{ - if (cb) { - bool checked = mSettings->value(key).toBool(); - cb->setChecked(checked); - } -} - -void xToolsCanBusStudioUi::setCustomConfigurationEnable(bool enable) -{ - ui->errorFilterComboBox->setEnabled(enable); - ui->loopbackComboBox->setEnabled(enable); - ui->receivOwnComboBox->setEnabled(enable); - ui->canFdComboBox->setEnabled(enable); - ui->bitrateComboBox->setEnabled(enable); - ui->dataBitrateComboBox->setEnabled(enable); - ui->customBitrateCheckBox->setEnabled(enable); - ui->customDataBitrateCheckBox->setEnabled(enable); -} - -void xToolsCanBusStudioUi::outputMessage(const QString& msg) -{ - QString datetimeString = -#if 0 - QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz"); -#else - QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); -#endif - QString cookedMsg; - cookedMsg = QString("%1 ").arg(datetimeString); - cookedMsg += msg; - - ui->textBrowser->append(cookedMsg); -} - -void xToolsCanBusStudioUi::updateUiState(bool connected) -{ - ui->connectPushButton->setEnabled(!connected); - ui->disconnectPushButton->setEnabled(connected); - - ui->interfaceNameComboBox->setEnabled(!connected); - ui->customConfigurationCheckBox->setEnabled(!connected); - if (connected) { - setCustomConfigurationEnable(false); - } else { - bool checked = ui->customConfigurationCheckBox->isChecked(); - setCustomConfigurationEnable(checked); - } -} - -QVector xToolsCanBusStudioUi::configurationItems() -{ - QVector items; - ConfigurationItem item; - - QString errorFilter = ui->errorFilterComboBox->currentText(); - if (!errorFilter.isEmpty()) { - bool ok = false; - int dec = errorFilter.toInt(&ok); - if (ok) { - item.first = QCanBusDevice::ErrorFilterKey; - item.second = QVariant::fromValue(QCanBusFrame::FrameErrors(dec)); - items.append(item); - } - } - - item.first = QCanBusDevice::LoopbackKey; - item.second = ui->loopbackComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::ReceiveOwnKey; - item.second = ui->receivOwnComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::CanFdKey; - item.second = ui->canFdComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::BitRateKey; - item.second = ui->bitrateComboBox->currentData(); - items.append(item); - - item.first = QCanBusDevice::DataBitRateKey; - item.second = ui->dataBitrateComboBox->currentData(); - items.append(item); - - return items; -} - -void xToolsCanBusStudioUi::setBitRates(QComboBox* cb, bool isFlexibleDataRateEnable) -{ - if (!cb) { - return; - } - - const QVector rates = {10000, 20000, 50000, 100000, 125000, 250000, 500000, 800000, 1000000}; - - const QVector dataRates = {2000000, 4000000, 8000000}; - - cb->clear(); - - for (int rate : rates) { - cb->addItem(QString::number(rate), rate); - } - - if (isFlexibleDataRateEnable) { - for (int rate : dataRates) { - cb->addItem(QString::number(rate), rate); - } - } -} diff --git a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.h b/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.h deleted file mode 100644 index a533a1c2..00000000 --- a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.h +++ /dev/null @@ -1,108 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE -namespace Ui { -class xToolsCanBusStudioUi; -} -QT_END_NAMESPACE - -class xToolsCanBusStudioUi : public QWidget -{ - Q_OBJECT - typedef QPair ConfigurationItem; - -public: - Q_INVOKABLE xToolsCanBusStudioUi(QWidget *parent = Q_NULLPTR); - ~xToolsCanBusStudioUi(); - -private: - struct - { - const QString pluginIndex = "CANStudio/pluginIndex"; - - const QString interfaceName = "CANStudio/interfaceName"; - const QString customConfiguration = "CANStudio/customConfiguration"; - const QString loopback = "CANStudio/loopback"; - const QString receiveOwn = "CANStudio/receiveOwn"; - const QString canFd = "CANStudio/canFd"; - const QString bitrate = "CANStudio/bitrate"; - const QString dataBitRate = "CANStudio/dataBitRate"; - const QString customBitRate = "CANStudio/customBitRate"; - const QString customDataBitRate = "CANStudio/customDataBitRate"; - - const QString frameTypeIndex = "CANStudio/frameTypeIndex"; - const QString extendedFormat = "CANStudio/extendedFormat"; - const QString flexibleDataRate = "CANStudio/fleibleDataRate"; - const QString bitrateSwitch = "CANStudio/bitrateSwitch"; - } mSettingKeyCtx; - -private: - Ui::xToolsCanBusStudioUi *ui; - QSettings *mSettings{nullptr}; - QCanBusDevice *mDevice{nullptr}; - -private: - void initUi(); - void initUiSelectPlugin(); - void initUiSpecifyConfiguration(); - void initUiCanFrame(); - void initUiSendCanFrame(); - - void initSetting(); - void initSettingSelectPlugin(); - void initSettingSpecifyConfiguration(); - void initSettingCanFrame(); - void initSettingSendCanFrame(); - - // These are slots. - void onPluginChanged(); - void onDisconnectClicked(); - void onConnectClicked(); - - void onCustomConfigurationChanged(); - void onLoopbackIndexChanged(int index); - void onReceiveOwnIndexChanged(int index); - void onCanFdIndexChanged(int index); - void onBitrateChanged(int index); - void onDataBitrateChanged(int index); - void onCustomBitrateChanged(); - void onCustomDataBitrateChanged(); - - void onFrameTypeChanged(); - void onExtendedFormatChanged(); - void onFlexibleDataRateChanged(); - void onBitrateSwitchChanged(); - - void onSendButtonClicked(); - - // Slots about CAN bus device - void onErrorOccure(QCanBusDevice::CanBusError error); - void onFrameReceived(); - void onFrameWritten(qint64 framesCount); - -private: - void setOptions(QComboBox *cb, bool usingUnspecified); - void setCurrentIndex(QComboBox *cb, const QString &key); - void setBitRates(QComboBox *cb, bool isFlexibleDataRateEnable); - void setChecked(QCheckBox *cb, const QString &key); - void setCustomConfigurationEnable(bool enable); - void outputMessage(const QString &msg); - void updateUiState(bool connected); - QVector configurationItems(); -}; diff --git a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.ui b/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.ui deleted file mode 100644 index 30b35f3b..00000000 --- a/Source/CANBusStudio/CANBusStudioUI/xToolsCanBusStudioUi.ui +++ /dev/null @@ -1,329 +0,0 @@ - - - xToolsCanBusStudioUi - - - - 0 - 0 - 691 - 634 - - - - CANBus Studio - - - - - - CAN frame - - - - - - Bitrate switch - - - - - - - - 0 - 0 - - - - Frame type - - - - - - - Flexible data-rate - - - - - - - - - - Extended format - - - - - - - - - - Send CAN frame - - - - - - Frame ID - - - - - - - true - - - - - - - Payload - - - - - - - - 0 - 0 - - - - true - - - - - - - Send - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - 0 - - - - Console - - - - - - - - - - - - - Select plugin - - - - - - - - - Disconnect - - - - - - - Connect - - - - - - - - - - - 0 - 0 - - - - Specify configuration - - - - - - Custom data bitrate - - - - - - - - - - - - - Custom bitrate - - - - - - - true - - - - - - - - 0 - 0 - - - - CAN FD - - - - - - - - 0 - 0 - - - - Loopback - - - - - - - - 0 - 0 - - - - Bitrate - - - - - - - true - - - - - - - - - - - 0 - 0 - - - - Interface - - - - - - - - - - - 0 - 0 - - - - Data bitrate - - - - - - - - - - - 0 - 0 - - - - Receive own - - - - - - - - 0 - 0 - - - - Error filter - - - - - - - Custom configurations - - - - - - - - - - - diff --git a/Source/CANBusStudio/CMakeLists.txt b/Source/CANBusStudio/CMakeLists.txt deleted file mode 100644 index 8ab370d3..00000000 --- a/Source/CANBusStudio/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -file(GLOB_RECURSE SOURCES_H "${CMAKE_SOURCE_DIR}/Source/CANBusStudio/*.h") -file(GLOB_RECURSE SOURCES_UI "${CMAKE_SOURCE_DIR}/Source/CANBusStudio/*.ui") -file(GLOB_RECURSE SOURCES_CPP "${CMAKE_SOURCE_DIR}/Source/CANBusStudio/*.cpp") - -list(APPEND ALL_SOURCE ${SOURCES_H}) -list(APPEND ALL_SOURCE ${SOURCES_UI}) -list(APPEND ALL_SOURCE ${SOURCES_CPP}) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsSettings.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsSettings.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsInterface.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsInterface.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsTranslator.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsTranslator.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsUi.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsMainWindow.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsMainWindow.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/xTools.qrc) - -x_tools_add_executable("CANBusStudio" ${ALL_SOURCE}) -x_tools_set_target_properties(CANBusStudio) -x_tools_deploy_qt(CANBusStudio) - -target_link_libraries(CANBusStudio PRIVATE glog::glog) -target_link_libraries(CANBusStudio PRIVATE Qt${QT_VERSION_MAJOR}::Widgets) -target_link_libraries(CANBusStudio PRIVATE Qt${QT_VERSION_MAJOR}::SerialBus) diff --git a/Source/CANBusStudio/main.cpp b/Source/CANBusStudio/main.cpp deleted file mode 100644 index f83e420a..00000000 --- a/Source/CANBusStudio/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsCanBusStudioUi.h" -#include "xToolsUi.h" - -int main(int argc, char* argv[]) -{ - const QString appName = QObject::tr("CAN Bus Studio"); - return xToolsExec(argc, argv, appName); -} diff --git a/Source/Common/Common/xToolsBleScanner.cpp b/Source/Common/Common/xToolsBleScanner.cpp deleted file mode 100644 index 74149b88..00000000 --- a/Source/Common/Common/xToolsBleScanner.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsBleScanner.h" - -#include -#include -#include - -#define BLE_ERR_SIG void (QBluetoothDeviceDiscoveryAgent::*)(QBluetoothDeviceDiscoveryAgent::Error) - -xToolsBleScanner::xToolsBleScanner(QObject* parent) - : QThread(parent) - , m_discover(Q_NULLPTR) -{} - -xToolsBleScanner::~xToolsBleScanner() {} - -void xToolsBleScanner::startDiscover() -{ - start(); -} - -void xToolsBleScanner::stopDiscover() -{ - exit(); -} - -bool xToolsBleScanner::isActive() -{ - return isRunning(); -} - -QVariant xToolsBleScanner::deviceInfo(int index) -{ - m_deviceInfoListMutex.lock(); - if (index >= 0 && index < m_deviceInfoList.length()) { - QBluetoothDeviceInfo info = m_deviceInfoList.at(index); - return QVariant::fromValue(info); - } - m_deviceInfoListMutex.unlock(); - - return QVariant(); -} - -QString xToolsBleScanner::deviceName(const QVariant& deviceInfo) -{ - auto cookedInfo = deviceInfo.value(); - return cookedInfo.name(); -} - -void xToolsBleScanner::run() -{ - m_discover = new QBluetoothDeviceDiscoveryAgent(); - connect(m_discover, - &QBluetoothDeviceDiscoveryAgent::finished, - this, - &xToolsBleScanner::onDiscoveryFinished); - connect(m_discover, - &QBluetoothDeviceDiscoveryAgent::errorOccurred, - this, - &xToolsBleScanner::onDiscoveryErrorOccurred); - connect(m_discover, - &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, - this, - &xToolsBleScanner::onDiscoveryDeviceDiscovered); - - // 10s-1minute - int interval = m_timeoutInterval < 10 ? 10 : m_timeoutInterval; - interval = interval > 120 ? 120 : interval; - m_discover->setLowEnergyDiscoveryTimeout(interval * 1000); - - m_deviceInfoListMutex.lock(); - m_deviceInfoList.clear(); - m_deviceInfoListMutex.unlock(); - m_discover->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod); - exec(); -} - -void xToolsBleScanner::onDiscoveryFinished() -{ - emit devicesInfoListChanged(); - exit(); -} - -void xToolsBleScanner::onDiscoveryErrorOccurred(QBluetoothDeviceDiscoveryAgent::Error error) -{ - Q_UNUSED(error); - qWarning() << "QBluetoothDeviceDiscoveryAgent error:" << m_discover->errorString(); - exit(); - emit errorOccurred(m_discover->errorString()); -} - -void xToolsBleScanner::onDiscoveryDeviceDiscovered(const QBluetoothDeviceInfo& info) -{ - const QString name = info.name(); - qInfo() << "new ble device:" << name; - - if (!m_nameFiltter.isEmpty()) { - if (!name.contains(m_nameFiltter)) { - qInfo() << "device is ignored:" << name; - return; - } - } - - m_deviceInfoListMutex.lock(); - m_deviceInfoList.append(info); - m_deviceInfoListMutex.unlock(); - emit deviceDiscovered(info); -} - -QVariantList xToolsBleScanner::devicesInfoList() -{ - QVariantList list; - m_deviceInfoListMutex.lock(); - for (auto& info : m_deviceInfoList) { - list.append(QVariant::fromValue(info)); - } - m_deviceInfoListMutex.unlock(); - - return list; -} - -int xToolsBleScanner::timeoutInterval() -{ - return m_timeoutInterval; -} - -void xToolsBleScanner::setTimeoutInterval(int interval) -{ - m_timeoutInterval = interval; - emit timeoutIntervalChanged(); -} - -QString xToolsBleScanner::namefiltter() -{ - return m_nameFiltter; -} - -void xToolsBleScanner::setNameFiltter(const QString& flag) -{ - m_nameFiltter = flag; - emit filtterNameChanged(); -} diff --git a/Source/Common/Common/xToolsBleScanner.h b/Source/Common/Common/xToolsBleScanner.h deleted file mode 100644 index 9718f572..00000000 --- a/Source/Common/Common/xToolsBleScanner.h +++ /dev/null @@ -1,71 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include - -class xToolsBleScanner : public QThread -{ - Q_OBJECT - // clang-format off - Q_PROPERTY(QVariantList deviceInfoList READ devicesInfoList NOTIFY devicesInfoListChanged) - Q_PROPERTY(int timeoutInterval READ timeoutInterval WRITE setTimeoutInterval NOTIFY timeoutIntervalChanged) - Q_PROPERTY(QString namefiltter READ namefiltter WRITE setNameFiltter NOTIFY filtterNameChanged) - // clang-format on -public: - explicit xToolsBleScanner(QObject *parent = nullptr); - ~xToolsBleScanner(); - -public: - Q_INVOKABLE void startDiscover(); - Q_INVOKABLE void stopDiscover(); - Q_INVOKABLE bool isActive(); - - Q_INVOKABLE QVariant deviceInfo(int index); - Q_INVOKABLE QString deviceName(const QVariant &deviceInfo); - -signals: - void deviceDiscovered(const QBluetoothDeviceInfo &info); - void errorOccurred(const QString &errStr); - -protected: - virtual void run() override; - -private: - QBluetoothDeviceDiscoveryAgent *m_discover; - QMutex m_deviceInfoListMutex; - -private: - void onDiscoveryFinished(); - void onDiscoveryErrorOccurred(QBluetoothDeviceDiscoveryAgent::Error error); - void onDiscoveryDeviceDiscovered(const QBluetoothDeviceInfo &info); - -public: - QVariantList devicesInfoList(); - int timeoutInterval(); - void setTimeoutInterval(int interval); - QString namefiltter(); - void setNameFiltter(const QString &flag); - -signals: - void devicesInfoListChanged(); - void enableRefreshChanged(); - void timeoutIntervalChanged(); - void filtterNameChanged(); - -private: - QVector m_deviceInfoList; - int m_timeoutInterval{120}; - QString m_nameFiltter{""}; -}; diff --git a/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.cpp b/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.cpp deleted file mode 100644 index 9739987f..00000000 --- a/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsBleDeviceInfoComboBox.h" - -#include -#include - -xToolsBleDeviceInfoComboBox::xToolsBleDeviceInfoComboBox(QWidget* parent) - : xToolsComboBox(parent) - , mScanner(Q_NULLPTR) -{ - mScanner = new xToolsBleScanner(this); - connect(mScanner, &xToolsBleScanner::finished, this, &xToolsBleDeviceInfoComboBox::onFinished); - connect(mScanner, &xToolsBleScanner::started, this, &xToolsBleDeviceInfoComboBox::started); - connect(mScanner, - &xToolsBleScanner::deviceDiscovered, - this, - &xToolsBleDeviceInfoComboBox::onDeviceDiscovered); - connect(mScanner, - &xToolsBleScanner::errorOccurred, - this, - &xToolsBleDeviceInfoComboBox::onErrorOccurred); -} - -xToolsBleDeviceInfoComboBox::~xToolsBleDeviceInfoComboBox() -{ - mScanner->stopDiscover(); -} - -void xToolsBleDeviceInfoComboBox::startDiscover() -{ - clear(); - mScanner->startDiscover(); -} - -void xToolsBleDeviceInfoComboBox::stopDiscover() -{ - mScanner->stopDiscover(); -} - -bool xToolsBleDeviceInfoComboBox::isActive() -{ - return mScanner->isActive(); - return false; -} - -void xToolsBleDeviceInfoComboBox::setTimeoutInterval(int interval) -{ -#if 0 - mScanner->setTimeoutInterval(interval); -#endif -} - -void xToolsBleDeviceInfoComboBox::setNameFiltter(const QString& filtter) -{ - mScanner->setNameFiltter(filtter); -} - -void xToolsBleDeviceInfoComboBox::changeEvent(QEvent* event) -{ - xToolsComboBox::changeEvent(event); - if ((event->type() == QEvent::EnabledChange) && isEnabled()) { - onFinished(); - } -} - -void xToolsBleDeviceInfoComboBox::onFinished() -{ - if (!isEnabled()) { - return; - } - - clear(); - auto infos = mScanner->devicesInfoList(); - for (auto& info : infos) { - QString name = mScanner->deviceName(info); - addItem(name, info); - } - - emit finished(); -} - -void xToolsBleDeviceInfoComboBox::onDeviceDiscovered(const QBluetoothDeviceInfo& info) -{ - if (!isEnabled()) { - return; - } - - addItem(info.name(), QVariant::fromValue(info)); -} - -void xToolsBleDeviceInfoComboBox::onErrorOccurred(const QString& errStr) -{ - QMessageBox::warning(this, tr("Error Occurred"), errStr); -} diff --git a/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.h b/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.h deleted file mode 100644 index 46caf7e8..00000000 --- a/Source/Common/CommonUI/xToolsBleDeviceInfoComboBox.h +++ /dev/null @@ -1,42 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include - -#include "xToolsBleScanner.h" -#include "xToolsComboBox.h" - -class xToolsBleDeviceInfoComboBox : public xToolsComboBox -{ - Q_OBJECT -public: - xToolsBleDeviceInfoComboBox(QWidget *parent = Q_NULLPTR); - ~xToolsBleDeviceInfoComboBox(); - void startDiscover(); - void stopDiscover(); - bool isActive(); - void setTimeoutInterval(int interval); - void setNameFiltter(const QString &filtter); - -signals: - void finished(); - void started(); - -protected: - virtual void changeEvent(QEvent *event) override; - -private: - xToolsBleScanner *mScanner; - -private slots: - void onFinished(); - void onDeviceDiscovered(const QBluetoothDeviceInfo &info); - void onErrorOccurred(const QString &errStr); -}; diff --git a/Source/ModbusStudio/CMakeLists.txt b/Source/ModbusStudio/CMakeLists.txt deleted file mode 100644 index 09e1c990..00000000 --- a/Source/ModbusStudio/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -file(GLOB_RECURSE SOURCE_H "${CMAKE_SOURCE_DIR}/Source/ModbusStudio/*.h") -file(GLOB_RECURSE SOURCE_UI "${CMAKE_SOURCE_DIR}/Source/ModbusStudio/*.ui") -file(GLOB_RECURSE SOURCE_CPP "${CMAKE_SOURCE_DIR}/Source/ModbusStudio/*.cpp") - -list(APPEND ALL_SOURCE ${SOURCE_H}) -list(APPEND ALL_SOURCE ${SOURCE_UI}) -list(APPEND ALL_SOURCE ${SOURCE_CPP}) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsSettings.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsSettings.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsInterface.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsInterface.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsTranslator.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/Common/xToolsTranslator.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsUi.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsMainWindow.h) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/Source/Common/CommonUI/xToolsMainWindow.cpp) -list(APPEND ALL_SOURCE ${CMAKE_SOURCE_DIR}/xTools.qrc) - -x_tools_add_executable("ModbusStudio" ${ALL_SOURCE}) -x_tools_set_target_properties(ModbusStudio) -x_tools_deploy_qt(ModbusStudio) - -target_link_libraries(ModbusStudio PRIVATE glog::glog) -target_link_libraries(ModbusStudio PRIVATE Qt${QT_VERSION_MAJOR}::Widgets) -target_link_libraries(ModbusStudio PRIVATE Qt${QT_VERSION_MAJOR}::Network) -target_link_libraries(ModbusStudio PRIVATE Qt${QT_VERSION_MAJOR}::SerialBus) -target_link_libraries(ModbusStudio PRIVATE Qt${QT_VERSION_MAJOR}::SerialPort) diff --git a/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.cpp b/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.cpp deleted file mode 100644 index 5bfa1a5a..00000000 --- a/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsModbusStudio.h" - -#include -#include -#include -#include -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) -#include -#include -#else -#include -#include -#endif - -xToolsModbusStudio::xToolsModbusStudio(QObject *parent) - : QObject(parent) -{} - -xToolsModbusStudio::~xToolsModbusStudio() {} - -xToolsModbusStudio *xToolsModbusStudio::Instance() -{ - static xToolsModbusStudio *factory = Q_NULLPTR; - - if (!factory) { - factory = new xToolsModbusStudio(qApp); - } - - return factory; -} - -const QString xToolsModbusStudio::TypeName(int type) -{ - if (type == kModbusRtuSerialClient) { - return tr("RTU Client"); - } else if (type == kModbusRtuSerialServer) { - return tr("RTU Server"); - } else if (type == kModbusTcpClient) { - return tr("TCP Client"); - } else if (type == kModbusTcpServer) { - return tr("TCP Server"); - } - - Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); - qWarning() << "Unknown modebus device type"; - - return "Unknown"; -} - -QModbusDevice *xToolsModbusStudio::CreateDevice(int type) -{ - if (type == kModbusRtuSerialClient) { - qInfo() << "Create rtu serial client."; -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - return new QModbusRtuSerialMaster(this); -#else - return new QModbusRtuSerialClient(this); -#endif - } else if (type == kModbusRtuSerialServer) { - qInfo() << "Create rtu serial server."; -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - return new QModbusRtuSerialSlave(this); -#else - return new QModbusRtuSerialServer(this); -#endif - } else if (type == kModbusTcpClient) { - qInfo() << "Create tcp client."; - return new QModbusTcpClient(); - } else if (type == kModbusTcpServer) { - qInfo() << "Create tcp server."; - return new QModbusTcpServer(); - } - - Q_ASSERT_X(false, __FUNCTION__, "Unknown modebus device type"); - qWarning() << "Unknown modebus device type"; - - return Q_NULLPTR; -} - -bool xToolsModbusStudio::IsTcpDevice(QModbusDevice *modbus_device) -{ - if (modbus_device) { - if (qobject_cast(modbus_device)) { - return true; - } else if (qobject_cast(modbus_device)) { - return true; - } - } - - return false; -} - -bool xToolsModbusStudio::IsRtuSerialDevice(QModbusDevice *modbus_device) -{ - if (modbus_device) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) - if (qobject_cast(modbus_device)) { -#else - if (qobject_cast(modbus_device)) { -#endif - return true; -#if QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) - } else if (qobject_cast(modbus_device)) { -#else - } else if (qobject_cast(modbus_device)) { -#endif - return true; - } - } - - return false; -} - -bool xToolsModbusStudio::IsTcpDeviceType(int type) -{ - bool is_tcp = (type == kModbusTcpClient); - is_tcp |= (type == kModbusTcpServer); - - return is_tcp; -} - -bool xToolsModbusStudio::IsRtuSerialDeviceType(int type) -{ - bool is_rtu = (type == kModbusRtuSerialClient); - is_rtu |= (type == kModbusRtuSerialServer); - - return is_rtu; -} - -bool xToolsModbusStudio::IsServerDevice(QModbusDevice *modbus_device) -{ - if (modbus_device && qobject_cast(modbus_device)) { - return true; - } - - return false; -} - -bool xToolsModbusStudio::IsClientDevice(QModbusDevice *modbus_device) -{ - if (modbus_device && qobject_cast(modbus_device)) { - return true; - } - - return false; -} - -bool xToolsModbusStudio::ConnectDeivce(QModbusDevice *modbus_device) -{ - if (modbus_device) { - return modbus_device->connectDevice(); - } - - return false; -} - -bool xToolsModbusStudio::IsConnected(QModbusDevice *modbus_device) -{ - if (modbus_device) { - if (modbus_device->state() == QModbusDevice::ConnectedState) { - return true; - } - } - - return false; -} - -bool xToolsModbusStudio::IsValidModbusReply(QModbusReply *reply) -{ - if (reply && !reply->isFinished()) { - return true; - } - - return false; -} - -bool xToolsModbusStudio::SetServerData(QModbusDevice *server, - QModbusDataUnit::RegisterType table, - int address, - int data, - bool enable_log) -{ - bool is_ok = false; - if (server && qobject_cast(server)) { - QModbusServer *modbusServer = qobject_cast(server); - is_ok = modbusServer->setData(table, address, data); - if (enable_log) { - qInfo() << "Set register data result:" << is_ok << "table:" << table - << "address:" << address << "data:" << data; - } - } - - return is_ok; -} - -QList xToolsModbusStudio::GetServerData(QModbusDevice *server, - QModbusDataUnit::RegisterType table, - int address, - int quantity) -{ - QList values; - if (server && qobject_cast(server)) { - QModbusServer *cooked_server = qobject_cast(server); - for (int i = address; i < quantity; i++) { - quint16 value; - if (cooked_server->data(table, i, &value)) { - values.append(value); - } else { - qWarning() << "Parameters error!"; - break; - } - } - } else { - qWarning() << "Can not get values from null object!"; - } - - return values; -} - -void xToolsModbusStudio::DeleteModbusDevuce(QModbusDevice **modbus_device) -{ - if (*modbus_device) { - QModbusServer *server = qobject_cast(*modbus_device); - if (server) { - server->disconnect(); - } - - (*modbus_device)->deleteLater(); - (*modbus_device) = Q_NULLPTR; - } -} - -QModbusDevice *xToolsModbusStudio::CreateRtuSerialDevice( - int type, const QString &port_name, int parity, int baud_rate, int data_bits, int stop_bits) -{ - QModbusDevice *device = CreateDevice(type); - if (IsRtuSerialDevice(device)) { - device->setConnectionParameter(QModbusDevice::SerialPortNameParameter, port_name); - device->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, baud_rate); - device->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, data_bits); - device->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, stop_bits); - device->setConnectionParameter(QModbusDevice::SerialParityParameter, parity); - - qInfo() << "Set rtu serial modbus device parameters:" - << "port name:" << port_name << "baud rate:" << baud_rate - << "data bits:" << data_bits << "stop bits" << stop_bits << "parity" << parity; - } - - return device; -} - -QModbusDevice *xToolsModbusStudio::CreateTcpDevice(int type, QString address, int port) -{ - QModbusDevice *device = CreateDevice(type); - if (IsTcpDevice(device)) { - device->setConnectionParameter(QModbusDevice::NetworkAddressParameter, address); - device->setConnectionParameter(QModbusDevice::NetworkPortParameter, port); - - qInfo() << "Set tcp modbus device parameters:" - << "ip address:" << address << "port" << port; - } - - return device; -} - -void xToolsModbusStudio::SetClientDeviceParameters(QModbusDevice *client, - int timeout, - int number_of_retries) -{ - if (client) { - qInfo() << "Set modbus client device parameters:" - << "timeout:" << timeout << "number_of_retries" << number_of_retries; - - QModbusClient *cooked_client = qobject_cast(client); - cooked_client->setTimeout(timeout); - cooked_client->setNumberOfRetries(number_of_retries); - } -} - -void xToolsModbusStudio::SetServerDeviceParameters(QModbusDevice *server, - int address, - bool device_busy, - bool listen_only_mode) -{ - if (server) { - qInfo() << "Set modbus server device parameters:" - << "address:" << address << "device busy" << device_busy - << "listen only mode:" << listen_only_mode; - - QModbusServer *cooked_server = qobject_cast(server); - cooked_server->setServerAddress(address); - cooked_server->setValue(QModbusServer::DeviceBusy, device_busy); - cooked_server->setValue(QModbusServer::ListenOnlyMode, listen_only_mode); - } -} - -QModbusReply *xToolsModbusStudio::SendWriteRequest(QModbusDevice *modbus_device, - int register_type, - int start_address, -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - QVector values, -#else - QList values, -#endif - int server_address) -{ - if (modbus_device && IsClientDevice(modbus_device)) { - auto cooked_type = QModbusDataUnit::RegisterType(register_type); - QModbusDataUnit dataUnit(cooked_type, start_address, values); - if (dataUnit.isValid()) { - qInfo() << "register-type:" << register_type << " start-address:" << start_address - << " serverAddress:" << server_address << " values:" << values; - - auto *client = qobject_cast(modbus_device); - QModbusReply *reply = client->sendWriteRequest(dataUnit, server_address); - return reply; - } else { - qWarning() << "Unvalid data unit!"; - } - } - - return Q_NULLPTR; -} - -QModbusReply *xToolsModbusStudio::SendRawRequest(QModbusDevice *modbus_device, - int server_address, - int function_code, - const QByteArray &data) -{ - auto cooked_function_code = QModbusPdu::FunctionCode(function_code); - QModbusRequest request(cooked_function_code, data); - if (IsClientDevice(modbus_device)) { - QModbusClient *client = qobject_cast(modbus_device); - return client->sendRawRequest(request, server_address); - } - - return Q_NULLPTR; -} diff --git a/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.h b/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.h deleted file mode 100644 index dc89ec75..00000000 --- a/Source/ModbusStudio/ModbusStudio/xToolsModbusStudio.h +++ /dev/null @@ -1,79 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include -#include -#include -#include - -class xToolsModbusStudio : public QObject -{ - Q_OBJECT -public: - enum ModbusDeviceType { - kModbusRtuSerialClient, - kModbusRtuSerialServer, - kModbusTcpClient, - kModbusTcpServer - }; - Q_ENUM(ModbusDeviceType) - -private: - xToolsModbusStudio(QObject *parent = Q_NULLPTR); - -public: - ~xToolsModbusStudio(); - static xToolsModbusStudio *Instance(); - -public: - const QString TypeName(int type); - QModbusDevice *CreateDevice(int type); - bool IsTcpDevice(QModbusDevice *modbus_device); - bool IsRtuSerialDevice(QModbusDevice *modbus_device); - bool IsTcpDeviceType(int type); - bool IsRtuSerialDeviceType(int type); - bool IsServerDevice(QModbusDevice *modbus_device); - bool IsClientDevice(QModbusDevice *modbus_device); - bool ConnectDeivce(QModbusDevice *modbus_device); - bool IsConnected(QModbusDevice *modbus_device); - bool IsValidModbusReply(QModbusReply *reply); - bool SetServerData(QModbusDevice *server, - QModbusDataUnit::RegisterType table, - int address, - int data, - bool enable_log = true); - QList GetServerData(QModbusDevice *server, - QModbusDataUnit::RegisterType table, - int address, - int quantity); - void DeleteModbusDevuce(QModbusDevice **modbus_device); - - QModbusDevice *CreateRtuSerialDevice( - int type, const QString &port_name, int parity, int baud_rate, int data_bits, int stop_bits); - QModbusDevice *CreateTcpDevice(int deviceType, QString address, int port); - void SetClientDeviceParameters(QModbusDevice *client, int timeout, int number_of_retries); - void SetServerDeviceParameters(QModbusDevice *server, - int address, - bool device_busy, - bool listen_only_mode); - QModbusReply *SendWriteRequest(QModbusDevice *modbus_device, - int register_type, - int start_address, -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) - QVector values, -#else - QList values, -#endif - int server_address); - QModbusReply *SendRawRequest(QModbusDevice *modbus_device, - int server_address, - int function_code, - const QByteArray &data); -}; diff --git a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.cpp b/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.cpp deleted file mode 100644 index 58c14180..00000000 --- a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.cpp +++ /dev/null @@ -1,1271 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsModbusStudioUi.h" -#include "ui_xToolsModbusStudioUi.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0) -#include -#include -#else -#include -#include -#endif - -#include "xToolsCompatibility.h" -#include "xToolsModbusStudio.h" -#include "xToolsSettings.h" - -#define RXCOLOR "green" -#define TXCOLOR "blue" -#define RXFLAG "rx:" -#define TXFLAG "tx:" -#define MAX_HISTORY_INDEX 9 - -struct xToolsModbusUiSettingKeys -{ - const QString deviceIndex = "xToolsModbus/deviceIndex"; - - const QString portName = "xToolsModbus/portName"; - const QString parity = "xToolsModbus/parity"; - const QString baudRate = "xToolsModbus/baudRate"; - const QString dataBits = "xToolsModbus/dataBits"; - const QString stopBits = "xToolsModbus/stopBits"; - const QString customBaudRate = "xToolsModbus/customBaudRate"; - - const QString address = "xToolsModbus/address"; - const QString port = "xToolsModbus/port"; - const QString customAddress = "xToolsModbus/customAddress"; - - const QString clientTimeout = "xToolsModbus/clientTimeout"; - const QString clientRepeatTime = "xToolsModbus/clientRepeatTime"; - - const QString serverIsBusy = "xToolsModbus/serverIsBusy"; - const QString serverJustListen = "xToolsModbus/serverJustListen"; - const QString serverAddress = "xToolsModbus/serverAddress"; - - const QString functionCode = "xToolsModbus/functionCode"; - const QString targetAddress = "xToolsModbus/targetAddress"; - const QString startAddress = "xToolsModbus/startAddress"; - const QString addressNumber = "xToolsModbus/addressNumber"; - - const QString sendHistory = "xToolsModbus/sendHistory"; - const QString sendHistoryIndex = "xToolsModbus/sendHistoryIndex"; - const QString pdu = "pdu"; -}; - -class ReadOnlyDelegate : public QItemDelegate -{ -public: - ReadOnlyDelegate(QWidget *parent = Q_NULLPTR) - : QItemDelegate(parent) - {} - QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem &option, - const QModelIndex &index) const override - { - Q_UNUSED(parent); - Q_UNUSED(option); - Q_UNUSED(index); - return Q_NULLPTR; - } -}; - -QList vectorTolist(const QVector &vector) -{ - QList list; - for (int i = 0; i < vector.length(); vector.count()) { - list.append(vector.at(i)); - } - return list; -} - -QVector listToVector(const QList &list) -{ - QVector vector; - for (int i = 0; i < list.length(); list.count()) { - vector.append(list.at(i)); - } - return vector; -} - -xToolsModbusStudioUi::xToolsModbusStudioUi(QWidget *parent) - : QWidget{parent} - , ui(new Ui::xToolsModbusStudioUi) - , m_modbusDevice(Q_NULLPTR) - , m_registerModel(Q_NULLPTR) - , m_keyCtx(new xToolsModbusUiSettingKeys) -{ - if (!m_settings) { - m_settings = xToolsSettings::instance(); - } - - ui->setupUi(this); - - initComponents(); - initSettings(); - initSignals(); - - updateUiState(false); - onDeviceTypeChanged(); - updateClientTableView(); - updateClientReadWriteButtonState(); -} - -xToolsModbusStudioUi::~xToolsModbusStudioUi() -{ - delete ui; -} - -void xToolsModbusStudioUi::initComponents() -{ - initComponentDevices(); - initComponentAddress(); - initComponentPortName(); - initComponnetBaudRate(); - initComponnetDataBits(); - initComponnetStopBits(); - initComponnetParity(); - initComponentFunctionCode(); - initComponentRegisterTableView(); - initComponentInput(); - initComponentRegisterTabWidget(); -} - -void xToolsModbusStudioUi::initComponentDevices() -{ - ui->device_list_->addItem(tr("RtuClient"), xToolsModbusStudio::kModbusRtuSerialClient); - ui->device_list_->addItem(tr("RtuServer"), xToolsModbusStudio::kModbusRtuSerialServer); - ui->device_list_->addItem(tr("TcpClient"), xToolsModbusStudio::kModbusTcpClient); - ui->device_list_->addItem(tr("TcpServer"), xToolsModbusStudio::kModbusTcpServer); -} - -void xToolsModbusStudioUi::initComponentAddress() -{ - ui->address_combo_box->clear(); - QList addresses = QNetworkInterface::allAddresses(); - for (QHostAddress &address : addresses) { - if (address.protocol() == QAbstractSocket::IPv4Protocol) { - ui->address_combo_box->addItem(address.toString()); - } - } -} - -void xToolsModbusStudioUi::initComponentPortName() -{ - ui->port_name_->clear(); - QList infos = QSerialPortInfo::availablePorts(); - for (QSerialPortInfo &info : infos) { - ui->port_name_->addItem(info.portName()); - } -} - -void xToolsModbusStudioUi::initComponnetBaudRate() -{ - ui->baud_rate_->clear(); - QList bds = QSerialPortInfo::standardBaudRates(); - for (qint32 &bd : bds) { - ui->baud_rate_->addItem(QString::number(bd), bd); - } -} - -void xToolsModbusStudioUi::initComponnetDataBits() -{ - ui->data_bits_->clear(); - ui->data_bits_->addItem("8", QSerialPort::Data8); - ui->data_bits_->addItem("7", QSerialPort::Data7); - ui->data_bits_->addItem("6", QSerialPort::Data6); - ui->data_bits_->addItem("5", QSerialPort::Data5); -} - -void xToolsModbusStudioUi::initComponnetStopBits() -{ - ui->stop_bits_->clear(); - ui->stop_bits_->addItem("1", QSerialPort::OneStop); -#ifdef Q_OS_WIN - ui->stop_bits_->addItem("1.5", QSerialPort::OneAndHalfStop); -#endif - ui->stop_bits_->addItem("2", QSerialPort::TwoStop); -} - -void xToolsModbusStudioUi::initComponnetParity() -{ - ui->parity_->clear(); - ui->parity_->addItem(tr("NoParity"), QSerialPort::NoParity); - ui->parity_->addItem(tr("EvenParity"), QSerialPort::EvenParity); - ui->parity_->addItem(tr("OddParity"), QSerialPort::OddParity); - ui->parity_->addItem(tr("SpaceParity"), QSerialPort::SpaceParity); - ui->parity_->addItem(tr("MarkParity"), QSerialPort::MarkParity); -} - -void xToolsModbusStudioUi::initComponentFunctionCode() -{ - const QString str0x01 = tr("0x01-ReadCoils"); - const QString str0x02 = tr("0x02-ReadDiscreteInputs"); - const QString str0x03 = tr("0x03-ReadHoldingRegisters"); - const QString str0x04 = tr("0x04-ReadInputRegisters"); - const QString str0x05 = tr("0x05-WriteSingleCoil"); - const QString str0x06 = tr("0x06-WriteSingleRegister"); - const QString str0x0f = tr("0x0f-WriteMultipleCoils"); - const QString str0x10 = tr("0x10-WriteMultipleRegisters"); - - int func0x01 = QModbusDataUnit::Coils; - int func0x02 = QModbusDataUnit::DiscreteInputs; - int func0x03 = QModbusDataUnit::HoldingRegisters; - int func0x04 = QModbusDataUnit::InputRegisters; - int func0x05 = QModbusDataUnit::Coils; - int func0x06 = QModbusDataUnit::HoldingRegisters; - int func0x0f = QModbusDataUnit::Coils; - int func0x10 = QModbusDataUnit::HoldingRegisters; - - ui->function_code_->addItem(str0x01, func0x01); - ui->function_code_->addItem(str0x02, func0x02); - ui->function_code_->addItem(str0x03, func0x03); - ui->function_code_->addItem(str0x04, func0x04); - ui->function_code_->addItem(str0x05, func0x05); - ui->function_code_->addItem(str0x06, func0x06); - ui->function_code_->addItem(str0x0f, func0x0f); - ui->function_code_->addItem(str0x10, func0x10); -} - -void xToolsModbusStudioUi::initComponentRegisterTableView() -{ - QTableView *table_view = CreateTableView(1, ui->client_registers_); - m_registerModel = qobject_cast(table_view->model()); -} - -void xToolsModbusStudioUi::initComponentInput() -{ - QRegularExpression re("([0-9a-fA-F][0-9a-fA-F][ ])*"); - QLineEdit *le = ui->pdu_->lineEdit(); - QRegularExpressionValidator *rev = new QRegularExpressionValidator(re, le); - le->setValidator(rev); - le->clear(); -} - -void xToolsModbusStudioUi::initComponentRegisterTabWidget() -{ - QTabWidget *tab_widget = ui->server_registers_; - QStringList titles = QStringList() << tr("Coils") << tr("DiscreteInputs") - << tr("InputRegisters") << tr("HoldingRegisters"); - for (QString &title : titles) { - QTableView *table_view = CreateTableView(UINT16_MAX + 1, Q_NULLPTR); - table_view->verticalHeader()->hide(); - tab_widget->addTab(table_view, title); - } -} - -void xToolsModbusStudioUi::initSettings() -{ - initSettingsDevice(); - initSettingsNetwork(); - initSettingsSerialPort(); - initSettingsClient(); - initSettingsServer(); - initSettingsClientOperations(); - initSettingsInput(); -} - -void xToolsModbusStudioUi::initSettingsDevice() -{ - int deviceIndex = m_settings->value(m_keyCtx->deviceIndex).toInt(); - if (deviceIndex >= 0 && deviceIndex < ui->device_list_->count()) { - ui->device_list_->setCurrentIndex(deviceIndex); - } -} - -void xToolsModbusStudioUi::initSettingsNetwork() -{ - QString address = m_settings->value(m_keyCtx->address).toString(); - ui->address_combo_box->setCurrentText(address); - - QVariant portValiant = m_settings->value(m_keyCtx->port); - int port = portValiant.toInt(); - if (portValiant.isNull()) { - port = 502; - } - ui->port_spin_box->setValue(port); -} - -void xToolsModbusStudioUi::initSettingsSerialPort() -{ - auto SetComboBoxIndex = [](int index, QComboBox *cb) { - if (index >= 0 && index < cb->count()) { - cb->setCurrentIndex(index); - } - }; - - QString portName = m_settings->value(m_keyCtx->portName).toString(); - int index = ui->port_name_->findText(portName); - SetComboBoxIndex(index, ui->port_name_); - - index = m_settings->value(m_keyCtx->parity).toInt(); - SetComboBoxIndex(index, ui->parity_); - - QString bd = m_settings->value(m_keyCtx->baudRate).toString(); - ui->baud_rate_->setCurrentText(bd); - - index = m_settings->value(m_keyCtx->dataBits).toInt(); - SetComboBoxIndex(index, ui->data_bits_); - - index = m_settings->value(m_keyCtx->stopBits).toInt(); - SetComboBoxIndex(index, ui->stop_bits_); -} - -void xToolsModbusStudioUi::initSettingsClient() -{ - int timeout = m_settings->value(m_keyCtx->clientTimeout).toInt(); - ui->timeout_->setValue(timeout < 100 ? 100 : timeout); - - const QString key = m_keyCtx->clientRepeatTime; - int repeatTimes = m_settings->value(key).toInt(); - ui->repeat_time_->setValue(repeatTimes); -} - -void xToolsModbusStudioUi::initSettingsServer() -{ - bool isBusy = m_settings->value(m_keyCtx->serverIsBusy).toBool(); - ui->device_busy_->setChecked(isBusy); - - QString key = m_keyCtx->serverJustListen; - bool just_listen = m_settings->value(key).toBool(); - ui->listen_only_mode_->setChecked(just_listen); - - int address = m_settings->value(m_keyCtx->serverAddress).toInt(); - ui->server_address->setValue(address); -} - -void xToolsModbusStudioUi::initSettingsClientOperations() -{ - int index = m_settings->value(m_keyCtx->functionCode).toInt(); - if (index >= 0 && index < ui->function_code_->count()) { - ui->function_code_->setCurrentIndex(index); - } - - int address = m_settings->value(m_keyCtx->targetAddress).toInt(); - ui->device_address_->setValue(address); - - int start = m_settings->value(m_keyCtx->startAddress).toInt(); - ui->start_address_->setValue(start); - - int number = m_settings->value(m_keyCtx->addressNumber).toInt(); - ui->quantity_->setValue(number); -} - -void xToolsModbusStudioUi::initSettingsInput() -{ - ui->pdu_->clear(); - m_settings->beginReadArray(m_keyCtx->sendHistory); - for (int i = 0; i < 10; i++) { - m_settings->setArrayIndex(i); - QString text = m_settings->value(m_keyCtx->pdu).toString(); - if (!text.isEmpty()) { - ui->pdu_->addItem(text); - } - } - m_settings->endArray(); - - int index = m_settings->value(m_keyCtx->sendHistoryIndex).toInt(); - ui->pdu_->setCurrentIndex(index - 1); -} - -void xToolsModbusStudioUi::initSignals() -{ - initSignalsDevice(); - initSignalsNetworking(); - initSignalsSerialPort(); - initSignalsClient(); - initSignalsServer(); - initSignalsClientOperations(); -} - -void xToolsModbusStudioUi::initSignalsDevice() -{ - connect(ui->device_list_, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsModbusStudioUi::onDeviceTypeChanged); - connect(ui->open_button_, &QPushButton::clicked, this, &xToolsModbusStudioUi::onOpenClicked); - connect(ui->cloese_button_, &QPushButton::clicked, this, &xToolsModbusStudioUi::onCloseClicked); -} - -void xToolsModbusStudioUi::initSignalsNetworking() -{ - connect(ui->address_combo_box, - &QComboBox::currentTextChanged, - this, - &xToolsModbusStudioUi::onAddressChanged); - connect(ui->port_spin_box, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onPortChanged); -} - -void xToolsModbusStudioUi::initSignalsSerialPort() -{ - connect(ui->port_name_, - &QComboBox::currentTextChanged, - this, - &xToolsModbusStudioUi::onPortNameChanged); - connect(ui->parity_, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsModbusStudioUi::onParityChanged); - connect(ui->baud_rate_, - &QComboBox::currentTextChanged, - this, - &xToolsModbusStudioUi::onBaudRateChanged); - connect(ui->data_bits_, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsModbusStudioUi::onDataBitsChanged); - connect(ui->stop_bits_, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsModbusStudioUi::onStopBistChanged); -} - -void xToolsModbusStudioUi::initSignalsClient() -{ - connect(ui->timeout_, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onClientTimeoutChanged); - connect(ui->repeat_time_, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onClientRepeatTimeChanged); -} - -void xToolsModbusStudioUi::initSignalsServer() -{ - connect(ui->device_busy_, - &QCheckBox::clicked, - this, - &xToolsModbusStudioUi::onServerIsBusyChanged); - connect(ui->listen_only_mode_, - &QCheckBox::clicked, - this, - &xToolsModbusStudioUi::onServerJustListenChanged); - connect(ui->server_address, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onServerAddressChanged); -} - -void xToolsModbusStudioUi::initSignalsClientOperations() -{ - connect(ui->function_code_, - &QComboBox::currentTextChanged, - this, - &xToolsModbusStudioUi::onFunctionCodeChanged); - connect(ui->device_address_, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onTargetAddressChanged); - connect(ui->start_address_, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onStartAddressChanged); - connect(ui->quantity_, - static_cast(&QSpinBox::valueChanged), - this, - &xToolsModbusStudioUi::onAddressNumberChanged); - connect(ui->read_, &QPushButton::clicked, this, &xToolsModbusStudioUi::onReadClicked); - connect(ui->write_, &QPushButton::clicked, this, &xToolsModbusStudioUi::onWriteClicked); - connect(ui->send_, &QPushButton::clicked, this, &xToolsModbusStudioUi::onSendClicked); -} - -void xToolsModbusStudioUi::onErrorOccurred() -{ - outputMessage(m_modbusDevice->errorString(), true, "", "error"); - if (m_modbusDevice->error() == QModbusDevice::ConnectionError) { - const QString msg = m_modbusDevice->errorString(); - onCloseClicked(); - QMessageBox::warning(this, tr("Error occured"), msg); - } -} - -void xToolsModbusStudioUi::onDeviceTypeChanged() -{ - int type = ui->device_list_->currentData().toInt(); - bool isSerial = (type == xToolsModbusStudio::kModbusRtuSerialClient - || type == xToolsModbusStudio::kModbusRtuSerialServer); - bool isClient = (type == xToolsModbusStudio::kModbusRtuSerialClient - || type == xToolsModbusStudio::kModbusTcpClient); - - // Hide ui component first then show ui component, - // or the window will be resize to the max size of default. - if (isSerial) { - ui->widgetNetworkSettings->setHidden(true); - ui->widgetSerialPortSettings->setHidden(false); - } else { - ui->widgetSerialPortSettings->setHidden(true); - ui->widgetNetworkSettings->setHidden(false); - } - - if (isClient) { - ui->console_->setVisible(true); - ui->widgetServerParameters->setHidden(true); - ui->registersGroupBox->setHidden(true); - ui->widgetClientParameters->setHidden(false); - ui->clientCustomCommandGroupBox->setHidden(false); - ui->clientRegistersGroupBox->setHidden(false); - } else { - ui->console_->setVisible(false); - ui->clientCustomCommandGroupBox->setHidden(true); - ui->clientRegistersGroupBox->setHidden(true); - ui->widgetClientParameters->setHidden(true); - ui->widgetServerParameters->setHidden(false); - ui->registersGroupBox->setHidden(false); - } - - m_settings->setValue(m_keyCtx->deviceIndex, type); -} - -void xToolsModbusStudioUi::onCloseClicked() -{ - xToolsModbusStudio::Instance()->DeleteModbusDevuce(&m_modbusDevice); - updateUiState(false); -} - -void xToolsModbusStudioUi::onOpenClicked() -{ - ui->open_button_->setEnabled(false); - xToolsModbusStudio::Instance()->DeleteModbusDevuce(&m_modbusDevice); - - m_modbusDevice = CreateModbusDevice(); - - if (xToolsModbusStudio::Instance()->IsServerDevice(m_modbusDevice)) { - if (!updateServerMap(m_modbusDevice)) { - ui->open_button_->setEnabled(true); - qWarning() << "Can not reset server map!"; - return; - } - - updateServerParameters(); - - QModbusServer *server = qobject_cast(m_modbusDevice); - updateServerRegistersData(); - connect(server, &QModbusServer::dataWritten, this, &xToolsModbusStudioUi::onDateWritten); - } else if (xToolsModbusStudio::Instance()->IsClientDevice(m_modbusDevice)) { - updateClientParameters(); - } else { - ui->open_button_->setEnabled(true); - qWarning() << "Can not create modbus devices!"; - return; - } - - connect(m_modbusDevice, - &QModbusDevice::errorOccurred, - this, - &xToolsModbusStudioUi::onErrorOccurred); - xToolsModbusStudio *factory = xToolsModbusStudio::Instance(); - bool connected = factory->ConnectDeivce(m_modbusDevice); - if (!connected) { - QString errStr = m_modbusDevice->errorString(); - QString info = tr("Can not open device: %1." - "Please check the parameters and try again!") - .arg(errStr); - QMessageBox::warning(this, tr("Can not open device"), info); - } - - updateUiState(connected); -} - -void xToolsModbusStudioUi::onAddressChanged() -{ - m_settings->setValue(m_keyCtx->address, ui->address_combo_box->currentText()); -} - -void xToolsModbusStudioUi::onPortChanged() -{ - m_settings->setValue(m_keyCtx->port, ui->port_spin_box->value()); -} - -void xToolsModbusStudioUi::onPortNameChanged() -{ - m_settings->setValue(m_keyCtx->portName, ui->port_name_->currentText()); -} - -void xToolsModbusStudioUi::onParityChanged() -{ - m_settings->setValue(m_keyCtx->parity, ui->parity_->currentIndex()); -} - -void xToolsModbusStudioUi::onBaudRateChanged() -{ - m_settings->setValue(m_keyCtx->baudRate, ui->baud_rate_->currentText()); -} - -void xToolsModbusStudioUi::onDataBitsChanged() -{ - m_settings->setValue(m_keyCtx->dataBits, ui->data_bits_->currentIndex()); -} - -void xToolsModbusStudioUi::onStopBistChanged() -{ - m_settings->setValue(m_keyCtx->stopBits, ui->stop_bits_->currentIndex()); -} - -void xToolsModbusStudioUi::onInvokeRefresh() -{ - initComponentPortName(); -} - -void xToolsModbusStudioUi::onClientTimeoutChanged() -{ - m_settings->setValue(m_keyCtx->clientTimeout, ui->timeout_->value()); - updateClientParameters(); -} - -void xToolsModbusStudioUi::onClientRepeatTimeChanged() -{ - m_settings->setValue(m_keyCtx->clientRepeatTime, ui->repeat_time_->value()); - updateClientParameters(); -} - -void xToolsModbusStudioUi::onServerIsBusyChanged() -{ - m_settings->setValue(m_keyCtx->serverIsBusy, ui->device_busy_->isChecked()); - updateServerParameters(); -} - -void xToolsModbusStudioUi::onServerJustListenChanged() -{ - m_settings->setValue(m_keyCtx->serverJustListen, ui->listen_only_mode_->isChecked()); - updateServerParameters(); -} - -void xToolsModbusStudioUi::onServerAddressChanged() -{ - m_settings->setValue(m_keyCtx->serverAddress, ui->server_address->value()); - updateServerParameters(); -} - -void xToolsModbusStudioUi::onFunctionCodeChanged() -{ - m_settings->setValue(m_keyCtx->functionCode, ui->function_code_->currentIndex()); - updateClientReadWriteButtonState(); -} - -void xToolsModbusStudioUi::onTargetAddressChanged() -{ - m_settings->setValue(m_keyCtx->targetAddress, ui->device_address_->value()); -} - -void xToolsModbusStudioUi::onStartAddressChanged() -{ - m_settings->setValue(m_keyCtx->startAddress, ui->start_address_->value()); - updateClientTableView(); -} - -void xToolsModbusStudioUi::onAddressNumberChanged() -{ - m_settings->setValue(m_keyCtx->addressNumber, ui->quantity_->value()); - updateClientTableView(); -} - -void xToolsModbusStudioUi::onReadClicked() -{ - if (!isConnected()) { - return; - } - - if (!xToolsModbusStudio::Instance()->IsClientDevice(m_modbusDevice)) { - return; - } - - int register_type = ui->function_code_->currentData().toInt(); - quint16 start_address = ui->start_address_->value(); - quint16 quantity = ui->quantity_->value(); - quint16 server_address = ui->device_address_->value(); - quint8 function_code = getClientFunctionCode(); - - qInfo() << "[SendReadRequest]" - << "register type:" << register_type << "start address:" << start_address - << "quantity:" << quantity << "server address:" << server_address; - - typedef QModbusDataUnit::RegisterType RegisterType; - RegisterType type = static_cast(register_type); - QModbusDataUnit data_unit(type, start_address, quantity); - QModbusClient *client = qobject_cast(m_modbusDevice); - QModbusReply *reply = client->sendReadRequest(data_unit, server_address); - if (!xToolsModbusStudio::Instance()->IsValidModbusReply(reply)) { - return; - } - - QString info = ui->function_code_->currentText(); - outputMessage(info, false, TXCOLOR, TXFLAG); - connect(reply, &QModbusReply::finished, this, [=]() { - outputModbusReply(reply, function_code); - - if (reply->error() == QModbusDevice::NoError) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - updateClientTableViewData(reply->result().values()); -#else - updateClientTableViewData(vectorTolist(reply->result().values())); -#endif - reply->deleteLater(); - } - }); -} - -void xToolsModbusStudioUi::onWriteClicked() -{ - if (!isConnected()) { - return; - } - - int registerType = ui->function_code_->currentData().toInt(); - int start_address = ui->start_address_->value(); - int server_address = ui->device_address_->value(); - quint8 function_code = getClientFunctionCode(); - QList values = getClientRegisterValue(); - xToolsModbusStudio *factory = xToolsModbusStudio::Instance(); - QModbusReply *reply = factory->SendWriteRequest(m_modbusDevice, - registerType, - start_address, -#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - values, -#else - listToVector(values), -#endif - server_address); - if (xToolsModbusStudio::Instance()->IsValidModbusReply(reply)) { - connect(reply, &QModbusReply::finished, this, [=]() { - outputModbusReply(reply, function_code); - reply->deleteLater(); - }); - - QString info = ui->function_code_->currentText(); - outputMessage(info, false, TXCOLOR, TXFLAG); - } -} - -void xToolsModbusStudioUi::onSendClicked() -{ - if (!isConnected()) { - return; - } - - quint8 server_address = ui->device_address_->value(); - QByteArray pdu = getClientPdu(); - QByteArray data = pdu; - if (!data.isEmpty()) { - data = data.remove(0, 1); - } - - int function_code = int(QModbusDataUnit::Invalid); - if (!pdu.isEmpty()) { - function_code = pdu.at(0); - } - xToolsModbusStudio *factory = xToolsModbusStudio::Instance(); - QModbusReply *reply = factory->SendRawRequest(m_modbusDevice, - server_address, - function_code, - data); - - qWarning() << "Send raw request:" - << "server address:" << server_address << "function code:" << function_code - << "data:" << QString(xToolsByteArrayToHex(pdu, ' ')); - if (xToolsModbusStudio::Instance()->IsValidModbusReply(reply)) { - connect(reply, &QModbusReply::finished, this, [=]() { - outputModbusReply(reply, function_code); - reply->deleteLater(); - }); - - QString info = "pdu(No server address, no crc):"; - info += QString(xToolsByteArrayToHex(pdu, ' ')); - outputMessage(info, false, TXCOLOR, TXFLAG); - } - - // Update settings data. - int index = m_settings->value(m_keyCtx->sendHistoryIndex).toInt(); - bool ret = writeSettingsArray(m_keyCtx->sendHistory, - m_keyCtx->pdu, - QString(xToolsByteArrayToHex(pdu, ' ')), - index, - MAX_HISTORY_INDEX); - if (!ret) { - return; - } - - if (index > ui->pdu_->count()) { - ui->pdu_->addItem(QString(xToolsByteArrayToHex(pdu, ' '))); - } else { - ui->pdu_->insertItem(index, QString(xToolsByteArrayToHex(pdu, ' '))); - } - - index = index + 1 > MAX_HISTORY_INDEX ? 0 : index + 1; - m_settings->setValue(m_keyCtx->sendHistoryIndex, index); -} - -void xToolsModbusStudioUi::onDateWritten(QModbusDataUnit::RegisterType table, int address, int size) -{ - qInfo() << "Data written:" - << "table:" << table << "start address:" << address << "size:" << size; - QTableView *tv = getTableView(table); - QStandardItemModel *model = qobject_cast(tv->model()); - QModbusServer *server = qobject_cast(m_modbusDevice); - QList data = xToolsModbusStudio::Instance()->GetServerData(server, table, address, size); - size = qMin(data.count(), size); - for (int i = 0; i < size; i++) { - int row = address + i; - int base = 16; - int width = base == 2 ? 16 : (base == 10 ? 5 : 4); - int value = data.at(i); - QString cooked_str = QString::number(value, base); - cooked_str = cooked_str.rightJustified(width, '0', true); - QStandardItem *item = model->item(row, 1); - if (item) { - item->setData(cooked_str, Qt::DisplayRole); - item->setTextAlignment(Qt::AlignCenter); - } - } - - tv->viewport()->update(); -} - -void xToolsModbusStudioUi::onItemChanged(QStandardItem *item) -{ - if (!item) { - return; - } - - if (item->column() != 1) { - return; - } - - if (xToolsModbusStudio::Instance()->IsServerDevice(m_modbusDevice)) { - int address = item->row(); - int current_index = ui->server_registers_->currentIndex(); - QModbusDataUnit::RegisterType table = QModbusDataUnit::Invalid; - if (current_index == 0) { - table = QModbusDataUnit::Coils; - } else if (current_index == 1) { - table = QModbusDataUnit::DiscreteInputs; - } else if (current_index == 2) { - table = QModbusDataUnit::InputRegisters; - } else if (current_index == 3) { - table = QModbusDataUnit::HoldingRegisters; - } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknow table type!"); - return; - } - - quint16 value = item->text().toInt(Q_NULLPTR, 16); - xToolsModbusStudio::Instance()->SetServerData(m_modbusDevice, table, address, value); - } -} - -QModbusDevice *xToolsModbusStudioUi::CreateModbusDevice() -{ - QModbusDevice *device = Q_NULLPTR; - int type = ui->device_list_->currentData().toInt(); - if (xToolsModbusStudio::Instance()->IsRtuSerialDeviceType(type)) { - QString port_name = ui->port_name_->currentText(); - int parity = ui->parity_->currentData().toInt(); - int baud_rate = ui->baud_rate_->currentData().toInt(); - int data_bits = ui->data_bits_->currentData().toInt(); - int stop_bits = ui->stop_bits_->currentData().toInt(); - xToolsModbusStudio *factory = xToolsModbusStudio::Instance(); - device = factory->CreateRtuSerialDevice(type, - port_name, - parity, - baud_rate, - data_bits, - stop_bits); - } else if (xToolsModbusStudio::Instance()->IsTcpDeviceType(type)) { - QString address = ui->address_combo_box->currentText(); - int port = ui->port_spin_box->value(); - xToolsModbusStudio *factory = xToolsModbusStudio::Instance(); - device = factory->CreateTcpDevice(type, address, port); - } else { - Q_ASSERT_X(false, __FUNCTION__, "Unknown device type"); - } - - return device; -} - -QTableView *xToolsModbusStudioUi::CreateTableView(int rowCount, QTableView *tableView) -{ - if (!tableView) { - tableView = new QTableView(this); - } - - QHeaderView *hv = tableView->horizontalHeader(); - QStandardItemModel *model = new QStandardItemModel(tableView); - QStringList labels = QStringList() << tr("Address") << tr("Value") << tr("Description"); - model->setHorizontalHeaderLabels(labels); - model->setColumnCount(3); - model->setRowCount(rowCount); - tableView->setModel(model); - tableView->verticalHeader()->hide(); - tableView->setItemDelegateForColumn(0, new ReadOnlyDelegate(tableView)); - updateClientTableViewAddress(tableView, 0); - hv->setStretchLastSection(true); - - // Set the default value to 0. - model->blockSignals(true); - for (int row = 0; row < rowCount; row++) { - QModelIndex index = model->index(row, 1); - QMap roles; - roles.insert(Qt::DisplayRole, "0000"); - model->setItemData(index, roles); - - QStandardItem *item = model->item(row, 1); - item->setTextAlignment(Qt::AlignCenter); - } - model->blockSignals(false); - - connect(model, &QStandardItemModel::itemChanged, this, &xToolsModbusStudioUi::onItemChanged); - - return tableView; -} - -void xToolsModbusStudioUi::updateUiState(bool connected) -{ - ui->device_list_->setEnabled(!connected); - ui->cloese_button_->setEnabled(connected); - ui->open_button_->setEnabled(!connected); - ui->widgetNetworkSettings->setEnabled(!connected); - ui->widgetSerialPortSettings->setEnabled(!connected); -#if 0 - ui->clientGroupBox->setEnabled(!connected); - ui->widgetServerParameters->setEnabled(!connected); -#endif -} - -void xToolsModbusStudioUi::updateClientTableView() -{ - int number = ui->quantity_->value(); - int rowCount = m_registerModel->rowCount(); - if (number > rowCount) { - m_registerModel->insertRows(rowCount, number - rowCount); - } else if (number < rowCount) { - m_registerModel->removeRows(number, rowCount - number); - } - - // Update address. - int start_address = ui->start_address_->value(); - updateClientTableViewAddress(ui->client_registers_, start_address); -} - -void xToolsModbusStudioUi::updateClientTableViewData(const QList &values) -{ - for (int row = 0; row < values.count(); row++) { - int value = values.at(row); - QModelIndex index = m_registerModel->index(row, 1); - QMap roles; - QString str = QString("%1").arg(QString::number(value, 16), 4, '0'); - roles.insert(Qt::DisplayRole, str); - m_registerModel->setItemData(index, roles); - QStandardItem *item = m_registerModel->item(row, 1); - if (item) { - item->setTextAlignment(Qt::AlignCenter); - } - } - - // Refresh the view, or the new value will not be show. - ui->client_registers_->viewport()->update(); -} - -void xToolsModbusStudioUi::updateClientReadWriteButtonState() -{ - QStringList list = ui->function_code_->currentText().split('-'); - int code = list.length() ? list.first().toInt(Q_NULLPTR, 16) : 0; - bool is_reading_operation = false; - if (code == 0x01 || code == 0x02 || code == 0x03 || code == 0x04) { - is_reading_operation = true; - } - - if (code == 0x05 || code == 0x06) { - ui->quantity_->setValue(1); - } - - ui->read_->setEnabled(is_reading_operation); - ui->write_->setEnabled(!is_reading_operation); -} - -void xToolsModbusStudioUi::updateClientParameters() -{ - int timeout = ui->timeout_->value(); - int repeat_time = ui->repeat_time_->value(); - xToolsModbusStudio::Instance()->SetClientDeviceParameters(m_modbusDevice, timeout, repeat_time); -} - -void xToolsModbusStudioUi::updateClientTableViewAddress(QTableView *view, int start_address) -{ - auto *model = qobject_cast(view->model()); - for (int row = 0; row < model->rowCount(); row++) { - int address = row + start_address; - QString text = QString("%1").arg(QString::number(address), 5, '0'); - QModelIndex index = model->index(row, 0); - QMap roles; - roles.insert(Qt::DisplayRole, text); - model->setItemData(index, roles); - - QStandardItem *item = model->item(row, 0); - if (item) { - item->setTextAlignment(Qt::AlignCenter); - } - } -} - -void xToolsModbusStudioUi::updateServerParameters() -{ - bool device_busy = ui->device_busy_->isChecked(); - bool listen_only_mode = ui->listen_only_mode_->isChecked(); - int address = ui->server_address->value(); - xToolsModbusStudio::Instance()->SetServerDeviceParameters(m_modbusDevice, - address, - device_busy, - listen_only_mode); -} - -bool xToolsModbusStudioUi::updateServerMap(QModbusDevice *server) -{ - if (server && qobject_cast(server)) { - QVector values(UINT16_MAX + 1, 0); - QModbusDataUnit dataUnit(QModbusDataUnit::Coils, 0, values); - - QModbusDataUnitMap map; - map.insert(QModbusDataUnit::Coils, dataUnit); - map.insert(QModbusDataUnit::DiscreteInputs, dataUnit); - map.insert(QModbusDataUnit::HoldingRegisters, dataUnit); - map.insert(QModbusDataUnit::InputRegisters, dataUnit); - - QModbusServer *cooked_server = qobject_cast(server); - cooked_server->blockSignals(true); - bool is_ok = cooked_server->setMap(map); - cooked_server->blockSignals(false); - return is_ok; - } - - return false; -} - -void xToolsModbusStudioUi::updateServerRegistersData() -{ - for (int i = 0; i < 4; i++) { - QWidget *widget = ui->server_registers_->widget(i); - QTableView *table_view = qobject_cast(widget); - auto *model = qobject_cast(table_view->model()); - int type = QModbusDataUnit::Invalid; - if (i == 0) { - type = QModbusDataUnit::Coils; - } else if (i == 1) { - type = QModbusDataUnit::DiscreteInputs; - } else if (i == 2) { - type = QModbusDataUnit::InputRegisters; - } else if (i == 3) { - type = QModbusDataUnit::HoldingRegisters; - } else { - qWarning() << "Unknown register type."; - continue; - } - - for (int row = 0; row < model->rowCount(); row++) { - QStandardItem *item = model->item(row, 1); - quint16 value = item ? item->text().toInt(Q_NULLPTR, 16) : 0; - auto table = static_cast(type); - xToolsModbusStudio::Instance()->SetServerData(m_modbusDevice, table, row, value, false); - } - } -} - -quint8 xToolsModbusStudioUi::getClientFunctionCode() -{ - QString txt = ui->function_code_->currentText(); - QStringList list = txt.split('-', xToolsSkipEmptyParts); - if (list.length()) { - return list.first().toInt(Q_NULLPTR, 16); - } - - return 0; -} - -QList xToolsModbusStudioUi::getClientRegisterValue() -{ - QList values; - for (int row = 0; row < m_registerModel->rowCount(); row++) { - QStandardItem *item = m_registerModel->item(row, 1); - if (item) { - QString text = item->text(); - values.append(text.toInt(Q_NULLPTR, 16)); - } else { - values.append(0); - } - } - - return values; -} - -QByteArray xToolsModbusStudioUi::getClientPdu() -{ - QString text = ui->pdu_->currentText(); -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - QStringList valueList = text.split(' ', QString::SkipEmptyParts); -#else - QStringList valueList = text.split(' ', Qt::SkipEmptyParts); -#endif - QByteArray data; - for (QString &value : valueList) { - data.append(char(value.toInt(Q_NULLPTR, 16))); - } - - return data; -} - -QTableView *xToolsModbusStudioUi::getTableView(QModbusDataUnit::RegisterType table) -{ - QWidget *tv = Q_NULLPTR; - if (table == QModbusDataUnit::Coils) { - tv = ui->server_registers_->widget(0); - } else if (table == QModbusDataUnit::DiscreteInputs) { - tv = ui->server_registers_->widget(1); - } else if (table == QModbusDataUnit::InputRegisters) { - tv = ui->server_registers_->widget(2); - } else if (table == QModbusDataUnit::HoldingRegisters) { - tv = ui->server_registers_->widget(3); - } else { - tv = ui->server_registers_->widget(3); - qWarning() << "Get table view failed: unknow register type!"; - } - - return qobject_cast(tv); -} - -QList xToolsModbusStudioUi::getTableValues(QTableView *tableView, int row, int count) -{ - if (!tableView) { - qWarning() << "Table view can not be null!"; - return QList(); - } - - auto *model = qobject_cast(tableView->model()); - if (!model) { - qWarning() << "Model can not be null!"; - return QList(); - } - - QList values; - for (int i = row; i < count; i++) { - QStandardItem *item = model->item(i, 1); - if (item) { - QString text = item->text(); - values.append(text.toInt(Q_NULLPTR, 16)); - } else { - values.append(0); - } - } - - return values; -} - -void xToolsModbusStudioUi::outputModbusReply(QModbusReply *reply, int functionCode) -{ - if (reply->error() != QModbusDevice::NoError) { - outputMessage(reply->errorString(), true, "", "error"); - QMessageBox::warning(this, tr("Error occured"), reply->errorString()); - return; - } - - int server_address = reply->serverAddress(); - if (reply->type() == QModbusReply::ReplyType::Raw) { - QByteArray data = reply->rawResult().data(); - QString info = QString("(from address: %1, " - "function code: %2), " - "data unit: %3") - .arg(server_address) - .arg(functionCode) - .arg(QString::fromLatin1(xToolsByteArrayToHex(data, ' '))); - outputMessage(info, false, RXCOLOR, RXFLAG); - } else if (reply->type() == QModbusReply::ReplyType::Common) { - QString info = ui->function_code_->currentText(); - outputMessage(info, false, RXCOLOR, RXFLAG); - } -} - -void xToolsModbusStudioUi::outputMessage(const QString &msg, - bool isError, - const QString &color, - const QString &flag) -{ - QString cookedMsg = QDateTime::currentDateTime().toString("hh:mm:ss.zzz"); - cookedMsg = QString("%1 ").arg(cookedMsg); - - QString cookedColor = color; - if (cookedColor.isEmpty()) { - if (isError) { - cookedColor = "red"; - } else { - cookedColor = "black"; - } - } - - cookedMsg += flag.isEmpty() ? "" - : QString("[%2] ").arg(cookedColor, flag); - cookedMsg += msg; - ui->text_browser_->append(cookedMsg); -} - -bool xToolsModbusStudioUi::isConnected() -{ - if (xToolsModbusStudio::Instance()->IsConnected(m_modbusDevice)) { - return true; - } - - QMessageBox::warning(this, - tr("Device is not Ready"), - tr("The modbus device is not ready, " - "please check settings and try again later!")); - return false; -} - -bool xToolsModbusStudioUi::writeSettingsArray( - const QString &group, const QString &key, const QString &value, int index, int maxIndex) -{ - m_settings->beginWriteArray(group); - for (int i = 0; i < maxIndex; i++) { - m_settings->setArrayIndex(i); - QString v = m_settings->value(key).toString(); - if (v == value) { - m_settings->endArray(); - return false; - } - } - - m_settings->setArrayIndex(index); - m_settings->setValue(key, value); - m_settings->endArray(); - return true; -} diff --git a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.h b/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.h deleted file mode 100644 index b10e5931..00000000 --- a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.h +++ /dev/null @@ -1,134 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ui { -class xToolsModbusStudioUi; -} - -struct xToolsModbusUiSettingKeys; -class xToolsModbusStudioUi : public QWidget -{ - Q_OBJECT -public: - explicit xToolsModbusStudioUi(QWidget *parent = Q_NULLPTR); - ~xToolsModbusStudioUi(); - -signals: - void deviceChanged(QModbusDevice *device); - -private: - Ui::xToolsModbusStudioUi *ui; - QModbusDevice *m_modbusDevice{Q_NULLPTR}; - QSettings *m_settings{Q_NULLPTR}; - QStandardItemModel *m_registerModel{Q_NULLPTR}; - xToolsModbusUiSettingKeys *m_keyCtx; - -private: - void initComponents(); - void initComponentDevices(); - void initComponentAddress(); - void initComponentPortName(); - void initComponnetBaudRate(); - void initComponnetDataBits(); - void initComponnetStopBits(); - void initComponnetParity(); - void initComponentFunctionCode(); - void initComponentRegisterTableView(); - void initComponentInput(); - void initComponentRegisterTabWidget(); - - void initSettings(); - void initSettingsDevice(); - void initSettingsNetwork(); - void initSettingsSerialPort(); - void initSettingsClient(); - void initSettingsServer(); - void initSettingsClientOperations(); - void initSettingsInput(); - - void initSignals(); - void initSignalsDevice(); - void initSignalsNetworking(); - void initSignalsSerialPort(); - void initSignalsClient(); - void initSignalsServer(); - void initSignalsClientOperations(); - - void onErrorOccurred(); - void onDeviceTypeChanged(); - void onCloseClicked(); - void onOpenClicked(); - void onAddressChanged(); - void onPortChanged(); - void onCustomAddressChanged(); - void onPortNameChanged(); - void onParityChanged(); - void onBaudRateChanged(); - void onDataBitsChanged(); - void onStopBistChanged(); - void onInvokeRefresh(); - void onClientTimeoutChanged(); - void onClientRepeatTimeChanged(); - void onServerIsBusyChanged(); - void onServerJustListenChanged(); - void onServerAddressChanged(); - void onFunctionCodeChanged(); - void onTargetAddressChanged(); - void onStartAddressChanged(); - void onAddressNumberChanged(); - - void onReadClicked(); - void onWriteClicked(); - void onSendClicked(); - - void onDateWritten(QModbusDataUnit::RegisterType table, int address, int size); - void onItemChanged(QStandardItem *item); - -private: - QModbusDevice *CreateModbusDevice(); - QTableView *CreateTableView(int rowCount, QTableView *tableView); - - void updateUiState(bool connected); - void updateClientTableView(); - void updateClientTableViewData(const QList &values); - void updateClientReadWriteButtonState(); - void updateClientParameters(); - void updateClientTableViewAddress(QTableView *view, int startAddress); - void updateServerParameters(); - bool updateServerMap(QModbusDevice *server); - void updateServerRegistersData(); - - quint8 getClientFunctionCode(); - QList getClientRegisterValue(); - QByteArray getClientPdu(); - QTableView *getTableView(QModbusDataUnit::RegisterType table); - QList getTableValues(QTableView *tableView, int row, int count); - - void outputModbusReply(QModbusReply *reply, int functionCode); - void outputMessage(const QString &msg, - bool isError, - const QString &color = QString(), - const QString &flag = QString()); - bool isConnected(); - bool writeSettingsArray( - const QString &group, const QString &key, const QString &value, int index, int maxIndex); -}; diff --git a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.ui b/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.ui deleted file mode 100644 index b1f3522a..00000000 --- a/Source/ModbusStudio/ModbusStudioUI/xToolsModbusStudioUi.ui +++ /dev/null @@ -1,773 +0,0 @@ - - - xToolsModbusStudioUi - - - - 0 - 0 - 1022 - 795 - - - - - 0 - 0 - - - - Modbus Studio - - - - - - - 200 - 0 - - - - - 0 - - - 0 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - true - true - - - - Device operations - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - CloseDevice - - - - - - - OpenDevice - - - - - - - - - - - - - 0 - 0 - - - - Device list - - - - - - - Qt::Horizontal - - - - - - - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - true - - - - - - - - true - true - - - - Network settings - - - - - - - - 0 - 0 - - - - Port - - - - - - - 65535 - - - - - - - - 0 - 0 - - - - Address - - - - - - - Qt::Horizontal - - - - - - - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - true - true - - - - Serial port settings - - - - - - - - 0 - 0 - - - - Port name - - - - - - - - 0 - 0 - - - - Baud rate - - - - - - - - - - - - - - 0 - 0 - - - - Data bits - - - - - - - - - - - - - - 0 - 0 - - - - Parity - - - - - - - - 0 - 0 - - - - Stop bits - - - - - - - true - - - - - - - Qt::Horizontal - - - - - - - - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - 265 - - - - - - - Device busy - - - - - - - Server address - - - - - - - - true - true - - - - Server parameters - - - - - - - Listen only mode - - - - - - - Qt::Horizontal - - - - - - - - - - - 0 - 200 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - 0 - - - 3 - - - - - - - - 0 - 0 - - - - 255 - - - - - - - - 0 - 0 - - - - Repeat times - - - - - - - - 0 - 0 - - - - Timeout - - - - - - - - 0 - 0 - - - - Function code - - - - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - - - - - 0 - 0 - - - - 1 - - - 128 - - - - - - - 500 - - - 10000 - - - 100 - - - 500 - - - - - - - - 0 - 0 - - - - 65535 - - - - - - - - 0 - 0 - - - - Target address - - - - - - - - 0 - 0 - - - - Start address - - - - - - - Qt::Horizontal - - - - - - - - 0 - 0 - - - - Address number - - - - - - - - - Read - - - - - - - Write - - - - - - - - - Qt::Horizontal - - - - - - - - true - true - - - - Client parameters - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - Colsole - - - - - - - - - - - - - 16777215 - 16777215 - - - - Client registers - - - - - - - - - - - - Custom command - - - - - - Protocol data unit - - - - - - - - 0 - 0 - - - - true - - - - - - - Send - - - - - - - - - - - 0 - 250 - - - - - 16777215 - 16777215 - - - - Server registers - - - - - - -1 - - - - - - - - - - - - - diff --git a/Source/ModbusStudio/main.cpp b/Source/ModbusStudio/main.cpp deleted file mode 100644 index 84172e8b..00000000 --- a/Source/ModbusStudio/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsModbusStudioUi.h" -#include "xToolsUi.h" - -int main(int argc, char* argv[]) -{ - const QString appName = QObject::tr("Modbus Studio"); - return xToolsExec(argc, argv, appName); -} diff --git a/Source/Tools/Tools/xToolsBleCentralTool.cpp b/Source/Tools/Tools/xToolsBleCentralTool.cpp deleted file mode 100644 index a8a92974..00000000 --- a/Source/Tools/Tools/xToolsBleCentralTool.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsBleCentralTool.h" - -#include -#include - -#define BLE_ERR_SIG QLowEnergyController::Error - -xToolsBleCentralTool::xToolsBleCentralTool(QObject *parent) - : xToolsCommunicationTool(parent) -{} - -xToolsBleCentralTool::~xToolsBleCentralTool() {} - -QString xToolsBleCentralTool::serviceName(QVariant service) -{ - QObject *obj = service.value(); - auto cookedService = qobject_cast(obj); - if (cookedService) { - return cookedService->serviceName(); - } else { - qWarning() << "invalid valud of service, not a object!"; - } - - return "Invalid"; -} - -QVariantList xToolsBleCentralTool::characteristics(QVariant service) -{ - QVariantList list; - if (service.canConvert()) { - return list; - } - auto cookedService = service.value(); - if (cookedService) { - auto characteristics = cookedService->characteristics(); - for (auto &characteristic : characteristics) { - list.append(QVariant::fromValue(characteristic)); - } - } - return list; -} - -QString xToolsBleCentralTool::characteristicName(QVariant characteristic) -{ - if (characteristic.canConvert()) { - auto c = characteristic.value(); - return c.name(); - } - - return "Invalid"; -} - -void xToolsBleCentralTool::readCharacteristic() -{ - if (!(m_serviceIndex >= 0 && m_serviceIndex < m_services.length())) { - qWarning() << "invalid service index"; - return; - } - - auto service = m_services.at(m_serviceIndex); - auto chs = service->characteristics(); - if (!(m_characteristicIndex >= 0 && m_characteristicIndex < chs.count())) { - qWarning() << "invalid characteristic index"; - return; - } - - auto c = chs.at(m_characteristicIndex); - service->readCharacteristic(c); -} - -void xToolsBleCentralTool::changeNotify() -{ - if (!((m_serviceIndex >= 0) && (m_serviceIndex < m_services.length()))) { - return; - } - - auto service = m_services.at(m_serviceIndex); - auto characteristics = service->characteristics(); - if (!((m_characteristicIndex >= 0) && (m_characteristicIndex < characteristics.length()))) { - return; - } - - auto characteristic = characteristics.at(m_characteristicIndex); - auto descriptors = characteristic.descriptors(); - typedef QBluetoothUuid::DescriptorType SAKDescriptorType; - auto type = SAKDescriptorType::ClientCharacteristicConfiguration; - for (auto &descriptor : descriptors) { - auto value = descriptor.value(); - if (descriptor.type() != type) { - continue; - } - - if (value == QByteArray::fromHex("0100")) { - QByteArray value = QByteArray::fromHex("0000"); - service->writeDescriptor(descriptor, value); - qWarning() << "disable notify"; - } else { - QByteArray value = QByteArray::fromHex("0100"); - service->writeDescriptor(descriptor, value); - qWarning() << "enable notify"; - } - } -} - -bool xToolsBleCentralTool::hasFlag(QVariant characteristic, int flag) -{ - auto ch = characteristic.value(); - auto properties = ch.properties(); - if (properties & flag) { - return true; - } - - return false; -} - -bool xToolsBleCentralTool::isNotified(QVariant characteristic) -{ - auto cookedCh = characteristic.value(); - auto desList = cookedCh.descriptors(); - bool notified = false; - for (auto &des : desList) { - if (des.value() == QByteArray::fromHex("0100")) { - notified = true; - break; - } - } - - return notified; -} - -bool xToolsBleCentralTool::initialize(QString &errStr) -{ - if (!m_bluetoothDeviceInfo.isValid()) { - errStr = "invalid ble information."; - return false; - } - - m_services.clear(); - mBleCentral = QLowEnergyController::createCentral(m_bluetoothDeviceInfo); - connect(mBleCentral, - &QLowEnergyController::serviceDiscovered, - mBleCentral, - [=](const QBluetoothUuid &newService) { onServiceDiscovered(newService); }); - connect(mBleCentral, &QLowEnergyController::discoveryFinished, mBleCentral, [=]() { - onServiceDiscoveryFinished(); - }); - connect(mBleCentral, - &QLowEnergyController::errorOccurred, - mBleCentral, - [=](QLowEnergyController::Error err) { onBleCentralErrorOccuured(err); }); - connect(mBleCentral, &QLowEnergyController::connected, mBleCentral, [=]() { - onBleCentralConnected(); - }); - connect(mBleCentral, &QLowEnergyController::disconnected, mBleCentral, [=]() { - onBleCentralDisconnected(); - }); - - mBleCentral->connectToDevice(); - emit serviceDiscoveryStarted(); - return true; -} - -void xToolsBleCentralTool::readBytes() -{ - if (!((m_serviceIndex >= 0) && (m_serviceIndex < m_services.length()))) { - return; - } - - auto service = m_services.at(m_serviceIndex); - auto characteristics = service->characteristics(); - auto characteristic = characteristics.at(m_characteristicIndex); - service->readCharacteristic(characteristic); -} - -void xToolsBleCentralTool::writeBytes(const QByteArray &bytes) -{ - if (!((m_serviceIndex >= 0) && (m_serviceIndex < m_services.length()))) { - qWarning() << "invalid parameters."; - return; - } - - auto service = m_services.at(m_serviceIndex); - auto characteristics = service->characteristics(); - auto characteristic = characteristics.at(m_characteristicIndex); - if (m_writeModel == 0) { - if (!hasFlag(QVariant::fromValue(characteristic), QLowEnergyCharacteristic::Write)) { - QString str = "QLowEnergyService::WriteWithResponse"; - qWarning() << "unsupported write model: " + str; - return; - } - - qInfo() << "try to write bytes:" << QString::fromLatin1(bytes.toHex()); - service->writeCharacteristic(characteristic, bytes); - } else { - if (!hasFlag(QVariant::fromValue(characteristic), - QLowEnergyCharacteristic::WriteNoResponse)) { - QString str = "QLowEnergyService::WriteWithoutResponse"; - qWarning() << "unsupported write model: " + str; - return; - } - - qInfo() << "try to write bytes without response:" - << QString::fromLatin1(bytes.toHex()); - auto opt = QLowEnergyService::WriteWithoutResponse; - service->writeCharacteristic(characteristic, bytes, opt); - } -} - -void xToolsBleCentralTool::uninitialize() -{ - mBleCentral->disconnectFromDevice(); - mBleCentral->deleteLater(); - mBleCentral = nullptr; -} - -void xToolsBleCentralTool::onServiceDiscovered(const QBluetoothUuid &newService) -{ - qInfo() << "new ble service discovered:" + newService.toString(); -} - -void xToolsBleCentralTool::onServiceDiscoveryFinished() -{ - qInfo() << "ble service discovery finished."; - QList uuids = mBleCentral->services(); - qInfo() << "service count:" + QString::number(uuids.length()); - - for (auto &uuid : uuids) { - auto service = mBleCentral->createServiceObject(uuid); - if (!service) { - continue; - } - - connect(service, - &QLowEnergyService::characteristicChanged, - service, - [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { - emit outputBytes(value); - emit bytesRead(value, info.name()); - }); - connect(service, - &QLowEnergyService::characteristicRead, - service, - [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { - emit outputBytes(value); - emit bytesRead(value, info.name()); - }); - connect(service, - &QLowEnergyService::characteristicWritten, - service, - [=](const QLowEnergyCharacteristic &info, const QByteArray &value) { - emit bytesWritten(value, info.name()); - }); - connect(service, - &QLowEnergyService::stateChanged, - service, - [=](QLowEnergyService::ServiceState newState) { - onServiceObjectStateChanged(service, newState); - }); - connect(service, - &QLowEnergyService::descriptorWritten, - this, - &xToolsBleCentralTool::descriptorWritten); - - m_services.append(service); - service->discoverDetails(); - } - - emit serviceDiscoveryFinished(); -} - -void xToolsBleCentralTool::onBleCentralErrorOccuured(QLowEnergyController::Error err) -{ - if (err == QLowEnergyController::UnknownError) { - return; - } - - qWarning() << "new ble service error:" + mBleCentral->errorString(); - exit(); -} - -void xToolsBleCentralTool::onBleCentralConnected() -{ - qWarning() << "connect to device successfully."; - mBleCentral->discoverServices(); -} - -void xToolsBleCentralTool::onBleCentralDisconnected() -{ - QString msg = "disconnect from device"; - qWarning() << msg; - emit errorOccurred(msg); -} - -void xToolsBleCentralTool::onServiceObjectStateChanged(QLowEnergyService *service, - QLowEnergyService::ServiceState newState) -{ - Q_UNUSED(service); - auto state = QLowEnergyService::RemoteServiceDiscovered; - if (newState == state) { - qInfo() << "Remote service discovered:" << newState; - } -} - -QVariant xToolsBleCentralTool::info() -{ - return QVariant::fromValue(m_bluetoothDeviceInfo); -} - -void xToolsBleCentralTool::setInfo(QVariant info) -{ - m_bluetoothDeviceInfo = info.value(); - emit infoChanged(); -} - -QVariantList xToolsBleCentralTool::services() -{ - QVariantList varList; - for (auto &var : m_services) { - varList.append(QVariant::fromValue(var)); - } - return varList; -} - -int xToolsBleCentralTool::serviceIndex() -{ - return m_serviceIndex; -} - -void xToolsBleCentralTool::setServiceIndex(int index) -{ - m_serviceIndex = index; - emit serviceIndexChanged(); -} - -int xToolsBleCentralTool::characteristicIndex() -{ - return m_characteristicIndex; -} - -void xToolsBleCentralTool::setCharacteristicIndex(int index) -{ - m_characteristicIndex = index; - emit characteristicIndexChanged(); -} - -int xToolsBleCentralTool::writeModel() -{ - return m_writeModel; -} - -void xToolsBleCentralTool::setWriteModel(int model) -{ - m_writeModel = model; - emit writeModelChanged(); -} diff --git a/Source/Tools/Tools/xToolsBleCentralTool.h b/Source/Tools/Tools/xToolsBleCentralTool.h deleted file mode 100644 index b2d7d996..00000000 --- a/Source/Tools/Tools/xToolsBleCentralTool.h +++ /dev/null @@ -1,90 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include - -#include "xToolsCommunicationTool.h" - -class xToolsBleCentralTool : public xToolsCommunicationTool -{ - Q_OBJECT - // clang-format off - Q_PROPERTY(QVariant info READ info WRITE setInfo NOTIFY infoChanged) - Q_PROPERTY(QVariantList services READ services NOTIFY servicesChanged) - Q_PROPERTY(int serviceIndex READ serviceIndex WRITE setServiceIndex NOTIFY serviceIndexChanged) - Q_PROPERTY(int characteristicIndex READ characteristicIndex WRITE setCharacteristicIndex NOTIFY characteristicIndexChanged) - Q_PROPERTY(int writeModel READ writeModel WRITE setWriteModel NOTIFY writeModelChanged) - // clang-format on -public: - xToolsBleCentralTool(QObject *parent = nullptr); - ~xToolsBleCentralTool(); - -public: - Q_INVOKABLE QString serviceName(QVariant service); - Q_INVOKABLE QVariantList characteristics(QVariant service); - Q_INVOKABLE QString characteristicName(QVariant characteristic); - Q_INVOKABLE void readCharacteristic(); - Q_INVOKABLE void changeNotify(); - Q_INVOKABLE bool hasFlag(QVariant characteristic, int flag); - Q_INVOKABLE bool isNotified(QVariant characteristic); - -signals: - void descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue); - void serviceDiscoveryStarted(); - void serviceDiscoveryFinished(); - -protected: - bool initialize(QString &errStr) override; - void writeBytes(const QByteArray &bytes) override; - void readBytes(); - void uninitialize() override; - -private: - QLowEnergyController *mBleCentral{nullptr}; - -private: - void onServiceDiscovered(const QBluetoothUuid &newService); - void onServiceDiscoveryFinished(); - void onBleCentralErrorOccuured(QLowEnergyController::Error err); - void onBleCentralConnected(); - void onBleCentralDisconnected(); - void onServiceObjectStateChanged(QLowEnergyService *service, - QLowEnergyService::ServiceState newState); - -public: - Q_INVOKABLE QVariant info(); - Q_INVOKABLE void setInfo(QVariant info); - Q_INVOKABLE QVariantList services(); - Q_INVOKABLE int serviceIndex(); - Q_INVOKABLE void setServiceIndex(int index); - Q_INVOKABLE int characteristicIndex(); - Q_INVOKABLE void setCharacteristicIndex(int index); - Q_INVOKABLE int writeModel(); - Q_INVOKABLE void setWriteModel(int model); - -signals: - void infoChanged(); - void servicesChanged(); - void serviceIndexChanged(); - void characteristicsChanged(); - void characteristicIndexChanged(); - void writeModelChanged(); - -private: - QBluetoothDeviceInfo m_bluetoothDeviceInfo; - QVector m_services; - int m_serviceIndex{-1}; - int m_characteristicIndex{-1}; - int m_writeModel; -}; diff --git a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.cpp b/Source/Tools/ToolsUI/xToolsBleCentralToolUi.cpp deleted file mode 100644 index 7263cb5e..00000000 --- a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include "xToolsBleCentralToolUi.h" -#include "ui_xToolsBleCentralToolUi.h" - -#include -#include -#include -#include -#include -#include - -#include "xToolsLineEdit.h" -#include "xToolsSpinBox.h" - -xToolsBleCentralToolUi::xToolsBleCentralToolUi(QWidget* parent) - : xToolsCommunicationToolUi{parent} - , ui(new Ui::xToolsBleCentralToolUi) - , mBleTool(Q_NULLPTR) -{ - ui->setupUi(this); - ui->progressBar->hide(); - connect(ui->pushButtonScan, - &QPushButton::clicked, - this, - &xToolsBleCentralToolUi::onPushButtonScanClicked); - connect(ui->comboBoxDevices, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsBleCentralToolUi::onComboBoxDevicesActived); - connect(ui->comboBoxServices, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsBleCentralToolUi::onComboBoxServicesCurrentIndexChanged); - connect(ui->comboBoxCharacteristics, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsBleCentralToolUi::onComboBoxCharacteristicsActived); - connect(ui->comboBoxWriteWay, - static_cast(&QComboBox::currentIndexChanged), - this, - &xToolsBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged); - connect(ui->pushButtonNotify, - &QPushButton::clicked, - this, - &xToolsBleCentralToolUi::onPushButtonNotifyClicked); - connect(ui->pushButtonRead, - &QPushButton::clicked, - this, - &xToolsBleCentralToolUi::onPushButtonReadClicked); - connect(ui->comboBoxDevices, &xToolsBleDeviceInfoComboBox::finished, this, [=]() { - ui->pushButtonScan->setText(tr("Scan")); - ui->pushButtonScan->setEnabled(true); - }); - connect(ui->comboBoxDevices, &xToolsBleDeviceInfoComboBox::started, this, [=]() { - ui->pushButtonScan->setText(tr("Stop")); - ui->pushButtonScan->setEnabled(true); - }); - - ui->labelWriteWay->setVisible(false); - ui->comboBoxWriteWay->setVisible(false); - ui->pushButtonNotify->setVisible(false); - ui->pushButtonRead->setVisible(false); - ui->labelUnsupported->setVisible(false); - ui->labelUnsupported->setStyleSheet("QLabel{color:red}"); -} - -xToolsBleCentralToolUi::~xToolsBleCentralToolUi() -{ - delete ui; -} - -void xToolsBleCentralToolUi::onBaseToolUiInitialized(xToolsBaseTool* tool, - const QString& settingsGroup) -{ - xToolsCommunicationToolUi::onBaseToolUiInitialized(tool, settingsGroup); - - mBleTool = qobject_cast(mTool); - if (!mBleTool) { - QByteArray msg("invalid SAKBleCentralTool tool"); - qWarning() << QString::fromLatin1(msg); - Q_ASSERT_X(false, __FUNCTION__, msg.data()); - return; - } - - onComboBoxWriteWayCurrentIndexChanged(); - connect(mBleTool, - &xToolsBleCentralTool::descriptorWritten, - this, - &xToolsBleCentralToolUi::onDescriptorWritten); - - initSettingsMenu(settingsGroup); -} - -void xToolsBleCentralToolUi::onIsWorkingChanged(bool isWorking) -{ - if (!isWorking) { - ui->progressBar->hide(); - } -} - -void xToolsBleCentralToolUi::initSettingsMenu(const QString& settingsGroup) -{ - QWidget* w = new QWidget(this); - QGridLayout* gl = new QGridLayout(); - w->setLayout(gl); - - int rowIndex = 0; - gl->addWidget(new QLabel(tr("Timeout interval(S)"), w), rowIndex, 0, 1, 1); - xToolsSpinBox* sp = new xToolsSpinBox(w); - sp->setMinimum(10); - sp->setMaximum(120); - sp->setValue(120); - sp->setGroupKey(settingsGroup, "timeoutInterval"); - gl->addWidget(sp, rowIndex, 1, 1, 1); - connect(sp, QOverload::of(&QSpinBox::valueChanged), this, [=](int v) { - ui->comboBoxDevices->setTimeoutInterval(v); - }); - - rowIndex += 1; - gl->addWidget(new QLabel(tr("Name filtter"), w), rowIndex, 0, 1, 1); - xToolsLineEdit* le = new xToolsLineEdit(w); - le->setGroupKey(settingsGroup, "nameFiltter"); - gl->addWidget(le, rowIndex, 1, 1, 1); - connect(le, &xToolsLineEdit::textChanged, this, [=](const QString& text) { - ui->comboBoxDevices->setNameFiltter(text); - }); - - rowIndex += 1; - QMenu* menu = new QMenu(this); - QPushButton* bt = new QPushButton(tr("OK")); - connect(bt, &QPushButton::clicked, menu, &QMenu::close); - gl->addWidget(bt, rowIndex, 1, 1, 1); - - QWidgetAction* a = new QWidgetAction(this); - a->setDefaultWidget(w); - - menu->addAction(a); - ui->pushButtonSettings->setMenu(menu); - - connect(mBleTool, - &xToolsBleCentralTool::serviceDiscoveryStarted, - this, - &xToolsBleCentralToolUi::onServiceDiscoveryStarted); - connect(mBleTool, - &xToolsBleCentralTool::serviceDiscoveryFinished, - this, - &xToolsBleCentralToolUi::onServiceDiscoveryFinished); - - int timeoutInterval = sp->value(); - QString nameFiltter = le->text().trimmed(); - ui->comboBoxDevices->setTimeoutInterval(timeoutInterval); - ui->comboBoxDevices->setNameFiltter(nameFiltter); - - onComboBoxDevicesActived(); -} - -void xToolsBleCentralToolUi::onServiceDiscoveryStarted() -{ - ui->progressBar->show(); -} - -void xToolsBleCentralToolUi::onServiceDiscoveryFinished() -{ - ui->comboBoxServices->clear(); - auto services = mBleTool->services(); - for (auto& service : services) { - auto cookedSerivce = service.value(); - ui->comboBoxServices->addItem(cookedSerivce->serviceName(), service); - connect(cookedSerivce, - &QLowEnergyService::stateChanged, - this, - [=](QLowEnergyService::ServiceState state) { - if (state == QLowEnergyService::RemoteServiceDiscovered) { - onComboBoxServicesCurrentIndexChanged(); - } - }); - } - ui->progressBar->hide(); -} - -void xToolsBleCentralToolUi::onDescriptorWritten(const QLowEnergyDescriptor& descriptor, - const QByteArray& newValue) -{ - Q_UNUSED(descriptor) - Q_UNUSED(newValue) - onComboBoxCharacteristicsActived(); -} - -void xToolsBleCentralToolUi::onPushButtonScanClicked() -{ - ui->pushButtonScan->setEnabled(false); - if (ui->comboBoxDevices->isActive()) { - ui->comboBoxDevices->stopDiscover(); - } else { - ui->comboBoxDevices->startDiscover(); - } -} - -void xToolsBleCentralToolUi::onComboBoxDevicesActived() -{ - QVariant data = ui->comboBoxDevices->currentData(); - mBleTool->setInfo(data); -} - -void xToolsBleCentralToolUi::onComboBoxServicesCurrentIndexChanged() -{ - mBleTool->setServiceIndex(ui->comboBoxServices->currentIndex()); - auto service = ui->comboBoxServices->currentData(); - auto cookedSerivce = service.value(); - auto chs = cookedSerivce->characteristics(); - ui->comboBoxCharacteristics->clear(); - for (int i = 0; i < chs.count(); i++) { - auto ch = chs.at(i); - QVariant var = QVariant::fromValue(ch); - QString name = ch.name(); - name = name.isEmpty() ? tr("Characteristics%1").arg(i + 1) : name; - ui->comboBoxCharacteristics->addItem(name, var); - } -} - -void xToolsBleCentralToolUi::onComboBoxCharacteristicsActived() -{ - int index = ui->comboBoxCharacteristics->currentIndex(); - mBleTool->setCharacteristicIndex(index); - - QVariant ch = ui->comboBoxCharacteristics->currentData(); - bool writeFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Write); - int writeNoResponse = QLowEnergyCharacteristic::WriteNoResponse; - bool writeNoResponseFlag = mBleTool->hasFlag(ch, writeNoResponse); - ui->labelWriteWay->setVisible(writeFlag); - ui->comboBoxWriteWay->setVisible(writeNoResponseFlag); - - bool readFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Read); - bool notifyFlag = mBleTool->hasFlag(ch, QLowEnergyCharacteristic::Notify); - ui->pushButtonNotify->setVisible(notifyFlag); - ui->pushButtonRead->setVisible(readFlag); - bool supported = writeFlag || writeNoResponseFlag || readFlag || notifyFlag; - ui->labelUnsupported->setVisible(!supported); - - if (notifyFlag) { - bool isNotified = mBleTool->isNotified(ch); - QString txt = isNotified ? tr("Disnotify") : tr("Notify"); - ui->pushButtonNotify->setText(txt); - } -} - -void xToolsBleCentralToolUi::onComboBoxWriteWayCurrentIndexChanged() -{ - int index = ui->comboBoxWriteWay->currentIndex(); - mBleTool->setWriteModel(index); - qInfo() << "set write model to:" << index; -} - -void xToolsBleCentralToolUi::onPushButtonNotifyClicked() -{ - mBleTool->changeNotify(); -} - -void xToolsBleCentralToolUi::onPushButtonReadClicked() -{ - mBleTool->readCharacteristic(); -} diff --git a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.h b/Source/Tools/ToolsUI/xToolsBleCentralToolUi.h deleted file mode 100644 index e7797906..00000000 --- a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.h +++ /dev/null @@ -1,50 +0,0 @@ -/*************************************************************************************************** - * Copyright 2023-2024 x-tools-author(x-tools@outlook.com). All rights reserved. - * - * The file is encoded using "utf8 with bom", it is a part of xTools project. - * - * xTools is licensed according to the terms in the file LICENCE(GPL V3) in the root of the source - * code directory. - **************************************************************************************************/ -#include - -#include "xToolsBleCentralTool.h" -#include "xToolsCommunicationToolUi.h" - -namespace Ui { -class xToolsBleCentralToolUi; -} -class xToolsBleCentralToolUi : public xToolsCommunicationToolUi -{ - Q_OBJECT -public: - explicit xToolsBleCentralToolUi(QWidget *parent = nullptr); - ~xToolsBleCentralToolUi(); - -protected: - virtual void onBaseToolUiInitialized(xToolsBaseTool *tool, - const QString &settingsGroup) override; - - virtual void onIsWorkingChanged(bool isWorking) final; - -private: - Ui::xToolsBleCentralToolUi *ui{nullptr}; - xToolsBleCentralTool *mBleTool; - const QLoggingCategory mLoggingCategory{"sak.blecentraltoolui"}; - -private: - void initSettingsMenu(const QString &settingsGroup); - -private slots: - void onServiceDiscoveryStarted(); - void onServiceDiscoveryFinished(); - void onDescriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue); - - void onPushButtonScanClicked(); - void onComboBoxDevicesActived(); - void onComboBoxServicesCurrentIndexChanged(); - void onComboBoxCharacteristicsActived(); - void onComboBoxWriteWayCurrentIndexChanged(); - void onPushButtonNotifyClicked(); - void onPushButtonReadClicked(); -}; diff --git a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.ui b/Source/Tools/ToolsUI/xToolsBleCentralToolUi.ui deleted file mode 100644 index a9d54087..00000000 --- a/Source/Tools/ToolsUI/xToolsBleCentralToolUi.ui +++ /dev/null @@ -1,185 +0,0 @@ - - - xToolsBleCentralToolUi - - - - 0 - 0 - 256 - 256 - - - - Form - - - - 0 - - - 0 - - - 0 - - - 9 - - - - - - 0 - 0 - - - - Service - - - - - - - - 0 - 0 - - - - Devices - - - - - - - - 0 - 0 - - - - Write way - - - - - - - - - - - - Notify - - - - - - - Read - - - - - - - - - Qt::Horizontal - - - - - - - - - - - 0 - 0 - - - - - - - - 0 - - - -1 - - - - - - - - WriteWithResponse - - - - - WriteWithoutResponse - - - - - - - - - 0 - 0 - - - - Characteristic - - - - - - - - - Settings - - - - - - - Scan - - - - - - - - - (Unsupported characteristic) - - - Qt::AlignCenter - - - - - - - - xToolsBleDeviceInfoComboBox - QComboBox -
xToolsBleDeviceInfoComboBox.h
-
-
- - -