feat:煤量分布功能实现

This commit is contained in:
徐超 2024-11-04 18:11:55 +08:00
parent 8e78e7c4ef
commit 49deef1231
16 changed files with 2362 additions and 27 deletions

View File

@ -4,8 +4,9 @@
# #
#------------------------------------------------- #-------------------------------------------------
QT += core gui \ QT += core gui
charts QT += charts
QT += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = HX_CoalFlowDetect TARGET = HX_CoalFlowDetect
@ -25,6 +26,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11 CONFIG += c++11
SOURCES += \ SOURCES += \
controller/coaldistributmodbusthread.cpp \
main.cpp \ main.cpp \
mainwindow.cpp \ mainwindow.cpp \
view/beltspeedlinewidget.cpp \ view/beltspeedlinewidget.cpp \
@ -36,6 +38,7 @@ SOURCES += \
component/ZDateEdit/ztimeedit.cpp\ component/ZDateEdit/ztimeedit.cpp\
HEADERS += \ HEADERS += \
controller/coaldistributmodbusthread.h \
mainwindow.h \ mainwindow.h \
view/beltspeedlinewidget.h \ view/beltspeedlinewidget.h \
view/coaldistributbarchartwidget.h \ view/coaldistributbarchartwidget.h \

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,215 @@
#ifndef DATECOMMONINFO_H
#define DATECOMMONINFO_H
#include <QDateTimeEdit>
#include <QLabel>
#include <QObject>
#include <QPushButton>
QT_BEGIN_NAMESPACE
class QPushButton;
class QComboBox;
class QGroupBox;
class QLineEdit;
class QDate;
class QGridLayout;
class QHBoxLayout;
class QVBoxLayout;
class Event;
class DataBase;
QT_END_NAMESPACE
typedef enum {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Week
} E_WEEK;
typedef enum {
PREV_MONTH_DAY, // 上月剩余天数
NEXT_MONTH_DAY, // 下个月的天数
CURR_MONTH_DAY, // 当月天数
WEEKEND_DAY, // 周末
SELECT_DAY, // 选中的天
CURRENT_DAY, // 当天
} E_DAY;
//#define LC_STR QString::fromLocal8Bit
#define LC_STR QStringLiteral
class DateCommonInfo : public QObject {
Q_OBJECT
public:
explicit DateCommonInfo(QObject* parent = 0);
signals:
public slots:
public:
static quint16 getSpringFestivalDate(int year);
static int getFirstDayOfWeek(int year, int month);
static int getTotalMonthDays(int year, int month);
static int getMonthDays(int year, int month);
static bool isLoopYaer(int year);
static QString getLunarDate(int year, int month, int day);
static QString getLunarMonAndDay(int year, int month, int day);
// 计算今年是什么年如 :甲子年
static QString getLunarTime(int year);
private:
static QString holiday(int month, int day);
static QString solarTerms(int year, int month, int day);
static QString lunarFestival(int month, int day);
};
class DayLabel : public QLabel {
Q_OBJECT
public:
explicit DayLabel(QWidget* parent = 0);
bool getBSelect() const;
void setSelected(bool value);
void setColor(int type);
void showDay(int nDay, QString strLunar);
signals:
void signalClicked(int ntype, int day);
private:
QLabel* labelIcon;
int m_nDay;
bool m_bHover;
bool m_bSelect;
QString m_strText;
protected:
void enterEvent(QEvent* e);
void leaveEvent(QEvent* e);
void mousePressEvent(QMouseEvent* e);
void mouseDoubleClickEvent(QMouseEvent* e);
void paintEvent(QPaintEvent* e);
};
class CalendarWidget : public QWidget {
Q_OBJECT
public:
explicit CalendarWidget(QString fromat, QWidget* parent = 0, Qt::WindowFlags f = Qt::WindowFlags());
~CalendarWidget();
int year() const;
void setYear(int year);
int month() const;
void setMonth(int month);
int day() const;
void setDay(int day);
int hour() const;
void setHour(int h);
int minute();
void setMinute(int m);
int second();
void setSecond(int s);
void jumpToDateTime(const QDateTime& dt);
void setDateTimeRange(const QDateTime& min, const QDateTime& max);
void dateTimeRange(QDateTime& min, QDateTime& max);
void setDisplayFormat(const QString& format);
signals:
void dayClicked(const QDateTime&);
void selectDayChanged(const QDateTime&);
private:
QString m_fromat;
QVBoxLayout* verLayoutCalendar;
QWidget* m_base;
QWidget* widgetTitle;
QComboBox* comboBox_Year;
QComboBox* comboBox_Month;
QWidget* widgetWeek;
QLabel* labelWeek[Week];
QHBoxLayout* horLayoutWeek;
QWidget* widgetBody;
DayLabel* labelDay[42];
QGridLayout* gridLayoutBody;
QWidget* widgetRight;
QLabel* labelShowToday;
QLabel* labelShowWeek;
QLabel* labelShowDay;
QLabel* labelShowNYear;
QLabel* labelShowLunarDate;
QLabel* labelSpacer;
QLabel* labelScheduleTitle;
QLabel* labelSchedule;
QWidget* widget_bottom;
QComboBox* comboBox_Hour;
QComboBox* comboBox_min;
QComboBox* comboBox_sec;
QLabel* label_splite;
QLabel* label_splite2;
QPushButton* pushBtn_Rtn;
QPushButton* pushBtn_Now;
QPushButton* pushBtn_Ok;
QVBoxLayout* verlayoutWidgetRight;
QHBoxLayout* horLayoutGlobal;
private:
int m_nYear;
int m_nMonth;
int m_nDay;
int m_nHour;
int m_nMin;
int m_nSec;
QDateTime m_maxDt;
QDateTime m_minDt;
DayLabel* m_pCrtSelect;
private:
void initWidget();
void initSize();
void initDate();
void initStyleSheet();
void UpdateYear();
DayLabel* getDayLabel(int y, int m, int d);
void changeCurrentSelectDay();
protected:
//virtual void paintEvent(QPaintEvent* e);
private slots:
void sltDayClicked(int type, int day);
void sltShowPrevMonth();
void sltShowNextMonth();
void sltComboBoxDateChange(int);
void sltComboBoxTimeChange(int);
void slotPushBtnRtn();
void slotPushBtnNow();
void slotPushBtnOk();
};
#endif // DATE_H

