mainwindow.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. Logger::getInstance().info("Received Mqtt message on topic: " + topic.name() +
  123. ", message: " + QString::fromUtf8(message));
  124. QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
  125. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  126. QJsonObject jsonObj = jsonDoc.object();
  127. if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
  128. QJsonValue uuidValue = jsonObj["uuid"];
  129. QJsonValue statusValue = jsonObj["status"];
  130. if (statusValue.isString() &&
  131. statusValue.toString() == BlastStatus::Created) { // "1" 未注册
  132. if (uuidValue.isNull()) {
  133. qDebug() << "uuid 的值为 null";
  134. } else {
  135. QString uuid = uuidValue.toString();
  136. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  137. dao.updateBlastStatusByUuid(uuid, "2");
  138. }
  139. }
  140. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "safeCheck") {
  141. // 处理安全验证消息
  142. if (jsonObj["status"] != "ok") {
  143. QMessageBox::warning(this, "安全验证失败",
  144. QString("安全验证未通过,练习安全员确认"));
  145. return;
  146. }
  147. const QString addressUuid = jsonObj["addressUuid"].toString();
  148. QJsonArray addressList = backendAPIManager::getHAddresses();
  149. QList<QString> subAddressUuids = findAllChildUuids(addressList, addressUuid);
  150. subAddressUuids.append(addressUuid); // 添加当前地址的 UUID
  151. qDebug() << "子地址 UUIDs: " << subAddressUuids << "-----" << addressUuid;
  152. if (subAddressUuids.isEmpty()) {
  153. QMessageBox::information(nullptr, "安全验证失败",
  154. QString("未找到子地址,练习安全员确认"));
  155. return;
  156. }
  157. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  158. QList<QSharedPointer<HProject>> pendingCheckProjects =
  159. dao.getRegistedProjectByAddressUuid(subAddressUuids);
  160. for (const auto &project : pendingCheckProjects) {
  161. dao.updateBlastStatusByUuid(project->getUuid(), BlastStatus::SafeChecked);
  162. }
  163. if (!pendingCheckProjects.isEmpty()) {
  164. QMessageBox::information(nullptr, "安全员确认信息",
  165. QString("收到工程被安全员确认,请查看爆破列表"));
  166. return;
  167. }
  168. // TODO: refresh the project list page
  169. }
  170. }
  171. }
  172. void MainWindow::setStyleSheets(QPushButton *selectedButton) {
  173. for (auto *b : left_button_station) {
  174. b->setProperty("selected", b == selectedButton);
  175. b->setStyleSheet(b->styleSheet()); // 刷新显示
  176. }
  177. }
  178. // 处理 MQTT 连接成功的槽函数
  179. void MainWindow::onMqttConnected() {
  180. m_isMqttConnected = true;
  181. Logger::getInstance().info("Mqtt connected.");
  182. }
  183. void MainWindow::initialBtnSerial() {
  184. bool success;
  185. serialTool = SerialTool::getInstance(this, &success);
  186. connect(serialTool, &SerialTool::serialPortOpened, this, &MainWindow::onSerialToolCreated);
  187. serialTool->setupSerialPort();
  188. Logger::getInstance().info("Fire buttons initialized");
  189. }
  190. void MainWindow::onSerialToolCreated() {
  191. m_btnSerialInitialized = true;
  192. serialTool->releaseInstance();
  193. qDebug() << ANSI_COLOR_GREEN << "Serial tool initialized" << ANSI_COLOR_RESET;
  194. Logger::getInstance().info("SerialTool initialized");
  195. }
  196. void MainWindow::initialGPSSerial() {
  197. Logger::getInstance().info("开始初始化GPS");
  198. SerialGPSThread *threadGPS = new SerialGPSThread(this);
  199. connect(threadGPS, &SerialGPSThread::storedGNRMCDataUpdated, this,
  200. &MainWindow::handleStoredGNRMCData);
  201. threadGPS->start();
  202. }
  203. // 槽函数,用于接收 RMCData 数据
  204. void MainWindow::handleStoredGNRMCData(const RMCData &data) {
  205. if (data.isValid) {
  206. lat = QString::number(data.latitude);
  207. lon = QString::number(data.longitude);
  208. } else {
  209. lat = "定位失败";
  210. lon = "定位失败";
  211. }
  212. ui->labLat->setText("经度: " + lat);
  213. ui->labLon->setText("纬度: " + lon);
  214. labLat = lat;
  215. labLon = lon;
  216. }
  217. void MainWindow::initDateTime() {
  218. timeThread = new TimeUpdateThread(this);
  219. connect(timeThread, &TimeUpdateThread::timeUpdated, this, &MainWindow::onTimeUpdated);
  220. timeThread->start();
  221. }
  222. void MainWindow::onTimeUpdated(const QString &timeString) { ui->dateTimeShow->setText(timeString); }
  223. MainWindow::~MainWindow() {
  224. timeThread->stop();
  225. delete ui;
  226. }
  227. void MainWindow::mousePressEvent(QMouseEvent *event) {
  228. if (event->button() == Qt::LeftButton) {
  229. m_dragPosition = event->globalPos() - frameGeometry().topLeft();
  230. event->accept();
  231. }
  232. }
  233. void MainWindow::mouseMoveEvent(QMouseEvent *event) {
  234. if (event->buttons() & Qt::LeftButton) {
  235. move(event->globalPos() - m_dragPosition);
  236. event->accept();
  237. }
  238. }
  239. QList<QString> MainWindow::findAllChildUuids(const QJsonArray &addressArray,
  240. const QString targetUuid) {
  241. QList<QString> childrenUuids;
  242. for (const QJsonValue &value : addressArray) {
  243. if (!value.isObject()) continue;
  244. QJsonObject addressObj = value.toObject();
  245. QString currentUuid = addressObj["uuid"].toString();
  246. if (currentUuid == targetUuid) {
  247. // Found the target address, now collect all children UUIDs recursively
  248. if (addressObj.contains("children") && addressObj["children"].isArray()) {
  249. QJsonArray children = addressObj["children"].toArray();
  250. for (const QJsonValue &child : children) {
  251. if (child.isObject()) {
  252. QString childUuid = child.toObject()["uuid"].toString();
  253. childrenUuids.append(childUuid);
  254. // Also add any grandchildren
  255. if (child.toObject().contains("children") &&
  256. child.toObject()["children"].isArray()) {
  257. QJsonArray grandchildren = child.toObject()["children"].toArray();
  258. childrenUuids.append(findAllChildUuids(
  259. grandchildren, child.toObject()["uuid"].toString()));
  260. }
  261. }
  262. }
  263. return childrenUuids;
  264. }
  265. } else if (addressObj.contains("children") && addressObj["children"].isArray()) {
  266. // Continue searching in children
  267. QJsonArray children = addressObj["children"].toArray();
  268. QList<QString> result = findAllChildUuids(children, targetUuid);
  269. if (!result.isEmpty()) {
  270. return result;
  271. }
  272. }
  273. }
  274. return childrenUuids;
  275. }