mainwindow.cpp 11 KB

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