View File

@ -0,0 +1,66 @@
#include "zdateedit.h"
#include "QWidgetAction"
#include "dateCommonInfo.h"
#include <QFile>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMenu>
ZDateEdit::ZDateEdit(QWidget* parent)
: QDateEdit(parent)
{
m_popupButton = new QPushButton();
m_popupButton->setObjectName("popupButton");
//m_popupButton->setText("+");
//m_popupButton->setCursor(Qt::ArrowCursor);
QHBoxLayout* layout = new QHBoxLayout();
m_popupButton->setCursor(QCursor(Qt::PointingHandCursor));
layout->addStretch();
layout->addWidget(m_popupButton);
layout->setContentsMargins(0, 0, 20, 0);
this->setLayout(layout);
QFile file(":/component/ZDateEdit/qss/zDateTimeEdit.qss");
if (file.open(QFile::ReadOnly)) {
QString qss = file.readAll();
setStyleSheet(qss);
file.close();
}
m_pCldrWgt = new CalendarWidget(displayFormat(), this, QMenu().windowFlags() | Qt::FramelessWindowHint);
m_dateTime = QDateTime::currentDateTime();
setDateTime(m_dateTime);
connect(m_popupButton, &QAbstractButton::clicked, this, &ZDateEdit::showCalendarWidget);
connect(m_pCldrWgt, &CalendarWidget::dayClicked, this, &ZDateEdit::slotDayClicked);
QString tmp = displayFormat();
}
ZDateEdit::~ZDateEdit()
{
if (m_pCldrWgt) {
delete m_pCldrWgt;
}
}
void ZDateEdit::showCalendarWidget()
{
QPoint pt(-17, height() - 10);
pt = mapToGlobal(pt);
m_pCldrWgt->jumpToDateTime(m_dateTime);
m_pCldrWgt->move(pt);
m_pCldrWgt->show();
}
void ZDateEdit::slotDayClicked(const QDateTime& dt)
{
m_dateTime = dt;
setDateTime(dt);
}
void ZDateEdit::setDisplayFormat(const QString& format)
{
m_pCldrWgt->setDisplayFormat(format);
QDateTimeEdit::setDisplayFormat(format);
}

View File

