mainwindow.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 "mqtt/mqttclient.h"
  13. #include "ui_mainwindow.h"
  14. // 定义 ANzI 转义序列来设置颜色
  15. #define ANSI_COLOR_GREEN "\x1B[32m"
  16. #define ANSI_COLOR_RESET "\x1B[0m"
  17. #include <QMessageBox>
  18. #include <exception>
  19. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
  20. try {
  21. this->setWindowFlags(Qt::FramelessWindowHint | Qt::Window);
  22. this->setWindowState(Qt::WindowMaximized); // Maximizes the window
  23. // this->setFixedSize(1360, 864);
  24. ui->setupUi(this);
  25. LoadingWidget::init(ui->stackedWidget);
  26. initializeAnimate();
  27. initialMqttService();
  28. pageFactories[ui->btnNew] = new AddressFactory();
  29. pageFactories[ui->btnBlastProject] = new BlastProjectFactory();
  30. pageFactories[ui->btnEquipment] = new EquipmentFactory();
  31. pageFactories[ui->btnDet] = new DetInfoFactory();
  32. pageFactories[ui->btnBlastOper] = new BlastOperationFactory();
  33. pageFactories[ui->btnRecord] = new BlastRecordFactory();
  34. connect(ui->btnToggle, &QPushButton::clicked, this, &MainWindow::onToggleButtonClicked);
  35. for (auto *widget : left_button_station) {
  36. QPushButton *button = qobject_cast<QPushButton *>(widget);
  37. if (button) {
  38. connect(button, &QPushButton::clicked, this, [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::menubarTitleChanged, 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) { ui->projectTitleLable->setText(newTitle); }
  59. void MainWindow::handleRefreshPage() {
  60. // 刷新页面
  61. ui->stackedWidget->currentWidget()->update();
  62. }
  63. void MainWindow::setMenubarTitle(const QString &newTitle) {
  64. if (m_currentProjectTitle != newTitle) {
  65. m_currentProjectTitle = newTitle;
  66. // Emit the signal to notify listeners (like our QLabel slot)
  67. emit menubarTitleChanged(m_currentProjectTitle);
  68. }
  69. }
  70. void MainWindow::initializeAnimate() {
  71. move(200, 200);
  72. animate_leftFrame = new QPropertyAnimation(ui->leftFrame, "minimumWidth");
  73. animate_leftFrame->setDuration(300);
  74. for (QObject *child : ui->left_buttonsBox->children()) {
  75. if (qobject_cast<QWidget *>(child)) {
  76. left_button_station.append(qobject_cast<QWidget *>(child));
  77. }
  78. }
  79. }
  80. void MainWindow::onToggleButtonClicked() {
  81. // 执行动画
  82. JOBS ::btn_animation(ui->leftFrame, animate_leftFrame);
  83. for (QWidget *b : left_button_station) {
  84. b->setProperty("spread", !b->property("spread").toBool());
  85. b->setStyleSheet(b->styleSheet());
  86. }
  87. }
  88. // 选中按钮
  89. void MainWindow::onButtonClicked(QPushButton *button) {
  90. setStyleSheets(static_cast<QPushButton *>(button));
  91. switchPage(static_cast<QPushButton *>(button));
  92. }
  93. void MainWindow::switchPage(QWidget *button) {
  94. LoadingWidget::showLoading(this, "请稍等");
  95. if (pageFactories.contains(button)) {
  96. PageFactory *factory = pageFactories[button];
  97. if (createdPageByButton.contains(button)) {
  98. QWidget *existingPage = createdPageByButton[button];
  99. existingPage->hide();
  100. ui->stackedWidget->removeWidget(existingPage);
  101. createdPageByButton.remove(button);
  102. }
  103. QWidget *newPage = factory->createPage(this);
  104. ui->stackedWidget->addWidget(newPage);
  105. ui->stackedWidget->setCurrentWidget(newPage);
  106. setMenubarTitle(qobject_cast<QPushButton *>(button)->text());
  107. createdPageByButton.insert(button, newPage);
  108. int pageCount = ui->stackedWidget->count();
  109. }
  110. LoadingWidget::hideLoading();
  111. }
  112. void MainWindow::initialMqttService() {
  113. Logger::getInstance().info("Start init Mqtt server.");
  114. if (mainMqttClient != nullptr) {
  115. QMqttSubscription *projectMsgSubsciber = mainMqttClient->subscribeToTopic(MQTT_TOPIC_COMPANY_PROJECTS);
  116. if (projectMsgSubsciber != nullptr) {
  117. connect(projectMsgSubsciber, &QMqttSubscription::messageReceived, this, &MainWindow::handleMqttProjectsMessage);
  118. } else {
  119. Logger::getInstance().error("Failed to subscribe to MQTT topic: " + MQTT_TOPIC_COMPANY_PROJECTS);
  120. }
  121. } else {
  122. Logger::getInstance().error("mainMqttClient is null, cannot initialize MQTT service");
  123. }
  124. }
  125. void MainWindow::handleMqttProjectsMessage(const QMqttMessage &message) {
  126. Logger::getInstance().info("Received Mqtt message on topic: " + message.topic().name() +
  127. ", message: " + QString::fromUtf8(message.payload()));
  128. QJsonDocument jsonDoc = QJsonDocument::fromJson(message.payload());
  129. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  130. // 注册工程信息
  131. QJsonObject jsonObj = jsonDoc.object();
  132. if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
  133. QJsonValue uuidValue = jsonObj["uuid"];
  134. QJsonValue statusValue = jsonObj["status"];
  135. if (statusValue.isString() && statusValue.toString() == BlastStatus::Created) { // "1" 未注册
  136. if (uuidValue.isNull()) {
  137. qDebug() << "uuid 的值为 null";
  138. } else {
  139. QString uuid = uuidValue.toString();
  140. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  141. dao.updateBlastStatusByUuid(uuid, "2");
  142. }
  143. }
  144. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "safeCheck") {
  145. // 处理安全验证消息
  146. if (jsonObj["status"] != "ok") {
  147. QMessageBox::warning(this, "安全验证失败", QString("安全验证未通过,请联系安全员确认"));
  148. return;
  149. }
  150. const QString addressUuid = jsonObj["addressUuid"].toString();
  151. QJsonArray addressList = backendAPIManager::getHAddresses();
  152. QList<QString> subAddressUuids = findAllChildUuids(addressList, addressUuid);
  153. subAddressUuids.append(addressUuid); // 添加当前地址的 UUID
  154. qDebug() << "子地址 UUIDs: " << subAddressUuids << "-----" << addressUuid;
  155. if (subAddressUuids.isEmpty()) {
  156. QMessageBox::information(nullptr, "安全验证失败", QString("未找到子地址,请联系安全员确认"));
  157. return;
  158. }
  159. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  160. QList<QSharedPointer<HProject>> pendingCheckProjects = dao.getRegistedProjectByAddressUuid(subAddressUuids);
  161. for (const auto &project : pendingCheckProjects) {
  162. dao.updateBlastStatusByUuid(project->getUuid(), BlastStatus::SafeChecked);
  163. }
  164. if (!pendingCheckProjects.isEmpty()) {
  165. QMessageBox::information(nullptr, "安全员确认信息", QString("收到工程被安全员确认,请查看爆破列表"));
  166. emit refreshPage();
  167. return;
  168. }
  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, &MainWindow::handleStoredGNRMCData);
  200. threadGPS->start();
  201. }
  202. // 槽函数,用于接收 RMCData 数据
  203. void MainWindow::handleStoredGNRMCData(const RMCData &data) {
  204. if (data.isValid) {
  205. lat = QString::number(data.latitude);
  206. lon = QString::number(data.longitude);
  207. } else {
  208. lat = "定位失败";
  209. lon = "定位失败";
  210. }
  211. ui->labLat->setText("经度: " + lat);
  212. ui->labLon->setText("纬度: " + lon);
  213. labLat = lat;
  214. labLon = lon;
  215. }
  216. void MainWindow::initDateTime() {
  217. timeThread = new TimeUpdateThread(this);
  218. connect(timeThread, &TimeUpdateThread::timeUpdated, this, &MainWindow::onTimeUpdated);
  219. timeThread->start();
  220. }
  221. void MainWindow::onTimeUpdated(const QString &timeString) { ui->dateTimeShow->setText(timeString); }
  222. MainWindow::~MainWindow() {
  223. timeThread->stop();
  224. delete ui;
  225. }
  226. void MainWindow::mousePressEvent(QMouseEvent *event) {
  227. // if (event->button() == Qt::LeftButton) {
  228. // m_dragPosition = event->globalPos() - frameGeometry().topLeft();
  229. // event->accept();
  230. // }
  231. }
  232. void MainWindow::mouseMoveEvent(QMouseEvent *event) {
  233. // if (event->buttons() & Qt::LeftButton) {
  234. // move(event->globalPos() - m_dragPosition);
  235. // event->accept();
  236. // }
  237. }
  238. QList<QString> MainWindow::findAllChildUuids(const QJsonArray &addressArray, const QString targetUuid) {
  239. QList<QString> childrenUuids;
  240. for (const QJsonValue &value : addressArray) {
  241. if (!value.isObject()) continue;
  242. QJsonObject addressObj = value.toObject();
  243. QString currentUuid = addressObj["uuid"].toString();
  244. if (currentUuid == targetUuid) {
  245. // Found the target address, now collect all children UUIDs recursively
  246. if (addressObj.contains("children") && addressObj["children"].isArray()) {
  247. QJsonArray children = addressObj["children"].toArray();
  248. for (const QJsonValue &child : children) {
  249. if (child.isObject()) {
  250. QString childUuid = child.toObject()["uuid"].toString();
  251. childrenUuids.append(childUuid);
  252. // max depth 3
  253. if (child.toObject().contains("children") && child.toObject()["children"].isArray()) {
  254. QJsonArray grandchildren = child.toObject()["children"].toArray();
  255. for (const QJsonValue &grandchild : grandchildren) {
  256. if (grandchild.isObject()) {
  257. QString grandchildUuid = grandchild.toObject()["uuid"].toString();
  258. childrenUuids.append(grandchildUuid);
  259. }
  260. }
  261. }
  262. }
  263. }
  264. return childrenUuids;
  265. }
  266. } else if (addressObj.contains("children") && addressObj["children"].isArray()) {
  267. // Continue searching in children
  268. QJsonArray children = addressObj["children"].toArray();
  269. QList<QString> result = findAllChildUuids(children, targetUuid);
  270. if (!result.isEmpty()) {
  271. return result;
  272. }
  273. }
  274. }
  275. return childrenUuids;
  276. }