mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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->setStyleSheet("QWidget { font-size: 16px; }");
  24. this->setStyleSheet("QPushButton { font-size: 16px; }");
  25. ui->setupUi(this);
  26. LoadingWidget::init(ui->stackedWidget);
  27. initializeAnimate();
  28. initialMqttService();
  29. pageFactories[ui->btnHome] = new HomepageFactory();
  30. pageFactories[ui->btnNew] = new AddressFactory();
  31. pageFactories[ui->btnBlastProject] = new BlastProjectFactory();
  32. pageFactories[ui->btnEquipment] = new EquipmentFactory();
  33. pageFactories[ui->btnDet] = new DetInfoFactory();
  34. pageFactories[ui->btnBlastOper] = new BlastOperationFactory();
  35. pageFactories[ui->btnRecord] = new BlastRecordFactory();
  36. connect(ui->btnToggle, &QPushButton::clicked, this, &MainWindow::onToggleButtonClicked);
  37. for (auto *widget : left_button_station) {
  38. QPushButton *button = qobject_cast<QPushButton *>(widget);
  39. if (button) {
  40. connect(button, &QPushButton::clicked, this, [this, button] { onButtonClicked(button); });
  41. }
  42. }
  43. initDateTime();
  44. initialBtnSerial();
  45. // initialGPSSerial();
  46. ui->labLat->setText("经度: " + lat);
  47. ui->labLon->setText("维度: " + lon);
  48. connect(ui->btnClose, &QPushButton::clicked, this, &MainWindow::close);
  49. connect(this, &MainWindow::menubarTitleChanged, this, &MainWindow::updateProjectTitleLabel);
  50. } catch (const std::exception &ex) {
  51. Logger::getInstance().error(QString("Application crashed: %1").arg(ex.what()));
  52. QMessageBox::critical(this, "Error", QString("Application crashed: %1").arg(ex.what()));
  53. throw; // rethrow to allow further handling if needed
  54. } catch (...) {
  55. Logger::getInstance().error("Application crashed: Unknown exception");
  56. QMessageBox::critical(this, "Error", "Application crashed: Unknown exception");
  57. throw;
  58. }
  59. this->switchPage(ui->btnHome); // 默认显示首页
  60. }
  61. void MainWindow::updateProjectTitleLabel(const QString &newTitle) { ui->projectTitleLable->setText(newTitle); }
  62. void MainWindow::handleRefreshPage() {
  63. // 刷新页面
  64. ui->stackedWidget->currentWidget()->update();
  65. }
  66. void MainWindow::setMenubarTitle(const QString &newTitle) {
  67. if (m_currentProjectTitle != newTitle) {
  68. m_currentProjectTitle = newTitle;
  69. // Emit the signal to notify listeners (like our QLabel slot)
  70. emit menubarTitleChanged(m_currentProjectTitle);
  71. }
  72. }
  73. void MainWindow::initializeAnimate() {
  74. move(200, 200);
  75. animate_leftFrame = new QPropertyAnimation(ui->leftFrame, "minimumWidth");
  76. animate_leftFrame->setDuration(300);
  77. for (QObject *child : ui->left_buttonsBox->children()) {
  78. if (qobject_cast<QWidget *>(child)) {
  79. left_button_station.append(qobject_cast<QWidget *>(child));
  80. }
  81. }
  82. }
  83. void MainWindow::onToggleButtonClicked() {
  84. // 执行动画
  85. JOBS ::btn_animation(ui->leftFrame, animate_leftFrame);
  86. for (QWidget *b : left_button_station) {
  87. b->setProperty("spread", !b->property("spread").toBool());
  88. b->setStyleSheet(b->styleSheet());
  89. }
  90. }
  91. // 选中按钮
  92. void MainWindow::onButtonClicked(QPushButton *button) {
  93. setStyleSheets(static_cast<QPushButton *>(button));
  94. switchPage(static_cast<QPushButton *>(button));
  95. }
  96. void MainWindow::switchPage(QWidget *button) {
  97. LoadingWidget::showLoading(this, "请稍等");
  98. if (pageFactories.contains(button)) {
  99. PageFactory *factory = pageFactories[button];
  100. if (createdPageByButton.contains(button)) {
  101. QWidget *existingPage = createdPageByButton[button];
  102. existingPage->hide();
  103. ui->stackedWidget->removeWidget(existingPage);
  104. createdPageByButton.remove(button);
  105. }
  106. QWidget *newPage = factory->createPage(this);
  107. ui->stackedWidget->addWidget(newPage);
  108. ui->stackedWidget->setCurrentWidget(newPage);
  109. setMenubarTitle(qobject_cast<QPushButton *>(button)->text());
  110. createdPageByButton.insert(button, newPage);
  111. int pageCount = ui->stackedWidget->count();
  112. }
  113. LoadingWidget::hideLoading();
  114. }
  115. void MainWindow::initialMqttService() {
  116. Logger::getInstance().info("Start init Mqtt server.");
  117. if (mainMqttClient != nullptr) {
  118. QMqttSubscription *projectMsgSubsciber = mainMqttClient->subscribeToTopic(MQTT_TOPIC_COMPANY_PROJECTS_SUB);
  119. if (projectMsgSubsciber != nullptr) {
  120. connect(projectMsgSubsciber, &QMqttSubscription::messageReceived, this,
  121. &MainWindow::handleMqttProjectsMessage);
  122. } else {
  123. Logger::getInstance().error("Failed to subscribe to MQTT topic: " + MQTT_TOPIC_COMPANY_PROJECTS_SUB);
  124. }
  125. } else {
  126. Logger::getInstance().error("mainMqttClient is null, cannot initialize MQTT service");
  127. }
  128. }
  129. void MainWindow::publishBlastProjects() {
  130. QJsonArray jsonArray;
  131. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  132. QList<QSharedPointer<HProject>> projectsReg = dao.getAllHProjectsReg();
  133. for (const auto &projectPtr : projectsReg) {
  134. if (projectPtr) {
  135. QByteArray projectJson = projectPtr->ProjectToJson(*projectPtr);
  136. QJsonDocument doc = QJsonDocument::fromJson(projectJson);
  137. jsonArray.append(doc.object());
  138. }
  139. }
  140. QJsonDocument jsonDoc(jsonArray);
  141. QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Indented);
  142. mainMqttClient->sendMessage(MQTT_TOPIC_COMPANY_PROJECTS_PUBLISH, jsonData, 2, true);
  143. }
  144. void MainWindow::handleMqttProjectsMessage(const QMqttMessage &message) {
  145. Logger::getInstance().info("Received Mqtt message on topic: " + message.topic().name() +
  146. ", message: " + QString::fromUtf8(message.payload()));
  147. QJsonDocument jsonDoc = QJsonDocument::fromJson(message.payload());
  148. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  149. // 注册工程信息
  150. QJsonObject jsonObj = jsonDoc.object();
  151. if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
  152. QJsonValue uuidValue = jsonObj["uuid"];
  153. QJsonValue statusValue = jsonObj["status"];
  154. if (statusValue.isString() && statusValue.toString() == BlastStatus::Created) { // "1" 未注册
  155. if (uuidValue.isNull()) {
  156. qDebug() << "uuid 的值为 null";
  157. } else {
  158. QString uuid = uuidValue.toString();
  159. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  160. dao.updateBlastStatusByUuid(uuid, BlastStatus::Registered);
  161. }
  162. }
  163. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "blastSuccess") {
  164. // 爆破成功, 更新状态; 尤其是离线爆破的; 服务器收到爆破记录后发布
  165. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  166. for (const QJsonValue &projectUuid : jsonObj["projectUuids"].toArray()) {
  167. qDebug() << "Received offline project blasted UUID: " << projectUuid;
  168. dao.updateBlastStatusByUuid(projectUuid.toString(), BlastStatus::Blasted);
  169. }
  170. publishBlastProjects();
  171. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "safeCheck") {
  172. // 处理安全验证消息
  173. if (jsonObj["status"] != "ok") {
  174. QMessageBox::warning(this, "安全验证失败", QString("安全验证未通过,请联系安全员确认"));
  175. return;
  176. }
  177. const QString addressUuid = jsonObj["addressUuid"].toString();
  178. QJsonArray addressList = backendAPIManager::getHAddresses();
  179. QList<QString> subAddressUuids = findAllChildUuids(addressList, addressUuid);
  180. subAddressUuids.append(addressUuid); // 添加当前地址的 UUID
  181. if (subAddressUuids.isEmpty()) {
  182. QMessageBox::information(nullptr, "安全验证失败", QString("未找到子地址,请联系安全员确认"));
  183. return;
  184. }
  185. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  186. QList<QSharedPointer<HProject>> pendingCheckProjects = dao.getRegistedProjectByAddressUuid(subAddressUuids);
  187. for (const auto &project : pendingCheckProjects) {
  188. dao.updateBlastStatusByUuid(project->getUuid(), BlastStatus::SafeChecked);
  189. }
  190. if (!pendingCheckProjects.isEmpty()) {
  191. QMessageBox::information(nullptr, "安全员确认信息",
  192. QString("收到工程被安全员确认,请刷新查看爆破作业列表"));
  193. return;
  194. }
  195. }
  196. }
  197. }
  198. void MainWindow::setStyleSheets(QPushButton *selectedButton) {
  199. for (auto *b : left_button_station) {
  200. b->setProperty("selected", b == selectedButton);
  201. b->setStyleSheet(b->styleSheet()); // 刷新显示
  202. }
  203. }
  204. // 处理 MQTT 连接成功的槽函数
  205. void MainWindow::onMqttConnected() {
  206. m_isMqttConnected = true;
  207. Logger::getInstance().info("Mqtt connected.");
  208. }
  209. void MainWindow::initialBtnSerial() {
  210. bool success;
  211. serialTool = SerialTool::getInstance(this, &success);
  212. connect(serialTool, &SerialTool::serialPortOpened, this, &MainWindow::onSerialToolCreated);
  213. serialTool->setupSerialPort();
  214. Logger::getInstance().info("Fire buttons initialized");
  215. }
  216. void MainWindow::onSerialToolCreated() {
  217. m_btnSerialInitialized = true;
  218. serialTool->releaseInstance();
  219. qDebug() << ANSI_COLOR_GREEN << "Serial tool initialized" << ANSI_COLOR_RESET;
  220. Logger::getInstance().info("SerialTool initialized");
  221. }
  222. void MainWindow::initialGPSSerial() {
  223. Logger::getInstance().info("开始初始化GPS");
  224. SerialGPSThread *threadGPS = new SerialGPSThread(this);
  225. connect(threadGPS, &SerialGPSThread::storedGNRMCDataUpdated, this, &MainWindow::handleStoredGNRMCData);
  226. threadGPS->start();
  227. }
  228. // 槽函数,用于接收 RMCData 数据
  229. void MainWindow::handleStoredGNRMCData(const RMCData &data) {
  230. if (data.isValid) {
  231. lat = QString::number(data.latitude);
  232. lon = QString::number(data.longitude);
  233. } else {
  234. lat = "定位失败";
  235. lon = "定位失败";
  236. }
  237. ui->labLat->setText("经度: " + lat);
  238. ui->labLon->setText("纬度: " + lon);
  239. labLat = lat;
  240. labLon = lon;
  241. }
  242. void MainWindow::initDateTime() {
  243. timeThread = new TimeUpdateThread(this);
  244. connect(timeThread, &TimeUpdateThread::timeUpdated, this, &MainWindow::onTimeUpdated);
  245. timeThread->start();
  246. }
  247. void MainWindow::onTimeUpdated(const QString &timeString) { ui->dateTimeShow->setText(timeString); }
  248. MainWindow::~MainWindow() {
  249. timeThread->stop();
  250. delete ui;
  251. }
  252. void MainWindow::mousePressEvent(QMouseEvent *event) {
  253. // if (event->button() == Qt::LeftButton) {
  254. // m_dragPosition = event->globalPos() - frameGeometry().topLeft();
  255. // event->accept();
  256. // }
  257. }
  258. void MainWindow::mouseMoveEvent(QMouseEvent *event) {
  259. // if (event->buttons() & Qt::LeftButton) {
  260. // move(event->globalPos() - m_dragPosition);
  261. // event->accept();
  262. // }
  263. }
  264. QList<QString> MainWindow::findAllChildUuids(const QJsonArray &addressArray, const QString targetUuid) {
  265. QList<QString> childrenUuids;
  266. for (const QJsonValue &value : addressArray) {
  267. if (!value.isObject()) continue;
  268. QJsonObject addressObj = value.toObject();
  269. QString currentUuid = addressObj["uuid"].toString();
  270. if (currentUuid == targetUuid) {
  271. // Found the target address, now collect all children UUIDs recursively
  272. if (addressObj.contains("children") && addressObj["children"].isArray()) {
  273. QJsonArray children = addressObj["children"].toArray();
  274. for (const QJsonValue &child : children) {
  275. if (child.isObject()) {
  276. QString childUuid = child.toObject()["uuid"].toString();
  277. childrenUuids.append(childUuid);
  278. // max depth 3
  279. if (child.toObject().contains("children") && child.toObject()["children"].isArray()) {
  280. QJsonArray grandchildren = child.toObject()["children"].toArray();
  281. for (const QJsonValue &grandchild : grandchildren) {
  282. if (grandchild.isObject()) {
  283. QString grandchildUuid = grandchild.toObject()["uuid"].toString();
  284. childrenUuids.append(grandchildUuid);
  285. }
  286. }
  287. }
  288. }
  289. }
  290. return childrenUuids;
  291. }
  292. } else if (addressObj.contains("children") && addressObj["children"].isArray()) {
  293. // Continue searching in children
  294. QJsonArray children = addressObj["children"].toArray();
  295. QList<QString> result = findAllChildUuids(children, targetUuid);
  296. if (!result.isEmpty()) {
  297. return result;
  298. }
  299. }
  300. }
  301. return childrenUuids;
  302. }