@ -0,0 +1,49 @@
#ifndef ZDATEEDIT_H
#define ZDATEEDIT_H
#include <QWidget>
#include <QDateEdit>
#include <QPushButton>
#include <QLabel>
QT_BEGIN_NAMESPACE
class QPushButton;
class QComboBox;
class QGroupBox;
class QLineEdit;
class QDate;
class QGridLayout;
class QHBoxLayout;
class QVBoxLayout;
class Event;
class DataBase;
QT_END_NAMESPACE
class DayLabel;
class CalendarWidget;
class ZDateEdit : public QDateEdit
{
Q_OBJECT
public:
explicit ZDateEdit(QWidget *parent = nullptr);
~ZDateEdit();
void setDisplayFormat(const QString &format);
private:
QPushButton *m_popupButton=nullptr;
CalendarWidget* m_pCldrWgt;
QDateTime m_dateTime;
QString m_strFormat;
public slots:
void showCalendarWidget();
protected slots:
void slotDayClicked(const QDateTime & dt);
};
#endif // ZDATEEDIT_H

View File

@ -0,0 +1,66 @@
#include "zdatetimeedit.h"
#include "QWidgetAction"
#include "dateCommonInfo.h"
#include <QFile>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMenu>
ZDateTimeEdit::ZDateTimeEdit(QWidget* parent)
: QDateTimeEdit(parent)
{
m_popupButton = new QPushButton();
m_popupButton->setObjectName("popupButton");
//m_popupButton->setText("+");
//m_popupButton->setCursor(Qt::ArrowCursor);
QHBoxLayout* layout = new QHBoxLayout();
m_popupButton->setCursor(QCursor(Qt::PointingHandCursor));
layout->addStretch();
layout->addWidget(m_popupButton);
layout->setContentsMargins(0, 0, 2, 0);
this->setLayout(layout);
QFile file(":/component/ZDateEdit/qss/zDateTimeEdit.qss");
if (file.open(QFile::ReadOnly)) {
QString qss = file.readAll();
setStyleSheet(qss);
file.close();
}
m_pCldrWgt = new CalendarWidget(displayFormat(), this, QMenu().windowFlags() | Qt::FramelessWindowHint);
m_dateTime = QDateTime::currentDateTime();
setDateTime(m_dateTime);
connect(m_popupButton, &QAbstractButton::clicked, this, &ZDateTimeEdit::showCalendarWidget);
connect(m_pCldrWgt, &CalendarWidget::dayClicked, this, &ZDateTimeEdit::slotDayClicked);
QString tmp = displayFormat();
}
ZDateTimeEdit::~ZDateTimeEdit()
{
if (m_pCldrWgt) {
delete m_pCldrWgt;
}
}
void ZDateTimeEdit::showCalendarWidget()
{
QPoint pt(0, height() + 5);
pt = mapToGlobal(pt);
m_pCldrWgt->jumpToDateTime(m_dateTime);
m_pCldrWgt->move(pt);
m_pCldrWgt->show();
}
void ZDateTimeEdit::slotDayClicked(const QDateTime& dt)
{
m_dateTime = dt;
setDateTime(dt);
}
void ZDateTimeEdit::setDisplayFormat(const QString& format)
{
m_pCldrWgt->setDisplayFormat(format);
QDateTimeEdit::setDisplayFormat(format);
}

View File

@ -0,0 +1,59 @@
#ifndef ZDATETIMEEDIT_H
#define ZDATETIMEEDIT_H
#include <QWidget>
#include <QDateTimeEdit>
#include <QPushButton>
#include <QLabel>
QT_BEGIN_NAMESPACE
class QPushButton;
class QComboBox;
class QGroupBox;
class QLineEdit;
class QDate;
class QGridLayout;
class QHBoxLayout;
class QVBoxLayout;
class Event;
class DataBase;
QT_END_NAMESPACE
class DayLabel;
class CalendarWidget;
class ZDateTimeEdit : public QDateTimeEdit
{
Q_OBJECT
public:
explicit ZDateTimeEdit(QWidget *parent = 0);
~ZDateTimeEdit();
void setDisplayFormat(const QString &format);
private:
QPushButton *m_popupButton=nullptr;
CalendarWidget* m_pCldrWgt;
QDateTime m_dateTime;
QString m_strFormat;
public slots:
void showCalendarWidget();
protected slots:
void slotDayClicked(const QDateTime & dt);
};
#endif // ZDATETIMEEDIT_H

