mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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_SUB);
  116. if (projectMsgSubsciber != nullptr) {
  117. connect(projectMsgSubsciber, &QMqttSubscription::messageReceived, this,
  118. &MainWindow::handleMqttProjectsMessage);
  119. } else {
  120. Logger::getInstance().error("Failed to subscribe to MQTT topic: " + MQTT_TOPIC_COMPANY_PROJECTS_SUB);
  121. }
  122. } else {
  123. Logger::getInstance().error("mainMqttClient is null, cannot initialize MQTT service");
  124. }
  125. }
  126. void MainWindow::publishBlastProjects() {
  127. QJsonArray jsonArray;
  128. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  129. QList<QSharedPointer<HProject>> projectsReg = dao.getAllHProjectsReg();
  130. for (const auto &projectPtr : projectsReg) {
  131. if (projectPtr) {
  132. QByteArray projectJson = projectPtr->ProjectToJson(*projectPtr);
  133. QJsonDocument doc = QJsonDocument::fromJson(projectJson);
  134. jsonArray.append(doc.object());
  135. }
  136. }
  137. QJsonDocument jsonDoc(jsonArray);
  138. QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Indented);
  139. mainMqttClient->sendMessage(MQTT_TOPIC_COMPANY_PROJECTS_PUBLISH, jsonData, 2, true);
  140. }
  141. void MainWindow::handleMqttProjectsMessage(const QMqttMessage &message) {
  142. Logger::getInstance().info("Received Mqtt message on topic: " + message.topic().name() +
  143. ", message: " + QString::fromUtf8(message.payload()));
  144. QJsonDocument jsonDoc = QJsonDocument::fromJson(message.payload());
  145. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  146. // 注册工程信息
  147. QJsonObject jsonObj = jsonDoc.object();
  148. if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
  149. QJsonValue uuidValue = jsonObj["uuid"];
  150. QJsonValue statusValue = jsonObj["status"];
  151. if (statusValue.isString() && statusValue.toString() == BlastStatus::Created) { // "1" 未注册
  152. if (uuidValue.isNull()) {
  153. qDebug() << "uuid 的值为 null";
  154. } else {
  155. QString uuid = uuidValue.toString();
  156. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  157. dao.updateBlastStatusByUuid(uuid, BlastStatus::Registered);
  158. }
  159. }
  160. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "blastSuccess") {
  161. // 爆破成功, 更新状态; 尤其是离线爆破的; 服务器收到爆破记录后发布
  162. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  163. for (const QJsonValue &projectUuid : jsonObj["projectUuids"].toArray()) {
  164. qDebug() << "Received offline project blasted UUID: " << projectUuid;
  165. dao.updateBlastStatusByUuid(projectUuid.toString(), BlastStatus::Blasted);
  166. }
  167. publishBlastProjects();
  168. } else if (jsonObj.contains("msgType") && jsonObj["msgType"].toString() == "safeCheck") {
  169. // 处理安全验证消息
  170. if (jsonObj["status"] != "ok") {
  171. QMessageBox::warning(this, "安全验证失败", QString("安全验证未通过,请联系安全员确认"));
  172. return;
  173. }
  174. const QString addressUuid = jsonObj["addressUuid"].toString();
  175. QJsonArray addressList = backendAPIManager::getHAddresses();
  176. QList<QString> subAddressUuids = findAllChildUuids(addressList, addressUuid);
  177. subAddressUuids.append(addressUuid); // 添加当前地址的 UUID
  178. if (subAddressUuids.isEmpty()) {
  179. QMessageBox::information(nullptr, "安全验证失败", QString("未找到子地址,请联系安全员确认"));
  180. return;
  181. }
  182. HProjectDao dao = HProjectDao(DatabaseManager::getInstance().getDatabase());
  183. QList<QSharedPointer<HProject>> pendingCheckProjects = dao.getRegistedProjectByAddressUuid(subAddressUuids);
  184. for (const auto &project : pendingCheckProjects) {
  185. dao.updateBlastStatusByUuid(project->getUuid(), BlastStatus::SafeChecked);
  186. }
  187. if (!pendingCheckProjects.isEmpty()) {
  188. QMessageBox::information(nullptr, "安全员确认信息",
  189. QString("收到工程被安全员确认,请刷新查看爆破作业列表"));
  190. return;
  191. }
  192. }
  193. }
  194. }
  195. void MainWindow::setStyleSheets(QPushButton *selectedButton) {
  196. for (auto *b : left_button_station) {
  197. b->setProperty("selected", b == selectedButton);
  198. b->setStyleSheet(b->styleSheet()); // 刷新显示
  199. }
  200. }
  201. // 处理 MQTT 连接成功的槽函数
  202. void MainWindow::onMqttConnected() {
  203. m_isMqttConnected = true;
  204. Logger::getInstance().info("Mqtt connected.");
  205. }
  206. void MainWindow::initialBtnSerial() {
  207. bool success;
  208. serialTool = SerialTool::getInstance(this, &success);
  209. connect(serialTool, &SerialTool::serialPortOpened, this, &MainWindow::onSerialToolCreated);
  210. serialTool->setupSerialPort();
  211. Logger::getInstance().info("Fire buttons initialized");
  212. }
  213. void MainWindow::onSerialToolCreated() {
  214. m_btnSerialInitialized = true;
  215. serialTool->releaseInstance();
  216. qDebug() << ANSI_COLOR_GREEN << "Serial tool initialized" << ANSI_COLOR_RESET;
  217. Logger::getInstance().info("SerialTool initialized");
  218. }
  219. void MainWindow::initialGPSSerial() {
  220. Logger::getInstance().info("开始初始化GPS");
  221. SerialGPSThread *threadGPS = new SerialGPSThread(this);
  222. connect(threadGPS, &SerialGPSThread::storedGNRMCDataUpdated, this, &MainWindow::handleStoredGNRMCData);
  223. threadGPS->start();
  224. }
  225. // 槽函数,用于接收 RMCData 数据
  226. void MainWindow::handleStoredGNRMCData(const RMCData &data) {
  227. if (data.isValid) {
  228. lat = QString::number(data.latitude);
  229. lon = QString::number(data.longitude);
  230. } else {
  231. lat = "定位失败";
  232. lon = "定位失败";
  233. }
  234. ui->labLat->setText("经度: " + lat);
  235. ui->labLon->setText("纬度: " + lon);
  236. labLat = lat;
  237. labLon = lon;
  238. }
  239. void MainWindow::initDateTime() {
  240. timeThread = new TimeUpdateThread(this);
  241. connect(timeThread, &TimeUpdateThread::timeUpdated, this, &MainWindow::onTimeUpdated);
  242. timeThread->start();
  243. }
  244. void MainWindow::onTimeUpdated(const QString &timeString) { ui->dateTimeShow->setText(timeString); }
  245. MainWindow::~MainWindow() {
  246. timeThread->stop();
  247. delete ui;
  248. }
  249. void MainWindow::mousePressEvent(QMouseEvent *event) {
  250. // if (event->button() == Qt::LeftButton) {
  251. // m_dragPosition = event->globalPos() - frameGeometry().topLeft();
  252. // event->accept();
  253. // }
  254. }
  255. void MainWindow::mouseMoveEvent(QMouseEvent *event) {
  256. // if (event->buttons() & Qt::LeftButton) {
  257. // move(event->globalPos() - m_dragPosition);
  258. // event->accept();
  259. // }
  260. }
  261. QList<QString> MainWindow::findAllChildUuids(const QJsonArray &addressArray, const QString targetUuid) {
  262. QList<QString> childrenUuids;
  263. for (const QJsonValue &value : addressArray) {
  264. if (!value.isObject()) continue;
  265. QJsonObject addressObj = value.toObject();
  266. QString currentUuid = addressObj["uuid"].toString();
  267. if (currentUuid == targetUuid) {
  268. // Found the target address, now collect all children UUIDs recursively
  269. if (addressObj.contains("children") && addressObj["children"].isArray()) {
  270. QJsonArray children = addressObj["children"].toArray();
  271. for (const QJsonValue &child : children) {
  272. if (child.isObject()) {
  273. QString childUuid = child.toObject()["uuid"].toString();
  274. childrenUuids.append(childUuid);
  275. // max depth 3
  276. if (child.toObject().contains("children") && child.toObject()["children"].isArray()) {
  277. QJsonArray grandchildren = child.toObject()["children"].toArray();
  278. for (const QJsonValue &grandchild : grandchildren) {
  279. if (grandchild.isObject()) {
  280. QString grandchildUuid = grandchild.toObject()["uuid"].toString();
  281. childrenUuids.append(grandchildUuid);
  282. }
  283. }
  284. }
  285. }
  286. }
  287. return childrenUuids;
  288. }
  289. } else if (addressObj.contains("children") && addressObj["children"].isArray()) {
  290. // Continue searching in children
  291. QJsonArray children = addressObj["children"].toArray();
  292. QList<QString> result = findAllChildUuids(children, targetUuid);
  293. if (!result.isEmpty()) {
  294. return result;
  295. }
  296. }
  297. }
  298. return childrenUuids;
  299. }