mainwindow.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #include "mainwindow.h"
  2. #include <QtCore/qlist.h>
  3. #include <QtCore/qobject.h>
  4. #include <QDebug>
  5. #include <QPushButton>
  6. #include <QWidget>
  7. #include "backendapimanager.h"
  8. #include "global.h"
  9. #include "jobs.h"
  10. #include "loadingWidget.h"
  11. #include "logger.h"
  12. #include "ui_mainwindow.h"
  13. // 定义 ANzI 转义序列来设置颜色
  14. #define ANSI_COLOR_GREEN "\x1B[32m"
  15. #define ANSI_COLOR_RESET "\x1B[0m"
  16. #include <QMessageBox>
  17. #include <exception>
  18. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
  19. try {
  20. this->setWindowFlags(Qt::FramelessWindowHint);
  21. // this->setWindowState(Qt::WindowMaximized); // Maximizes the window
  22. this->setFixedSize(1000, 600);
  23. ui->setupUi(this);
  24. LoadingWidget::init(ui->stackedWidget);
  25. initializeAnimate();
  26. initialMqttService();
  27. pageFactories[ui->btnNew] = new AddressFactory();
  28. pageFactories[ui->btnBlastProject] = new BlastProjectFactory();
  29. pageFactories[ui->btnEquipment] = new EquipmentFactory();
  30. pageFactories[ui->btnDet] = new DetInfoFactory();
  31. pageFactories[ui->btnBlastOper] = new BlastOperationFactory();
  32. pageFactories[ui->btnRecord] = new BlastRecordFactory();
  33. connect(ui->btnToggle, &QPushButton::clicked, this, &MainWindow::onToggleButtonClicked);
  34. for (auto *widget : left_button_station) {
  35. QPushButton *button = qobject_cast<QPushButton *>(widget);
  36. if (button) {
  37. connect(button, &QPushButton::clicked, this,
  38. [this, button] { onButtonClicked(button); });
  39. }
  40. }
  41. initDateTime();
  42. initialBtnSerial();
  43. // initialGPSSerial();
  44. ui->labLat->setText("经度: " + lat);
  45. ui->labLon->setText("维度: " + lon);
  46. connect(ui->btnClose, &QPushButton::clicked, this, &MainWindow::close);
  47. connect(this, &MainWindow::projectTitleChanged, this, &MainWindow::updateProjectTitleLabel);
  48. } catch (const std::exception &ex) {
  49. Logger::getInstance().error(QString("Application crashed: %1").arg(ex.what()));
  50. QMessageBox::critical(this, "Error", QString("Application crashed: %1").arg(ex.what()));
  51. throw; // rethrow to allow further handling if needed
  52. } catch (...) {
  53. Logger::getInstance().error("Application crashed: Unknown exception");
  54. QMessageBox::critical(this, "Error", "Application crashed: Unknown exception");
  55. throw;
  56. }
  57. }
  58. void MainWindow::updateProjectTitleLabel(const QString &newTitle) {
  59. ui->projectTitleLable->setText(newTitle);
  60. }
  61. void MainWindow::setProjectTitle(const QString &newTitle) {
  62. if (m_currentProjectTitle != newTitle) {
  63. m_currentProjectTitle = newTitle;
  64. // Emit the signal to notify listeners (like our QLabel slot)
  65. emit projectTitleChanged(m_currentProjectTitle);
  66. }
  67. }
  68. void MainWindow::initializeAnimate() {
  69. move(200, 200);
  70. animate_leftFrame = new QPropertyAnimation(ui->leftFrame, "minimumWidth");
  71. animate_leftFrame->setDuration(300);
  72. for (QObject *child : ui->left_buttonsBox->children()) {
  73. if (qobject_cast<QWidget *>(child)) {
  74. left_button_station.append(qobject_cast<QWidget *>(child));
  75. }
  76. }
  77. }
  78. void MainWindow::onToggleButtonClicked() {
  79. // 执行动画
  80. JOBS ::btn_animation(ui->leftFrame, animate_leftFrame);
  81. for (QWidget *b : left_button_station) {
  82. b->setProperty("spread", !b->property("spread").toBool());
  83. b->setStyleSheet(b->styleSheet());
  84. }
  85. }
  86. // 选中按钮
  87. void MainWindow::onButtonClicked(QPushButton *button) {
  88. setStyleSheets(static_cast<QPushButton *>(button));
  89. switchPage(static_cast<QPushButton *>(button));
  90. }
  91. void MainWindow::switchPage(QWidget *button) {
  92. LoadingWidget::showLoading(this, "请稍等");
  93. if (pageFactories.contains(button)) {
  94. PageFactory *factory = pageFactories[button];
  95. if (createdPageByButton.contains(button)) {
  96. QWidget *existingPage = createdPageByButton[button];
  97. existingPage->hide();
  98. ui->stackedWidget->removeWidget(existingPage);
  99. createdPageByButton.remove(button);
  100. }
  101. QWidget *newPage = factory->createPage(this);
  102. ui->stackedWidget->addWidget(newPage);
  103. ui->stackedWidget->setCurrentWidget(newPage);
  104. setProjectTitle(qobject_cast<QPushButton *>(button)->text());
  105. createdPageByButton.insert(button, newPage);
  106. int pageCount = ui->stackedWidget->count();
  107. }
  108. LoadingWidget::hideLoading();
  109. }
  110. void MainWindow::initialMqttService() {
  111. Logger::getInstance().info("Start init Mqtt server.");
  112. MqttClient *pcMqttInit = MqttClient::getInstance();
  113. // "hxgc/topic"
  114. QStringList topics = {MQTT_TOPIC_CAMPANY_PROJECTS};
  115. pcMqttInit->connectToMqttBroker("114.55.233.194", 1883, "hxgc", "hxgc123456", mqttClientId,
  116. topics);
  117. connect(pcMqttInit, &MqttClient::proMessageReceived, this,
  118. &MainWindow::handleMqttProjectsMessage);
  119. Logger::getInstance().info("Connect Mqtt server request sent.");
  120. }
  121. void MainWindow::handleMqttProjectsMessage(const QByteArray &message, const QMqttTopicName &topic) {
  122. QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
  123. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  124. QJsonObject jsonObj = jsonDoc.object();
  125. if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
  126. QJsonValue uuidValue = jsonObj["uuid"];
  127. QJsonValue statusValue = jsonObj["status"];
  128. if (statusValue.isString() &&
  129. statusValue.toString() == BlastStatus::Created) { // "1" 未注册
  130. if (uuidValue.isNull()) {
  131. qDebug() << "uuid 的值为 null";
  132. } else {
  133. QString uuid = uuidValue.toString();
  134. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  135. dao.updateBlastStatusByUuid(uuid, "2");
  136. }
  137. }
  138. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "safeCheck") {
  139. // 处理安全验证消息
  140. if (jsonObj["status"] != "ok") {
  141. QMessageBox::warning(this, "安全验证失败",
  142. QString("安全验证未通过,练习安全员确认"));
  143. return;
  144. }
  145. const QString addressUuid = jsonObj["addressUuid"].toString();
  146. QJsonArray addressList = backendAPIManager::getHAddresses();
  147. QList<QString> subAddressUuids = findAllChildUuids(addressList, addressUuid);
  148. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  149. QList<QSharedPointer<HProject>> projects =
  150. dao.getRegistedProjectByAddressUuid(subAddressUuids);
  151. for (const auto &project : projects) {
  152. dao.updateBlastStatusByUuid(project->getUuid(), BlastStatus::SafeChecked);
  153. }
  154. }
  155. }
  156. }
  157. void MainWindow::setStyleSheets(QPushButton *selectedButton) {
  158. for (auto *b : left_button_station) {
  159. b->setProperty("selected", b == selectedButton);
  160. b->setStyleSheet(b->styleSheet()); // 刷新显示
  161. }
  162. }
  163. // 处理 MQTT 连接成功的槽函数
  164. void MainWindow::onMqttConnected() {
  165. m_isMqttConnected = true;
  166. Logger::getInstance().info("Mqtt connected.");
  167. }
  168. void MainWindow::initialBtnSerial() {
  169. bool success;
  170. serialTool = SerialTool::getInstance(this, &success);
  171. connect(serialTool, &SerialTool::serialPortOpened, this, &MainWindow::onSerialToolCreated);
  172. serialTool->setupSerialPort();
  173. Logger::getInstance().info("Fire buttons initialized");
  174. }
  175. void MainWindow::onSerialToolCreated() {
  176. m_btnSerialInitialized = true;
  177. serialTool->releaseInstance();
  178. qDebug() << ANSI_COLOR_GREEN << "Serial tool initialized" << ANSI_COLOR_RESET;
  179. Logger::getInstance().info("SerialTool initialized");
  180. }
  181. void MainWindow::initialGPSSerial() {
  182. Logger::getInstance().info("开始初始化GPS");
  183. SerialGPSThread *threadGPS = new SerialGPSThread(this);
  184. connect(threadGPS, &SerialGPSThread::storedGNRMCDataUpdated, this,
  185. &MainWindow::handleStoredGNRMCData);
  186. threadGPS->start();
  187. }
  188. // 槽函数,用于接收 RMCData 数据
  189. void MainWindow::handleStoredGNRMCData(const RMCData &data) {
  190. if (data.isValid) {
  191. lat = QString::number(data.latitude);
  192. lon = QString::number(data.longitude);
  193. } else {
  194. lat = "定位失败";
  195. lon = "定位失败";
  196. }
  197. ui->labLat->setText("经度: " + lat);
  198. ui->labLon->setText("纬度: " + lon);
  199. labLat = lat;
  200. labLon = lon;
  201. }
  202. void MainWindow::initDateTime() {
  203. timeThread = new TimeUpdateThread(this);
  204. connect(timeThread, &TimeUpdateThread::timeUpdated, this, &MainWindow::onTimeUpdated);
  205. timeThread->start();
  206. }
  207. void MainWindow::onTimeUpdated(const QString &timeString) { ui->dateTimeShow->setText(timeString); }
  208. MainWindow::~MainWindow() {
  209. timeThread->stop();
  210. delete ui;
  211. }
  212. void MainWindow::mousePressEvent(QMouseEvent *event) {
  213. if (event->button() == Qt::LeftButton) {
  214. m_dragPosition = event->globalPos() - frameGeometry().topLeft();
  215. event->accept();
  216. }
  217. }
  218. void MainWindow::mouseMoveEvent(QMouseEvent *event) {
  219. if (event->buttons() & Qt::LeftButton) {
  220. move(event->globalPos() - m_dragPosition);
  221. event->accept();
  222. }
  223. }
  224. QList<QString> MainWindow::findAllChildUuids(const QJsonArray &addressArray,
  225. const QString targetUuid) {
  226. QList<QString> childrenUuids;
  227. for (const QJsonValue &value : addressArray) {
  228. if (!value.isObject()) continue;
  229. QJsonObject addressObj = value.toObject();
  230. QString currentUuid = addressObj["uuid"].toString();
  231. if (currentUuid == targetUuid) {
  232. // Found the target address, now collect all children UUIDs recursively
  233. if (addressObj.contains("children") && addressObj["children"].isArray()) {
  234. QJsonArray children = addressObj["children"].toArray();
  235. for (const QJsonValue &child : children) {
  236. if (child.isObject()) {
  237. QString childUuid = child.toObject()["uuid"].toString();
  238. childrenUuids.append(childUuid);
  239. // Also add any grandchildren
  240. if (child.toObject().contains("children") &&
  241. child.toObject()["children"].isArray()) {
  242. QJsonArray grandchildren = child.toObject()["children"].toArray();
  243. childrenUuids.append(findAllChildUuids(
  244. grandchildren, child.toObject()["uuid"].toString()));
  245. }
  246. }
  247. }
  248. return childrenUuids;
  249. }
  250. } else if (addressObj.contains("children") && addressObj["children"].isArray()) {
  251. // Continue searching in children
  252. QJsonArray children = addressObj["children"].toArray();
  253. QList<QString> result = findAllChildUuids(children, targetUuid);
  254. if (!result.isEmpty()) {
  255. return result;
  256. }
  257. }
  258. }
  259. return childrenUuids;
  260. }