View File

@ -0,0 +1,66 @@
#include "ztimeedit.h"
#include "QWidgetAction"
#include "dateCommonInfo.h"
#include <QFile>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMenu>
ZTimeEdit::ZTimeEdit(QWidget* parent)
: QTimeEdit(parent)
{
m_popupButton = new QPushButton();
m_popupButton->setObjectName("popupButton");
//m_popupButton->setText("+");
//m_popupButton->setCursor(Qt::ArrowCursor);
QHBoxLayout* layout = new QHBoxLayout();
m_popupButton->setCursor(QCursor(Qt::PointingHandCursor));
layout->addStretch();
layout->addWidget(m_popupButton);
layout->setContentsMargins(0, 0, 20, 0);
this->setLayout(layout);
QFile file(":/component/ZDateEdit/qss/zDateTimeEdit.qss");
if (file.open(QFile::ReadOnly)) {
QString qss = file.readAll();
setStyleSheet(qss);
file.close();
}
m_pCldrWgt = new CalendarWidget(displayFormat(), this, QMenu().windowFlags() | Qt::FramelessWindowHint);
m_dateTime = QDateTime::currentDateTime();
setDateTime(m_dateTime);
connect(m_popupButton, &QAbstractButton::clicked, this, &ZTimeEdit::showCalendarWidget);
connect(m_pCldrWgt, &CalendarWidget::dayClicked, this, &ZTimeEdit::slotDayClicked);
QString tmp = displayFormat();
}
ZTimeEdit::~ZTimeEdit()
{
if (m_pCldrWgt) {
delete m_pCldrWgt;
}
}
void ZTimeEdit::showCalendarWidget()
{
QPoint pt(-17, height() - 10);
pt = mapToGlobal(pt);
m_pCldrWgt->jumpToDateTime(m_dateTime);
m_pCldrWgt->move(pt);
m_pCldrWgt->show();
}
void ZTimeEdit::slotDayClicked(const QDateTime& dt)
{
m_dateTime = dt;
setDateTime(dt);
}
void ZTimeEdit::setDisplayFormat(const QString& format)
{
m_pCldrWgt->setDisplayFormat(format);
QDateTimeEdit::setDisplayFormat(format);
}

View File

@ -0,0 +1,48 @@
#ifndef ZTIMEEDIT_H
#define ZTIMEEDIT_H
#include <QWidget>
#include <QTimeEdit>
#include <QPushButton>
#include <QLabel>
QT_BEGIN_NAMESPACE
class QPushButton;
class QComboBox;
class QGroupBox;
class QLineEdit;
class QDate;
class QGridLayout;
class QHBoxLayout;
class QVBoxLayout;
class Event;
class DataBase;
QT_END_NAMESPACE
class DayLabel;
class CalendarWidget;
class ZTimeEdit : public QTimeEdit
{
Q_OBJECT
public:
explicit ZTimeEdit(QWidget *parent = nullptr);
~ZTimeEdit();
void setDisplayFormat(const QString &format);
private:
QPushButton *m_popupButton=nullptr;
CalendarWidget* m_pCldrWgt;
QDateTime m_dateTime;
QString m_strFormat;
public slots:
void showCalendarWidget();
protected slots:
void slotDayClicked(const QDateTime & dt);
};
#endif // ZTIMEEDIT_H

View File

@ -0,0 +1,7 @@
#include "coaldistributmodbusthread.h"
CoalDistributModbusThread::CoalDistributModbusThread(const QString& host, quint16 port)
: m_hostIP(host)
, m_port(port)
{
}

View File

@ -0,0 +1,16 @@
#ifndef COALDISTRIBUTMODBUSTHREAD_H
#define COALDISTRIBUTMODBUSTHREAD_H
#include <QObject>
class CoalDistributModbusThread {
public:
CoalDistributModbusThread(const QString& host, quint16 port);
private:
private:
QString m_hostIP;
quint16 m_port;
};
#endif // COALDISTRIBUTMODBUSTHREAD_H

View File

