This commit is contained in:
Вячеслав Штейбезандт 2025-03-11 14:58:08 +03:00
parent 9d6c9eb55f
commit ba56f67a1e
5 changed files with 766 additions and 0 deletions

41
LineRingerLib32Bit.pro Normal file
View File

@ -0,0 +1,41 @@
QT -= gui
QT += core gui
QT += widgets serialport
QT += serialbus widgets
requires(qtConfig(combobox))
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TEMPLATE = lib
DEFINES += LINERINGERLIB32BIT_LIBRARY
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
lineringer.cpp
HEADERS += \
LineRingerLib_global.h \
lineringer.h
FORMS += \
lineringer.ui
# Default rules for deployment.
unix {
target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target

12
LineRingerLib_global.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef LINERINGERLIB_GLOBAL_H
#define LINERINGERLIB_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(LINERINGERLIB_LIBRARY)
# define LINERINGERLIB_EXPORT Q_DECL_EXPORT
#else
# define LINERINGERLIB_EXPORT Q_DECL_IMPORT
#endif
#endif // LINERINGERLIB_GLOBAL_H

324
lineringer.cpp Normal file
View File

@ -0,0 +1,324 @@
#include "lineringer.h"
#include "ui_lineringer.h"
QWidget* init(QWidget *parent)
{
return new LineRinger(parent);
}
LineRinger::LineRinger(QWidget *parent) :
QWidget(parent),
ui(new Ui::LineRinger)
{
ui->setupUi(this);
father = parent;
const auto listPorts = QSerialPortInfo::availablePorts();
for (const auto& port: listPorts)
{
ui->comBox->addItem(QString(port.portName() + ": " + port.manufacturer()), QVariant(port.portName()));
}
ui->parityControlBox->addItem("No", QVariant(QSerialPort::NoParity));
ui->parityControlBox->addItem("Even", QVariant(QSerialPort::EvenParity));
ui->parityControlBox->addItem("Odd", QVariant(QSerialPort::OddParity));
ui->parityControlBox->addItem("Space", QVariant(QSerialPort::SpaceParity));
ui->parityControlBox->addItem("Mark", QVariant(QSerialPort::MarkParity));
ui->dataBox->addItem("Data5", QVariant(QSerialPort::Data5));
ui->dataBox->addItem("Data6", QVariant(QSerialPort::Data6));
ui->dataBox->addItem("Data7", QVariant(QSerialPort::Data7));
ui->dataBox->addItem("Data8", QVariant(QSerialPort::Data8));
ui->dataBox->setCurrentIndex(3);
ui->stopBox->addItem("One", QVariant(QSerialPort::OneStop));
ui->stopBox->addItem("OneAndHalf", QVariant(QSerialPort::OneAndHalfStop));
ui->stopBox->addItem("Two", QVariant(QSerialPort::TwoStop));
ui->deviceOnlineView->horizontalHeader()->setVisible(true);
syncColumnHeaders();
ui->deviceOnlineView->setColumnHidden(1, true);
ui->ringButton->setEnabled(false);
modbusDevice = new QModbusRtuSerialMaster(this);
}
LineRinger::~LineRinger()
{
if (modbusDevice->state() == QModbusDevice::ConnectedState)
on_connectButton_clicked();
delete ui;
}
void LineRinger::syncColumnHeaders()
{
QStringList headers;
headers << "ID" << "BaudRate" << "Vendor Name" << "Product Code" << "Major Minor Revision" << "Vendor Url" << "Product Name" << "Model Name" << "User Application Name" << "Примечание";
ui->deviceOnlineView->setHorizontalHeaderLabels(headers);
ui->deviceOnlineView->resizeColumnsToContents();
}
void LineRinger::on_connectButton_clicked()
{
if (!modbusDevice)
return;
if (modbusDevice->state() != QModbusDevice::ConnectedState) {
modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter,
ui->comBox->currentData().toString());
#if QT_CONFIG(modbus_serialport)
modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter,
ui->parityControlBox->currentData().toInt());
modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,
ui->baudRateBox->currentText().toInt(nullptr, 10));
modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,
ui->dataBox->currentData().toInt());
modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,
ui->stopBox->currentData().toInt());
#endif
modbusDevice->setTimeout(50);
modbusDevice->setNumberOfRetries(0);
if (!modbusDevice->connectDevice()) {
QMessageBox::warning(this, "Ошибка", "Произошла ошибка при попытке подключения.");
} else {
ui->connectButton->setText(tr("Отключить"));
ui->ringButton->setEnabled(true);
currentBaudRate = ui->baudRateBox->currentText().toUInt(nullptr, 10);
}
} else {
modbusDevice->disconnectDevice();
ui->connectButton->setText(tr("Подключить"));
ui->ringButton->setEnabled(false);
}
}
LineRinger::callStatus LineRinger::lineCall()
{
QModbusRequest readDeviceBasicIdentification(QModbusRequest::EncapsulatedInterfaceTransport, QByteArray::fromHex("0E0100"));
QModbusRequest readDeviceRegularIdentification(QModbusRequest::EncapsulatedInterfaceTransport, QByteArray::fromHex("0E0200"));
bool isRun = false;
bool *tmp_isRun = &isRun;
uint tmp_adr = 1;
auto bar = new QProgressDialog(this);
connect(bar, &QProgressDialog::canceled, this, [this, tmp_isRun]()
{
*tmp_isRun = true;
});
connect(this, &LineRinger::stopLineCall, this, [this, tmp_isRun]()
{
*tmp_isRun = true;
});
bar->setLabelText(tr("Поиск устройств... Текущий адрес: %1").arg(tmp_adr));
bar->setCancelButton(nullptr);
bar->setRange(1, 247);
bar->setMinimumDuration(100);
for(tmp_adr = 1; tmp_adr<248; tmp_adr++)
{
bar->setValue(tmp_adr);
bar->setLabelText(tr("Поиск устройств... Текущий адрес: %1/247").arg(tmp_adr));
auto *reply = modbusDevice->sendRawRequest(readDeviceBasicIdentification, tmp_adr);
//auto *reply = modbusDevice->sendReadRequest(*_unit, tmp_adr);
//Запрос типа устройства.
if(reply == nullptr)
{
QMessageBox::warning(this, "Ошибка при сканировании.", QString("%1").arg(modbusDevice->errorString()));
bar->close();
bar->deleteLater();
return callStatus::ERROR;
}
while(!reply->isFinished())
{
if(isRun)
{
bar->close();
bar->deleteLater();
return callStatus::INTERRUPT;
}
QCoreApplication::processEvents();
}
if(isRun)
{
bar->close();
bar->deleteLater();
return callStatus::INTERRUPT;
}
else if (!isRun)
{
//Нужна проверка типа устройства
if(reply->error()!=QModbusDevice::TimeoutError)
{
deviceOnLine currentDevice;
currentDevice.adr = tmp_adr;
currentDevice.baudRate = currentBaudRate;
bool regularReplyError = false;
QString regularReplyErrorString;
if(reply->error()==QModbusDevice::NoError)
{
QModbusResponse resp = reply->rawResult();
uint8_t numOfObject = resp.data().at(5);
QByteArray result = resp.data().remove(0, 6);
for(int tmp_obj = 0; tmp_obj < numOfObject; tmp_obj++)
{
uint8_t objectID = result.at(0);
uint8_t lengthOfObject = result.at(1);
if(lengthOfObject>0)
{
currentDevice.fields[objectID].clear();
}
for(int i = 0; i < lengthOfObject; i++)
{
currentDevice.fields[objectID] += QString(result.at(2+i));
}
result.remove(0, lengthOfObject+2);
}
auto *regularReply = modbusDevice->sendRawRequest(readDeviceRegularIdentification, tmp_adr);
if(regularReply == nullptr)
{
QMessageBox::warning(this, "Ошибка при сканировании.", QString("%1: %2").arg(modbusDevice->error()).arg(modbusDevice->errorString()));
bar->close();
bar->deleteLater();
return callStatus::ERROR;
}
while(!regularReply->isFinished())
{
if(isRun)
{
bar->close();
bar->deleteLater();
return callStatus::INTERRUPT;
}
QCoreApplication::processEvents();
}
if(isRun)
{
bar->close();
bar->deleteLater();
return callStatus::INTERRUPT;
}
else if(!isRun)
{
if(regularReply->error()!=QModbusDevice::NoError)
{
// QMessageBox::warning(this, "Ошибка при сканировании.", QString("%1: %2").arg(regularReply->error()).arg(regularReply->errorString()));
// bar->close();
// bar->deleteLater();
// return callStatus::ERROR;
regularReplyError = true;
regularReplyErrorString = QString("%1: %2").arg(regularReply->error()).arg(regularReply->errorString());
}
QModbusResponse regularResp = regularReply->rawResult();
uint8_t numOfRegularObject = regularResp.data().at(5);
QByteArray regularResult = regularResp.data().remove(0, 6);
for(int tmp_obj = 0; tmp_obj < numOfRegularObject; tmp_obj++)
{
uint8_t objectID = regularResult.at(0);
if(objectID > 0x06)
continue;
uint8_t lengthOfObject = regularResult.at(1);
if(lengthOfObject>0)
{
currentDevice.fields[objectID].clear();
}
for (int i = 0; i < lengthOfObject; i++) {
currentDevice.fields[objectID] += QString(regularResult.at(2+i));
}
regularResult.remove(0, lengthOfObject+2);
}
}
}
if(!isRun)
{
devicesList.append(currentDevice);
unsigned newRow = ui->deviceOnlineView->rowCount();
ui->deviceOnlineView->insertRow(newRow);
ui->deviceOnlineView->setItem(newRow, 0, new QTableWidgetItem(QString::number(currentDevice.adr)));
ui->deviceOnlineView->setItem(newRow, 1, new QTableWidgetItem(QString::number(currentDevice.baudRate)));
for (int i = 0; i < 7; i++) {
ui->deviceOnlineView->setItem(newRow, i+2, new QTableWidgetItem(currentDevice.fields[i]));
}
if(reply->error()!=QModbusDevice::NoError)
{
ui->deviceOnlineView->setItem(newRow, 9, new QTableWidgetItem(QString("%1: %2").arg(reply->error()).arg(reply->errorString())));
}
else if(regularReplyError)
{
ui->deviceOnlineView->setItem(newRow, 9, new QTableWidgetItem(regularReplyErrorString));
}
ui->deviceOnlineView->resizeColumnsToContents();
syncColumnHeaders();
}
}
}
}
return callStatus::NOERROR;
}
void LineRinger::on_ringButton_clicked()
{
ui->deviceOnlineView->clear();
devicesList.clear();
syncColumnHeaders();
while(ui->deviceOnlineView->rowCount()!=0)
ui->deviceOnlineView->removeRow(ui->deviceOnlineView->rowCount()-1);
if(isAutoBaud)
{
auto bar = new QProgressDialog(this);
bar->setLabelText(tr("Поиск устройств... Текущая скорость: %1").arg(currentBaudRate));
bar->setRange(0, ui->baudRateBox->count());
bar->setAutoClose(true);
bar->setMinimumDuration(0);
bar->setCancelButton(nullptr);
connect(bar, &QProgressDialog::canceled, this, [this]()
{
emit stopLineCall();
});
bar->setValue(0);
ui->deviceOnlineView->setColumnHidden(1, false);
modbusDevice->disconnectDevice();
for (int i = 0; i < ui->baudRateBox->count(); i++) {
bar->setValue(i+1);
modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,
ui->baudRateBox->itemText(i).toInt(nullptr, 10));
if (!modbusDevice->connectDevice()) {
QMessageBox::warning(this, "Ошибка", "Произошла ошибка при попытке подключения.");
on_connectButton_clicked();
break;
}
currentBaudRate = ui->baudRateBox->itemText(i).toUInt(nullptr, 10);
if(lineCall() == callStatus::INTERRUPT)
{
QMessageBox::warning(this, "Уведомление", QString("Досрочное завершение опроса. Найдено %1 устройств.").arg(devicesList.count()));
modbusDevice->disconnectDevice();
on_connectButton_clicked();
bar->close();
bar->deleteLater();
ui->timer->setTime(QTime::currentTime());
ui->timer->setDate(QDate::currentDate());
return;
}
modbusDevice->disconnectDevice();
}
on_connectButton_clicked();
}
else
{
ui->deviceOnlineView->setColumnHidden(1, true);
if(lineCall() == callStatus::INTERRUPT)
{
QMessageBox::warning(this, "Уведомление", QString("Досрочное завершение опроса. Найдено %1 устройств.").arg(devicesList.count()));
truthSeaker* HeraldOfTrue = new truthSeaker();
QCoreApplication::postEvent(father, HeraldOfTrue);
}
}
ui->timer->setTime(QTime::currentTime());
ui->timer->setDate(QDate::currentDate());
}
void LineRinger::on_checkAutoBaud_stateChanged(int arg1)
{
isAutoBaud = (bool)arg1;
}