@ -1,6 +1,7 @@
#include "beltspeedlinewidget.h" #include "beltspeedlinewidget.h"
#include <QDateTimeAxis> #include <QDateTimeAxis>
#include <QRandomGenerator>
#include <QVBoxLayout> #include <QVBoxLayout>
BeltSpeedLineWidget::BeltSpeedLineWidget(QWidget* parent) BeltSpeedLineWidget::BeltSpeedLineWidget(QWidget* parent)
@ -22,6 +23,7 @@ void BeltSpeedLineWidget::initLineChart()
m_chart = new QChart(); m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent); m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0)); m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
// 创建折线系列 // 创建折线系列
m_series = new QLineSeries(); m_series = new QLineSeries();
@ -32,11 +34,24 @@ void BeltSpeedLineWidget::initLineChart()
m_chart->addSeries(m_series); m_chart->addSeries(m_series);
m_chart->createDefaultAxes(); m_chart->createDefaultAxes();
// 假设数据点,替换为你的实时数据 // TODO:假设数据点,替换为你的实时数据
QDateTime currentTime = QDateTime::currentDateTime(); QDateTime currentTime = QDateTime::currentDateTime();
QRandomGenerator* generator = QRandomGenerator::global();
double previousSpeed = 10.0; // 初始速度值在中间
for (int i = 0; i < 120; ++i) { // 120个数据点代表最近两个小时 for (int i = 0; i < 120; ++i) { // 120个数据点代表最近两个小时
double speed = qrand() % 21; // 生成0到20之间的随机速度 // 根据前一个速度值生成新的速度值保持在5到15之间
double fluctuation = generator->generateDouble() * 2.0 - 1.0; // 生成 -1.0 到 1.0 之间的浮动 // 小范围波动
double speed = previousSpeed + fluctuation;
// 确保速度在5到15之间
if (speed < 5.0) {
speed = 5.0;
} else if (speed > 15.0) {
speed = 15.0;
}
m_series->append(currentTime.addSecs(-i * 60).toMSecsSinceEpoch(), speed); m_series->append(currentTime.addSecs(-i * 60).toMSecsSinceEpoch(), speed);
previousSpeed = speed; // 更新前一个速度值
} }
// 创建并设置X轴为日期时间轴 // 创建并设置X轴为日期时间轴

View File

@ -4,6 +4,7 @@
#include <QList> #include <QList>
#include <QRandomGenerator> #include <QRandomGenerator>
#include <QScopedPointer> #include <QScopedPointer>
#include <QTcpSocket>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QtCharts/QChart> #include <QtCharts/QChart>
@ -11,6 +12,7 @@
#include <QBarSet> #include <QBarSet>
#include <QChart> #include <QChart>
#include <QChartView> #include <QChartView>
#include <QColor>
#include <QDateTimeAxis> #include <QDateTimeAxis>
#include <QTimer> #include <QTimer>
#include <QVBoxLayout> #include <QVBoxLayout>
@ -19,22 +21,37 @@
CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget* parent) CoalDistributBarChartWidget::CoalDistributBarChartWidget(QWidget* parent)
: QWidget(parent) : QWidget(parent)
, m_tcpSocket(new QTcpSocket(this))
{ {
initializeChart(); initializeChart();
// setupTimer(); connectTCPSocket();
setupTimer();
}
CoalDistributBarChartWidget::~CoalDistributBarChartWidget()
{
if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
m_tcpSocket->disconnectFromHost();
m_tcpSocket->waitForDisconnected();
}
delete m_tcpSocket;
} }
void CoalDistributBarChartWidget::updateChart() void CoalDistributBarChartWidget::updateChart()
{ {
double newValue = QRandomGenerator::global()->bounded(0, 99); // 随机生成0-900的Y值 int radio = getCoalRatioByTCPSocket();
if (radio < 0 && radio > 100) {
return;
}
// 更新当前柱子的值 int setCount = m_set->count();
QBarSet* currentBarSet = static_cast<QBarSet*>(m_series->barSets().at(currentIndex));
currentBarSet->replace(0, newValue); // 更新当前柱子的值
// 循环更新下一个柱子的索引 qDebug() << "setCount" << setCount;
currentIndex = (currentIndex + 1) % m_series->count(); // 循环到下一个柱子
m_set->remove(setCount - 1);
m_set->insert(0, radio);
} }
void CoalDistributBarChartWidget::initializeChart() void CoalDistributBarChartWidget::initializeChart()
@ -44,6 +61,7 @@ void CoalDistributBarChartWidget::initializeChart()
m_chart->setBackgroundBrush(Qt::transparent); m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0)); m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
// 创建窗口并设置图表 // 创建窗口并设置图表
m_chartView = new QChartView(m_chart); m_chartView = new QChartView(m_chart);
@ -56,14 +74,7 @@ void CoalDistributBarChartWidget::initializeChart()
m_series = new QBarSeries(); m_series = new QBarSeries();
m_chart->addSeries(m_series); m_chart->addSeries(m_series);
// 创建300个柱状集 // 设置X轴为据煤溜摄像机距离
// for (int i = 0; i < 300; ++i) {
// QBarSet* barSet = new QBarSet(QString::number(i)); // 使用柱子编号作为名称
// barSet->append(0); // 初始化值为0
// m_series->append(barSet);
// }
// 设置X轴为时间
QValueAxis* axisX = new QValueAxis; QValueAxis* axisX = new QValueAxis;
axisX->setRange(1, 300); axisX->setRange(1, 300);
axisX->setTickCount(10); axisX->setTickCount(10);
@ -81,12 +92,21 @@ void CoalDistributBarChartWidget::initializeChart()
axisY->setLinePen(QPen(Qt::gray)); axisY->setLinePen(QPen(Qt::gray));
axisY->setLabelsColor(Qt::gray); // 设置标签字体颜色为灰色 axisY->setLabelsColor(Qt::gray); // 设置标签字体颜色为灰色
axisY->setRange(0, 100); axisY->setRange(0, 100);
axisY->setTitleFont(QFont("Arial", 10)); // 设置标题字体
axisY->setTitleVisible(true); // 确保标题可见
m_chart->addAxis(axisY, Qt::AlignLeft); m_chart->addAxis(axisY, Qt::AlignLeft);
m_series->attachAxis(axisY); m_series->attachAxis(axisY);
// 设置Y轴标题位置 // 初始化默认数据集
axisY->setTitleFont(QFont("Arial", 10)); // 设置标题字体 m_set = new QBarSet("测试1");
axisY->setTitleVisible(true); // 确保标题可见 m_set->setColor(QColor(95, 180, 255));
m_set->setBorderColor(QColor(95, 180, 255));
QRandomGenerator* generator = QRandomGenerator::global();
for (int i = 0; i < 300; i++) {
int randomNumber = generator->bounded(10, 51);
*m_set << randomNumber;
}
m_series->append(m_set);
QVBoxLayout* layout = new QVBoxLayout(this); QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0); layout->setContentsMargins(0, 0, 0, 0);
@ -102,3 +122,129 @@ void CoalDistributBarChartWidget::setupTimer()
connect(m_timer, &QTimer::timeout, this, &CoalDistributBarChartWidget::updateChart); connect(m_timer, &QTimer::timeout, this, &CoalDistributBarChartWidget::updateChart);
m_timer->start(1000); // 每秒更新一次 m_timer->start(1000); // 每秒更新一次
} }
void CoalDistributBarChartWidget::connectTCPSocket()
{
QString ipAddress = "192.168.80.101"; // 替换为实际 IP 地址
quint16 port = 3000; // Modbus TCP 端口
// 连接到 Modbus TCP 服务器
m_tcpSocket->connectToHost(ipAddress, port);
if (!m_tcpSocket->waitForConnected(5000)) {
qDebug() << "连接失败:" << m_tcpSocket->errorString();
}
}
int CoalDistributBarChartWidget::getCoalRatioByTCPSocket()
{
if (m_tcpSocket->state() != QAbstractSocket::ConnectedState) {
qDebug() << "未连接到服务器";
return -1; // 返回错误值
}
// 构建 Modbus 请求
const quint8 unitId = 1; // 单元 ID
const quint8 functionCode = 0x03; // 读保持寄存器
const quint16 startAddress = 699; // 寄存器地址
const quint16 registerCount = 1; // 读取寄存器数量
// 构建请求数据
QByteArray request;
QDataStream stream(&request, QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序
// 添加 Modbus 请求报文各部分
stream << static_cast<quint16>(0x0004); // 事务 ID
stream << static_cast<quint16>(0x0000); // 协议 ID
stream << static_cast<quint16>(0x0006); // 剩余长度
stream << unitId; // 单元 ID
stream << functionCode; // 功能码
stream << static_cast<quint16>(startAddress); // 寄存器地址700 = 0x01BB
stream << registerCount; // 寄存器数量
// 发送请求
m_tcpSocket->write(request);
if (!m_tcpSocket->waitForBytesWritten(5000)) {
qDebug() << "写入请求失败:" << m_tcpSocket->errorString();
return -1; // 返回错误值
}
// 等待响应
if (!m_tcpSocket->waitForReadyRead(5000)) {
qDebug() << "没有收到响应:" << m_tcpSocket->errorString();
return -1; // 返回错误值
}
// 读取响应数据
QByteArray response = m_tcpSocket->readAll();
if (response.size() < 9) {
qDebug() << "响应数据不完整";
return -1; // 返回错误值
}
qDebug() << "response" << response.toHex();
// 解析响应
QDataStream responseStream(response);
responseStream.setByteOrder(QDataStream::LittleEndian);
quint16 responseTransactionId;
responseStream >> responseTransactionId; // 事务 ID
quint16 responseProtocolId;
responseStream >> responseProtocolId; // 协议 ID
quint16 responseLength;
responseStream >> responseLength; // 剩余长度
quint8 responseUnitId;
responseStream >> responseUnitId; // 单元 ID
quint8 responseFunctionCode;
responseStream >> responseFunctionCode; // 功能码
quint8 byteCount;
responseStream >> byteCount; // 字节计数
// 检查功能码和字节计数
if (responseFunctionCode != functionCode || byteCount != 2) {
qDebug() << "功能码或字节计数不匹配";
return -1; // 返回错误值
}
// 获取并输出最后四个字节
if (response.size() < 2) {
qDebug() << "响应数据少于四个字节,无法获取最后四位";
}
QByteArray lastFourBytes = response.right(2); // 获取最后2个字节
bool isOk;
int decimalValue = lastFourBytes.toHex().toInt(&isOk, 16);
qDebug() << "最后四位:" << decimalValue;
return decimalValue; // 返回煤量占比
}
QByteArray CoalDistributBarChartWidget::createModbusTcpRequest()
{
QByteArray request;
QDataStream stream(&request, QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::BigEndian); // 使用大端字节序
// 构建 Modbus TCP 请求
quint16 transactionId = 0x0004; // 事务 ID
quint16 protocolId = 0x0000; // 协议 ID
quint16 length = 0x0006; // 剩余长度
quint8 unitId = 0x01; // 单元 ID
quint8 functionCode = 0x03; // 功能码
quint8 byteCount = 0x02; // 字节计数
quint16 registerAddress = 0x01BB; // 寄存器地址 700
quint16 registerCount = 0x0001; // 寄存器数量
// 写入数据
stream << transactionId;
stream << protocolId;
stream << length;
stream << unitId;
stream << functionCode;
stream << byteCount;
stream << registerAddress;
stream << registerCount;
return request; // 返回生成的请求报文
}

View File

@ -7,6 +7,8 @@
#include <QWidget> #include <QWidget>
#include <QDateTimeAxis> #include <QDateTimeAxis>
#include <QNetworkProxy>
#include <QTcpSocket>
#include <QtCharts/QBarSeries> #include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet> #include <QtCharts/QBarSet>
#include <QtCharts/QCategoryAxis> #include <QtCharts/QCategoryAxis>
@ -19,6 +21,7 @@ class CoalDistributBarChartWidget : public QWidget {
Q_OBJECT Q_OBJECT
public: public:
explicit CoalDistributBarChartWidget(QWidget* parent = nullptr); explicit CoalDistributBarChartWidget(QWidget* parent = nullptr);
~CoalDistributBarChartWidget();
private slots: private slots:
void updateChart(); void updateChart();
@ -28,6 +31,23 @@ private:
void setupTimer(); void setupTimer();
/**
* @brief connectTCPSocket TCP服务
*/
void connectTCPSocket();
/**
* @brief getCoalRatioByTCPSocket通过TCP协议获取煤量占比
* @return
*/
int getCoalRatioByTCPSocket();
/**
* @brief createModbusTcpRequest ModbusTCP报文
* @return
*/
QByteArray createModbusTcpRequest();
private: private:
QChart* m_chart; QChart* m_chart;
QChartView* m_chartView; QChartView* m_chartView;
@ -36,15 +56,15 @@ private:
QDateTimeAxis* m_axisX; QDateTimeAxis* m_axisX;
QBarSet* m_set;
int currentIndex; // 当前更新的柱子的索引 int currentIndex; // 当前更新的柱子的索引
static const int MaxDataPoints = 300; // 最大数据点数5分钟每秒1条 static const int MaxDataPoints = 300; // 最大数据点数5分钟每秒1条
QBarSet* m_set;
// QList<QString> m_timeLabels;
QList<QDateTime> m_timeLabels; // 存储时间标签
QList<double> m_values; // 存储比例值
// QList<QDateTime> timestamps; // 存储时间戳 QList<QDateTime> m_timeLabels; // 存储时间标签
QTcpSocket* m_tcpSocket;
}; };
#endif // COALDISTRIBUTBARCHARTWIDGET_H #endif // COALDISTRIBUTBARCHARTWIDGET_H