77
lineringer.h Normal file
View File

@ -0,0 +1,77 @@
#ifndef LINERINGER_H
#define LINERINGER_H
#include <QWidget>
#include <QModbusTcpClient>
#include <QModbusRtuSerialMaster>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QMessageBox>
#include <QProgressDialog>
extern "C" __declspec(dllexport) QWidget* init(QWidget *parent);
#include <QEvent>
class truthSeaker : public QEvent
{
public:
truthSeaker() : QEvent(QEvent::User) {}
~truthSeaker() {}
private:
};
namespace Ui {
class LineRinger;
}
class LineRinger : public QWidget
{
Q_OBJECT
public:
enum callStatus{
NOERROR = 0,
ERROR = 1,
INTERRUPT = 2
};
explicit LineRinger(QWidget *parent = nullptr);
~LineRinger();
callStatus lineCall();
void emitShowTheTru(QWidget* w);
QWidget* father = nullptr;
signals:
void stopLineCall();
private slots:
void on_connectButton_clicked();
void on_ringButton_clicked();
void on_checkAutoBaud_stateChanged(int arg1);
private:
Ui::LineRinger *ui;
void syncColumnHeaders();
struct deviceOnLine
{
uint8_t adr;
unsigned baudRate;
QString fields[7] = {"Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined"};
};
QVector<deviceOnLine>devicesList;
bool isAutoBaud = false;
unsigned currentBaudRate;
QModbusClient *modbusDevice = nullptr;
};
extern "C" __declspec(dllexport) void linker(LineRinger *w, QWidget*par, void (*lkn)(QWidget*));
#endif // LINERINGER_H