View File

@ -1,6 +1,14 @@
#include "coalstatisticschartwidget.h" #include "coalstatisticschartwidget.h"
#include "ui_coalstatisticschartwidget.h" #include "ui_coalstatisticschartwidget.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent) CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent)
: QWidget(parent) : QWidget(parent)
, ui(new Ui::CoalStatisticsChartWidget) , ui(new Ui::CoalStatisticsChartWidget)
@ -8,6 +16,8 @@ CoalStatisticsChartWidget::CoalStatisticsChartWidget(QWidget* parent)
ui->setupUi(this); ui->setupUi(this);
initCoalStatisticsBarChart(); initCoalStatisticsBarChart();
getCoalStatisInfoByHttpRequest("2024-09-01 08", "2024-09-02 08");
} }
CoalStatisticsChartWidget::~CoalStatisticsChartWidget() CoalStatisticsChartWidget::~CoalStatisticsChartWidget()
@ -21,6 +31,7 @@ void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
m_chart = new QChart(); m_chart = new QChart();
m_chart->setBackgroundBrush(Qt::transparent); m_chart->setBackgroundBrush(Qt::transparent);
m_chart->setMargins(QMargins(0, 0, 0, 0)); m_chart->setMargins(QMargins(0, 0, 0, 0));
m_chart->legend()->hide();
// 创建图表视图并设置 // 创建图表视图并设置
m_chartView = new QChartView(m_chart); m_chartView = new QChartView(m_chart);
@ -75,3 +86,46 @@ void CoalStatisticsChartWidget::initCoalStatisticsBarChart()
layout->addWidget(m_chartView); layout->addWidget(m_chartView);
} }
} }
void CoalStatisticsChartWidget::getCoalStatisInfoByHttpRequest(const QString& beginTime, const QString& endTime)
{
QNetworkAccessManager* manager = new QNetworkAccessManager();
// URL
QUrl url("http://192.168.5.205:5002/api/get/coal/statistics/value/");
QNetworkRequest request(url);
// Form data
QUrlQuery params;
params.addQueryItem("begin_time", beginTime);
params.addQueryItem("end_time", endTime);
// 设置请求头
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
// 发送 POST 请求
QNetworkReply* reply = manager->post(request, params.query(QUrl::FullyEncoded).toUtf8());
// 连接信号和槽
QObject::connect(reply, &QNetworkReply::finished, [reply]() {
if (reply->error() == QNetworkReply::NoError) {
// 处理成功的响应
QByteArray responseData = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonObject jsonObj = jsonResponse.object();
int code = jsonObj["code"].toInt();
QString message = jsonObj["message"].toString();
QJsonObject data = jsonObj["data"].toObject();
double totalVolume = data["total_volume"].toDouble();
qDebug() << "Code:" << code;
qDebug() << "Message:" << message;
qDebug() << "Total Volume:" << totalVolume;
} else {
// 处理错误
qDebug() << "Error:" << reply->errorString();
}
reply->deleteLater();
});
}

View File

@ -22,6 +22,11 @@ private:
*/ */
void initCoalStatisticsBarChart(); void initCoalStatisticsBarChart();
/**
* @brief getCoalStatisInfoByHttpRequest通过Http请求获取煤量统计信息
*/
void getCoalStatisInfoByHttpRequest(const QString& startTime, const QString& endTime);
private: private:
Ui::CoalStatisticsChartWidget* ui; Ui::CoalStatisticsChartWidget* ui;