312
lineringer.ui Normal file
View File

@ -0,0 +1,312 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LineRinger</class>
<widget class="QWidget" name="LineRinger">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>939</width>
<height>522</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="2">
<widget class="QGroupBox" name="gridGroupBox_2">
<layout class="QGridLayout" name="cmdLayout">
<item row="4" column="1">
<widget class="QLabel" name="labelTimer">
<property name="text">
<string>Последний опрос:</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QPushButton" name="ringButton">
<property name="text">
<string>Опросить</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QCheckBox" name="checkAutoBaud">
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="text">
<string>Любая скорость</string>
</property>
</widget>
</item>
<item row="4" column="2">
<widget class="QDateTimeEdit" name="timer">
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="buttonSymbols">
<enum>QAbstractSpinBox::NoButtons</enum>
</property>
<property name="keyboardTracking">
<bool>true</bool>
</property>
<property name="currentSection">
<enum>QDateTimeEdit::DaySection</enum>
</property>
<property name="displayFormat">
<string>dd.MM.yyyy HH:mm:ss</string>
</property>
<property name="calendarPopup">
<bool>false</bool>
</property>
<property name="currentSectionIndex">
<number>0</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="0" column="0">
<widget class="QGroupBox" name="controlGroup">
<layout class="QGridLayout" name="controlLaylout">
<item row="0" column="5">
<widget class="QLabel" name="labelStopBit">
<property name="text">
<string>Стоп-биты</string>
</property>
</widget>
</item>
<item row="1" column="8">
<widget class="QPushButton" name="connectButton">
<property name="text">
<string>Подключить</string>
</property>
</widget>
</item>
<item row="0" column="6">
<widget class="QLabel" name="labelEvenControl">
<property name="text">
<string>Чётность</string>
</property>
</widget>
</item>
<item row="1" column="5">
<widget class="QComboBox" name="stopBox"/>
</item>
<item row="1" column="0">
<widget class="QComboBox" name="comBox">
<property name="editable">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="pushButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>21</width>
<height>21</height>
</size>
</property>
<property name="text">
<string>Поиск</string>
</property>
</widget>
</item>
<item row="1" column="6">
<widget class="QComboBox" name="parityControlBox"/>
</item>
<item row="1" column="3">
<widget class="QComboBox" name="baudRateBox">
<property name="editable">
<bool>true</bool>
</property>
<property name="currentText">
<string>9600</string>
</property>
<property name="insertPolicy">
<enum>QComboBox::InsertAtBottom</enum>
</property>
<property name="modelColumn">
<number>0</number>
</property>
<item>
<property name="text">
<string>9600</string>
</property>
</item>
<item>
<property name="text">
<string>14400</string>
</property>
</item>
<item>
<property name="text">
<string>19200</string>
</property>
</item>
<item>
<property name="text">
<string>31250</string>
</property>
</item>
<item>
<property name="text">
<string>38400</string>
</property>
</item>
<item>
<property name="text">
<string>56000</string>
</property>
</item>
<item>
<property name="text">
<string>57600</string>
</property>
</item>
<item>
<property name="text">
<string>115200</string>
</property>
</item>
</widget>
</item>
<item row="1" column="4">
<widget class="QComboBox" name="dataBox"/>
</item>
<item row="0" column="3">
<widget class="QLabel" name="labelBaud">
<property name="text">
<string>Скорость</string>
</property>
</widget>
</item>
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="labelCom">
<property name="text">
<string>Порт</string>
</property>
</widget>
</item>
<item row="0" column="4">
<widget class="QLabel" name="labelDataBit">
<property name="text">
<string>Биты данных</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="0" column="1">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="0" colspan="3">
<widget class="QTableWidget" name="deviceOnlineView">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="textElideMode">
<enum>Qt::ElideMiddle</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="columnCount">
<number>10</number>
</property>
<attribute name="horizontalHeaderVisible">
<bool>false</bool>
</attribute>
<attribute name="horizontalHeaderCascadingSectionResizes">
<bool>false</bool>
</attribute>
<attribute name="verticalHeaderCascadingSectionResizes">
<bool>false</bool>
</attribute>
<attribute name="verticalHeaderShowSortIndicator" stdset="0">
<bool>false</bool>
</attribute>
<attribute name="verticalHeaderStretchLastSection">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string>ID</string>
</property>
</column>
<column>
<property name="text">
<string>BaudRate</string>
</property>
</column>
<column>
<property name="text">
<string>Vendor Name</string>
</property>
</column>
<column>
<property name="text">
<string>Product Code</string>
</property>
</column>
<column>
<property name="text">
<string>Major Minor Revision</string>
</property>
</column>
<column>
<property name="text">
<string>Vendor Url</string>
</property>
</column>
<column>
<property name="text">
<string>Product Name</string>
</property>
</column>
<column>
<property name="text">
<string>Model Name</string>
</property>
</column>
<column>
<property name="text">
<string>User Application Name</string>
</property>
</column>
<column>
<property name="text">
<string>Примечание</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>