firingwidget.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. #include "firingwidget.h"
  2. #include <QDebug>
  3. #include <QJsonArray>
  4. #include <QJsonDocument>
  5. #include <QJsonObject>
  6. #include <QMessageBox>
  7. #include <QNetworkAccessManager>
  8. #include <QNetworkReply>
  9. #include <QNetworkRequest>
  10. #include <QSqlQuery>
  11. #include <QTimeZone>
  12. #include <QUrl>
  13. #include <QUrlQuery>
  14. #include "../backendapimanager.h"
  15. #include "../global.h"
  16. #include "../logger.h"
  17. #include "ui_firingwidget.h"
  18. #define ANSI_COLOR_GREEN "\x1B[32m"
  19. #define ANSI_COLOR_RESET "\x1B[0m"
  20. #define MSG_DATA_TYPE_BLASTING 1
  21. #define MSG_DATA_TYPE_RECORD 2
  22. firingWidget::firingWidget(const int &row, const bool &select, const QString &uuid, QWidget *parent)
  23. : QWidget(parent),
  24. ui(new Ui::firingWidget),
  25. m_curProjUuid(uuid),
  26. m_row(row),
  27. m_select(select),
  28. daoProj(DatabaseManager::getInstance().getDatabase()),
  29. daoDet(DatabaseManager::getInstance().getDatabase()),
  30. daoReg(DatabaseManager::getInstance().getDatabase()) {
  31. ui->setupUi(this);
  32. ui->pushButton_2->setText("立即测试");
  33. ui->textEdit->setStyleSheet("border: none;background: transparent;");
  34. ui->frame_2->setStyleSheet("border: none;background: transparent;");
  35. QFrame *frame = ui->frame_2; // 使用你为 QFrame 设置的对象名称
  36. navProgress = new NavProgress(frame);
  37. ui->verticalLayout->setContentsMargins(0, 30, 0, 0);
  38. ui->scrollArea->setStyleSheet("background: rgba(0, 0, 0, 22); border-radius: 20px;");
  39. ui->verticalLayout->addWidget(navProgress);
  40. m_topic = "hxgc/" + uuid + "/B";
  41. QStringList topics = {m_topic};
  42. m_connectionCheckTimer = new QTimer(this);
  43. m_subscription = mainMqttClient->subscribeToTopic(m_topic);
  44. connect(m_subscription, &QMqttSubscription::messageReceived, this, &firingWidget::handleProjectFiringMqttMessage);
  45. connect(this, &firingWidget::lastStageChanged, this, &firingWidget::handleFiringStageChanged);
  46. connect(this, &firingWidget::updateData, this, &firingWidget::onBlastSuccess);
  47. }
  48. firingWidget::~firingWidget() {
  49. m_subscription->unsubscribe();
  50. delete ui;
  51. }
  52. void firingWidget::sendMqttMessage(const QString &topic, const QByteArray &message) {
  53. qDebug() << ANSI_COLOR_GREEN << "XXX Sending MQTT message to topic:" << topic << "with message:" << message
  54. << ANSI_COLOR_RESET;
  55. if (mainMqttClient->isConnected()) {
  56. mainMqttClient->sendMessage(topic, message, quint8(2), false);
  57. } else {
  58. QMessageBox::warning(nullptr, "MQTT未连接", "MQTT未连接, 无法发送消息: " + topic + ", " + message);
  59. Logger::getInstance().error("MQTT未连接, 无法发送消息" + topic + ", " + message);
  60. }
  61. qDebug() << ANSI_COLOR_GREEN << "XXXy Sending MQTT message to topic:" << topic << "with message:" << message;
  62. }
  63. void firingWidget::startBlasting() {
  64. // 等待3s mqtt连接后再发送mqtt消息
  65. m_lastStage = FiringStages::Starting;
  66. qDebug() << ANSI_COLOR_GREEN << "Firing widget started with topic: 1" << m_topic << ANSI_COLOR_RESET;
  67. emit lastStageChanged(FiringStages::Starting);
  68. qDebug() << ANSI_COLOR_GREEN << "Firing widget started with topic: 2" << m_topic << ANSI_COLOR_RESET;
  69. checkBlasterConnection();
  70. }
  71. // 定间隔检查有没有收到爆破器返回信息
  72. void firingWidget::checkBlasterConnection() {
  73. m_lastMsgTime = QDateTime::currentDateTime();
  74. connect(m_subscription, &QMqttSubscription::messageReceived, this,
  75. [&]() { m_lastMsgTime = QDateTime::currentDateTime(); });
  76. connect(m_connectionCheckTimer, &QTimer::timeout, this, [this]() {
  77. if (m_lastStage == FiringStages::CancelConfirmed || m_lastStage == FiringStages::BlastFinished) {
  78. return;
  79. }
  80. if (m_lastMsgTime.secsTo(QDateTime::currentDateTime()) > 3) {
  81. m_connectionCheckTimer->stop();
  82. QMessageBox msgBox;
  83. msgBox.setWindowTitle("起爆检测测试错误");
  84. msgBox.setText("超时未收到爆破器消息,是否继续等待");
  85. QPushButton *yesButton = msgBox.addButton("继续等待", QMessageBox::YesRole);
  86. QPushButton *noButton = msgBox.addButton("取消", QMessageBox::NoRole);
  87. yesButton->setStyleSheet(
  88. "QPushButton { background-color:rgb(5, 58, 156); color: white; padding: 5px 15px; "
  89. "border-radius: 4px; }");
  90. noButton->setStyleSheet(
  91. "QPushButton { background-color: #f44336; color: white; padding: 5px 15px; "
  92. "border-radius: 4px; }");
  93. msgBox.exec();
  94. if (msgBox.clickedButton() == noButton) {
  95. emit lastStageChanged(FiringStages::ForceCanceled);
  96. return;
  97. }
  98. m_connectionCheckTimer->start(1000);
  99. }
  100. });
  101. qDebug() << ANSI_COLOR_GREEN << "Firing widget initialized with topic: 6" << m_connectionCheckTimer
  102. << ANSI_COLOR_RESET;
  103. m_connectionCheckTimer->start(1000);
  104. }
  105. void firingWidget::on_pushButton_2_clicked() { emit countdown(m_curProjUuid, m_topic, "message"); }
  106. // NOTE: aborted, changed to upload in the smartmine server side.
  107. bool firingWidget::uploadToDanLing(const QJsonObject &jsonObj) {
  108. QString htid = jsonObj["project_htid"].toString();
  109. QString htm = ""; //
  110. QString xmbh = jsonObj["project_xmbh"].toString();
  111. QString sbbh = jsonObj["equipment_sn"].toString();
  112. QString bprysfz = jsonObj["operator_identity"].toString();
  113. QString dwdm = jsonObj["company_code"].toString();
  114. QString xtm = ""; //
  115. QString jd = jsonObj["blast_longitude"].toString();
  116. QString bpsj = jsonObj["blast_time"].toString();
  117. QString wd = jsonObj["blast_latitude"].toString();
  118. QStringList uidList;
  119. QJsonArray regs = jsonObj["regs"].toArray();
  120. for (const auto &reg : regs) {
  121. QJsonObject regObj = reg.toObject();
  122. QJsonArray dets = regObj["dets"].toArray();
  123. for (const auto &det : dets) {
  124. QJsonObject detObj = det.toObject();
  125. uidList.append(detObj["uid"].toString());
  126. }
  127. }
  128. QString uid = uidList.join(",");
  129. QString plainText = QString(
  130. "{\"htid\":\"%1\",\"htm\":\"%2\",\"xmbh\":\"%3\",\"sbbh\":\"%4\","
  131. "\"bprysfz\":\"%5\",\"dwdm\":\"%6\",\"xtm\":\"%7\",\"jd\":\"%8\","
  132. "\"bpsj\":\"%9\",\"wd\":\"%10\",\"uid\":\"%11\"}")
  133. .arg(htid)
  134. .arg(htm)
  135. .arg(xmbh)
  136. .arg(sbbh)
  137. .arg(bprysfz)
  138. .arg(dwdm)
  139. .arg(xtm)
  140. .arg(jd)
  141. .arg(bpsj)
  142. .arg(wd)
  143. .arg(uid);
  144. Des3Encryption des3;
  145. QByteArray key = "jadl12345678912345678912";
  146. QByteArray encryptedData = des3.des3Encrypt(plainText.toUtf8(), key);
  147. QByteArray base64Encoded = encryptedData.toBase64();
  148. QString encodedJson = QUrl::toPercentEncoding(base64Encoded);
  149. QString baseUrl = "http://test.mbdzlg.com/mbdzlgtxzx/servlet/DzlgSysbJsonServlert";
  150. QUrl url(baseUrl);
  151. QUrlQuery query;
  152. query.addQueryItem("param", encodedJson);
  153. url.setQuery(query);
  154. QNetworkAccessManager manager;
  155. QNetworkRequest request(url);
  156. request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  157. QByteArray postData;
  158. QNetworkReply *reply = manager.post(request, postData);
  159. QEventLoop loop;
  160. QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
  161. loop.exec();
  162. if (reply->error() == QNetworkReply::NoError) {
  163. QByteArray responseData = reply->readAll();
  164. qDebug() << "Response:" << QString(responseData);
  165. } else {
  166. qDebug() << "Error:" << reply->errorString();
  167. }
  168. reply->deleteLater();
  169. return true;
  170. }
  171. void firingWidget::handleProjectFiringMqttMessage(const QMqttMessage &message) {
  172. QString msgText = QString("Topic: %1, Message: %2").arg(message.topic().name(), QString(message.payload()));
  173. QTextEdit *textEdit = ui->scrollAreaWidgetContents->findChild<QTextEdit *>("textEdit");
  174. if (textEdit) {
  175. textEdit->append(msgText);
  176. }
  177. int stage = 0;
  178. QJsonDocument jsonDoc = QJsonDocument::fromJson(message.payload());
  179. if (!jsonDoc.isNull() && jsonDoc.isObject()) {
  180. QJsonObject jsonObj = jsonDoc.object();
  181. if (jsonObj.contains("type") && jsonObj["type"].toInt() == MSG_DATA_TYPE_BLASTING) {
  182. if (jsonObj.contains("data") && jsonObj["data"].isObject()) {
  183. QJsonObject relayInfo = jsonObj["data"].toObject();
  184. int status = relayInfo["status"].toInt();
  185. if (ErrorBlastStatus::isErrorStatus(status)) {
  186. Logger::getInstance().error(QString("爆破器返回异常. 工程uuid: %1; 错误code: %2")
  187. .arg(m_curProjUuid, ErrorBlastStatus::getErrorMessage(status)));
  188. QMessageBox::critical(nullptr, "爆破器报错",
  189. QString("错误错误信息: %1").arg(ErrorBlastStatus::getErrorMessage(status)));
  190. sendCancelFiringMsg();
  191. return;
  192. }
  193. stage = relayInfo["stage"].toInt();
  194. if (stage != m_lastStage) {
  195. m_lastStage = stage;
  196. switch (stage) {
  197. case FiringStages::Starting:
  198. navProgress->setState(FiringStages::Starting);
  199. ui->pushButton_2->setText("立即测试");
  200. ui->pushButton_2->setEnabled(false);
  201. break;
  202. case FiringStages::QuickTesting:
  203. navProgress->setState(FiringStages::QuickTesting);
  204. emit updatefiringStage(FiringStages::QuickTesting, m_row);
  205. ui->pushButton_2->setText("立即测试");
  206. ui->pushButton_2->setEnabled(false);
  207. break;
  208. case FiringStages::QuickTestFinished:
  209. // 起爆检测测试检查报错雷管数量,如果有错误,提示用户确认是否继续
  210. if (relayInfo["errorCount"].toInt() > 0) {
  211. m_connectionCheckTimer->stop();
  212. QMessageBox msgBox;
  213. msgBox.setWindowTitle("起爆检测测试错误");
  214. msgBox.setText(QString("起爆检测测试发现 %1 个报错雷管,是否继续起爆?")
  215. .arg(relayInfo["errorCount"].toInt()));
  216. QPushButton *yesButton = msgBox.addButton("确定继续", QMessageBox::YesRole);
  217. QPushButton *noButton = msgBox.addButton("取消", QMessageBox::NoRole);
  218. yesButton->setStyleSheet(
  219. "QPushButton { background-color:rgb(5, 58, 156); color: white; padding: 5px 15px; "
  220. "border-radius: 4px; }");
  221. noButton->setStyleSheet(
  222. "QPushButton { background-color: #f44336; color: white; padding: 5px 15px; "
  223. "border-radius: 4px; }");
  224. msgBox.exec();
  225. if (msgBox.clickedButton() == noButton) {
  226. sendCancelFiringMsg();
  227. return;
  228. }
  229. m_connectionCheckTimer->start();
  230. }
  231. ui->pushButton_2->setEnabled(true);
  232. ui->pushButton_2->setText("充电");
  233. navProgress->setState(FiringStages::QuickTestFinished);
  234. emit progressChanged(FiringStages::QuickTestFinished, m_row);
  235. emit updatefiringStage(FiringStages::QuickTestFinished, m_row);
  236. break;
  237. case FiringStages::NetCharging:
  238. ui->pushButton_2->setEnabled(false);
  239. emit progressChanged(FiringStages::NetCharging, m_row);
  240. emit updatefiringStage(FiringStages::NetCharging, m_row);
  241. ui->pushButton_2->setText("充电");
  242. navProgress->setState(FiringStages::NetCharging);
  243. break;
  244. case FiringStages::NetChargingFinished:
  245. ui->pushButton_2->setEnabled(true);
  246. ui->pushButton_2->setText("起爆");
  247. navProgress->setState(FiringStages::NetChargingFinished);
  248. emit progressChanged(FiringStages::NetChargingFinished, m_row);
  249. emit updatefiringStage(FiringStages::NetChargingFinished, m_row);
  250. break;
  251. case FiringStages::Blasting:
  252. ui->pushButton_2->setEnabled(false);
  253. emit progressChanged(FiringStages::Blasting, m_row);
  254. emit updatefiringStage(FiringStages::Blasting, m_row);
  255. ui->pushButton_2->setText("起爆");
  256. navProgress->setState(FiringStages::Blasting);
  257. break;
  258. case FiringStages::BlastFinished:
  259. ui->pushButton_2->setEnabled(false);
  260. emit progressChanged(FiringStages::BlastFinished, m_row);
  261. emit updatefiringStage(FiringStages::BlastFinished, m_row);
  262. emit updateProjectStatus(m_curProjUuid, BlastStatus::Blasted);
  263. ui->pushButton_2->setText("已完成起爆");
  264. navProgress->setState(FiringStages::BlastFinished);
  265. emit closeFiring(m_curProjUuid, m_row);
  266. break;
  267. case FiringStages::CancelConfirmed:
  268. navProgress->setState(FiringStages::BlastFinished);
  269. ui->pushButton_2->setEnabled(false);
  270. ui->pushButton_2->setText("已确认取消");
  271. emit progressChanged(FiringStages::Starting, m_row);
  272. emit updatefiringStage(FiringStages::Starting, m_row);
  273. emit updateProjectStatus(m_curProjUuid, BlastStatus::Created);
  274. emit closeFiring(m_curProjUuid, m_row);
  275. break;
  276. default:
  277. break;
  278. }
  279. emit lastStageChanged(m_lastStage);
  280. }
  281. }
  282. }
  283. if (jsonObj.contains("type") && jsonObj["type"].toInt() == MSG_DATA_TYPE_RECORD) {
  284. if (jsonObj.contains("data") && jsonObj["data"].isObject()) {
  285. QJsonObject dataObject = jsonObj["data"].toObject();
  286. emit updateData(dataObject);
  287. emit closeFiring(m_curProjUuid, m_row);
  288. }
  289. }
  290. }
  291. }
  292. void firingWidget::onCountdownFinished(const QString &topic, const QString &message) {
  293. qDebug() << "Countdown finished for topic:" << topic << ", message:" << message;
  294. sendMqttMessage(topic, message.toUtf8());
  295. }
  296. void firingWidget::onMqttDisconnected() {
  297. Logger::getInstance().info(QString("Project(%1) firing MQTT disconncted.").arg(m_curProjUuid));
  298. }
  299. void firingWidget::onMqttConnected() {
  300. Logger::getInstance().info(QString("Project(%1) firing MQTT connected.").arg(m_curProjUuid));
  301. }
  302. void firingWidget::onButtonPressedReceived(const QString &topic, const QString &message) {
  303. QByteArray data = "\r\nDISABLE_BUTTON\r\n";
  304. // 调用发送数据的方法
  305. bool success = serialTool->sendData(data);
  306. if (!success) {
  307. Logger::getInstance().error(QString("onButtonPressedReceived: Failed to send data: %1").arg(data));
  308. return;
  309. }
  310. emit countdown(m_curProjUuid, topic, message);
  311. qDebug() << "Data sent successfully";
  312. }
  313. void firingWidget::onSafeChecked(const QString projectUuid) {
  314. if (projectUuid == m_curProjUuid) {
  315. m_lastStage = 3; // 设置为待安全确认状态
  316. emit projSafeCheckSuccess(m_curProjUuid);
  317. emit lastStageChanged(m_lastStage);
  318. qDebug() << ANSI_COLOR_GREEN << "安全确认成功,进入待起爆状态" << ANSI_COLOR_RESET;
  319. } else {
  320. qDebug() << "Project UUID mismatch, expected: " << m_curProjUuid << ", got: " << projectUuid;
  321. }
  322. }
  323. // 状态改变
  324. void firingWidget::handleFiringStageChanged(int newStage) {
  325. qDebug() << ANSI_COLOR_GREEN << "handleFiringStageChanged: " << newStage << ANSI_COLOR_RESET;
  326. QString topic = "hxgc/" + m_curProjUuid + "/P";
  327. QString message;
  328. QString buttonText;
  329. switch (newStage) {
  330. case FiringStages::Starting:
  331. message = "起爆测试";
  332. buttonText = "立即测试";
  333. sendMqttMessage(topic, message.toUtf8());
  334. emit updatefiringStage(FiringStages::Starting, m_row);
  335. break;
  336. case FiringStages::QuickTestFinished:
  337. message = "开始充电";
  338. buttonText = "充电";
  339. sendMqttMessage(topic, message.toUtf8());
  340. break;
  341. case FiringStages::NetChargingFinished:
  342. message = "起爆";
  343. buttonText = "起爆";
  344. break;
  345. case FiringStages::Blasting:
  346. if (!m_select) {
  347. if (connection) {
  348. disconnect(connection);
  349. qDebug() << "Connection disconnected.";
  350. }
  351. if (connectionPress) {
  352. disconnect(connectionPress);
  353. qDebug() << "connectionPress disconnected.";
  354. }
  355. serialTool->releaseInstance();
  356. }
  357. qDebug() << ANSI_COLOR_GREEN << "释放按键 5" << ANSI_COLOR_RESET;
  358. break;
  359. case FiringStages::ForceCanceled:
  360. // 强制取消
  361. sendCancelFiringMsg();
  362. emit updateProjectStatus(m_curProjUuid, BlastStatus::Created);
  363. emit updatefiringStage(FiringStages::ForceCanceled, m_row);
  364. emit closeFiring(m_curProjUuid, m_row);
  365. break;
  366. default:
  367. return;
  368. }
  369. qDebug() << ANSI_COLOR_GREEN << "Stage 值变为: i2" << newStage << ANSI_COLOR_RESET;
  370. if (!message.isEmpty()) {
  371. if (m_lastStage == FiringStages::NetChargingFinished && !m_select) {
  372. bool success2;
  373. serialTool = SerialTool::getInstance(nullptr, &success2);
  374. if (serialTool) {
  375. QByteArray data = "\r\nENABLE_BUTTON\r\n";
  376. bool success = serialTool->sendData(data);
  377. if (success) {
  378. qDebug() << "Data sent successfully";
  379. } else {
  380. qDebug() << "Failed to send data";
  381. }
  382. connection = connect(serialTool, &SerialTool::enableButtonReceived,
  383. [this]() { emit updatefiringStage(10, m_row); });
  384. connectionPress = connect(serialTool, &SerialTool::buttonPressedReceived,
  385. [this, topic, message]() { this->onButtonPressedReceived(topic, message); });
  386. } else {
  387. qDebug() << "serialTool Not found.";
  388. // 在准备起爆状态下 但是没有获取串口
  389. m_lastStage = FiringStages::PendingTriggerButtonClick;
  390. }
  391. } else if (m_lastStage == FiringStages::NetChargingFinished && m_select) {
  392. qDebug() << "多台起爆:待起爆状态";
  393. emit batchFiringSignal(m_curProjUuid);
  394. } else {
  395. qDebug() << "Stage 值变为: " << newStage << "发送消息" << message.toUtf8();
  396. }
  397. }
  398. }
  399. void firingWidget::sendCancelFiringMsg() {
  400. QString message = "取消流程";
  401. QString topic = "hxgc/" + m_curProjUuid + "/P";
  402. sendMqttMessage(topic, message.toUtf8());
  403. }
  404. void firingWidget::on_sendTest_4_clicked() {}
  405. void firingWidget::testOnBlastSuccess(const QJsonObject &jsonObj) { onBlastSuccess(jsonObj); }
  406. // 处理爆破成功,安全验证装置通过MQTT传回的数据
  407. void firingWidget::onBlastSuccess(const QJsonObject &jsonObj) {
  408. Logger::getInstance("blastRecord.log").info(QJsonDocument(jsonObj).toJson(QJsonDocument::Indented));
  409. saveAndUploadRecord(jsonObj);
  410. }
  411. void firingWidget::saveAndUploadRecord(const QJsonObject &jsonObj) {
  412. return; // changed to use server to save the record
  413. QSqlDatabase db = DatabaseManager::getInstance().getDatabase();
  414. if (!db.transaction()) {
  415. Logger::getInstance().critical(QString("Failed to start DB transaction. Error: %1").arg(db.lastError().text()));
  416. return;
  417. }
  418. qDebug() << "Starting transaction for blast record with uuid:" << jsonObj;
  419. HBlastRecord *blastRecord = recordBlastProject(jsonObj);
  420. if (blastRecord == nullptr) {
  421. Logger::getInstance("error_blast_records.log")
  422. .error(QString("Failed to create blast record. projectName: %1, ProjectID: %2; "
  423. "rollback transaction: %3")
  424. .arg(jsonObj["project_name"].toString(), jsonObj["project_htid"].toString(),
  425. db.rollback() ? "success" : "failed"));
  426. return;
  427. }
  428. QList<HBlastEquipmentRecord *> blastEquipmentRecords;
  429. for (const auto &regValue : jsonObj["regs"].toArray()) {
  430. QJsonObject equipmentJsonObject = regValue.toObject();
  431. HBlastEquipmentRecord *hBlastEquipmentRecord =
  432. recordBlastEquipment(blastRecord->getUuid(), equipmentJsonObject);
  433. if (hBlastEquipmentRecord != nullptr) {
  434. blastEquipmentRecords.append(hBlastEquipmentRecord);
  435. }
  436. QList<HBlastRecordDet *> hBlastRecordDets = recordBlastProjectDets(
  437. blastRecord->getUuid(), hBlastEquipmentRecord->getUuid(), equipmentJsonObject["dets"].toArray());
  438. hBlastEquipmentRecord->setDetRecords(hBlastRecordDets);
  439. }
  440. blastRecord->setEquipmentRecords(blastEquipmentRecords);
  441. if (db.commit()) {
  442. Logger::getInstance().info(
  443. QString("Transaction committed successfully. blast_uuid: %1").arg(blastRecord->getUuid()));
  444. } else {
  445. Logger::getInstance().error(QString("Failed to commit transaction: %1. try to rollback: %2")
  446. .arg(db.lastError().text(), db.rollback() ? "success" : "failed"));
  447. return;
  448. }
  449. uploadBlastRecordToServer(blastRecord);
  450. }
  451. void firingWidget::uploadBlastRecordToServer(HBlastRecord *blastRecord) {
  452. if (blastRecord == nullptr) {
  453. return;
  454. }
  455. if (!backendAPIManager::uploadBlastProjectFull(blastRecord->ToJson())) {
  456. Logger::getInstance().error(QString("Failed to upload blast project. data: %1")
  457. .arg(QJsonDocument(blastRecord->ToJson()).toJson(QJsonDocument::Indented)));
  458. }
  459. Logger::getInstance().info(
  460. QString("Blast project uploaded to server successfully. blast_uuid: %1").arg(blastRecord->getUuid()));
  461. }
  462. HBlastRecord *firingWidget::recordBlastProject(const QJsonObject &jsonObj) {
  463. HBlastRecord *record = new HBlastRecord();
  464. record->setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-")));
  465. record->setIsOfflineBlast(jsonObj["is_offline_blast"].toString() == "true");
  466. record->setProjectName(jsonObj["project_name"].toString());
  467. record->setProjectHtid(jsonObj["project_htid"].toString());
  468. record->setProjectXmbh(jsonObj["project_xmbh"].toString());
  469. record->setOperatorName(jsonObj["operator_name"].toString());
  470. record->setPhone(jsonObj["phone"].toString());
  471. record->setOperatorIdentity(jsonObj["operator_identity"].toString());
  472. record->setEquipmentSn(jsonObj["equipment_sn"].toString());
  473. record->setCompanyCode(jsonObj["company_code"].toString());
  474. record->setAppVersion(jsonObj["app_version"].toString());
  475. // TODO: 如何获得坐标
  476. record->setLongitude(jsonObj["blast_longitude"].toString().left(10));
  477. record->setLatitude(jsonObj["blast_latitude"].toString().left(10));
  478. record->setRegDetCount(jsonObj["reg_deto_count"].toString().toInt());
  479. record->setErrorDetCount(jsonObj["error_deto_count"].toString().toInt());
  480. QDateTime blastTime = QDateTime::fromString(jsonObj["blast_time"].toString(), "yyyy-MM-dd hh:mm:ss");
  481. record->setBlastAt(blastTime);
  482. record->setCreatedAt(QDateTime::currentDateTime());
  483. if (daoProj.addHBlastRecord(*record)) {
  484. qDebug() << "Record inserted successfully.";
  485. return record;
  486. } else {
  487. qDebug() << "Failed to insert record.";
  488. delete record;
  489. return nullptr;
  490. }
  491. }
  492. HBlastEquipmentRecord *firingWidget::recordBlastEquipment(const QString blastProjectUuid, const QJsonObject &regObj) {
  493. HBlastEquipmentRecord *recordReg = new HBlastEquipmentRecord();
  494. recordReg->setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-")));
  495. recordReg->setEquipSn(regObj["equipment_sn"].toString());
  496. recordReg->setEquipVersion(regObj["equipment_version"].toString());
  497. recordReg->setRegDetoCount(regObj["reg_deto_count"].toString().toInt());
  498. recordReg->setErrorDetoCount(regObj["error_deto_count"].toString().toInt());
  499. recordReg->setAfterTestBusV(regObj["after_test_bus_v"].toString());
  500. recordReg->setAfterTestBusI(regObj["after_test_bus_i"].toString());
  501. recordReg->setBusLeakageCurrentI(regObj["bus_leakage_current_i"].toString());
  502. recordReg->setNetChargedV(regObj["net_charged_v"].toString());
  503. recordReg->setNetChargedI(regObj["net_charged_i"].toString());
  504. recordReg->setBeforeBlastingV(regObj["before_blasting_v"].toString());
  505. recordReg->setBeforeBlastingI(regObj["before_blasting_i"].toString());
  506. recordReg->setRecordUuid(blastProjectUuid);
  507. recordReg->setCreatedAt(QDateTime::currentDateTime());
  508. if (!daoReg.saveHBlastRegRecord(*recordReg)) {
  509. Logger::getInstance().error(QString("Failed to save HBlastRegRecord: %1").arg(recordReg->getEquipSn()));
  510. delete recordReg;
  511. return nullptr;
  512. }
  513. return recordReg;
  514. }
  515. QList<HBlastRecordDet *> firingWidget::recordBlastProjectDets(const QString projectUuid, const QString equipmentUuid,
  516. const QJsonArray detsArray) {
  517. QList<HBlastRecordDet *> recordDets;
  518. for (const auto &detValue : detsArray) {
  519. QJsonObject detObj = detValue.toObject();
  520. HBlastRecordDet *recordDet = new HBlastRecordDet();
  521. recordDet->setId(0);
  522. recordDet->setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-")));
  523. recordDet->setOutCode(detObj["out_code"].toString());
  524. recordDet->setInnerCode(detObj["in_code"].toString());
  525. recordDet->setUid(detObj["uid"].toString());
  526. recordDet->setStatus(detObj["status"].toString());
  527. recordDet->setFreq(detObj["freq"].toString());
  528. recordDet->setDelayTime(detObj["delay_time"].toString());
  529. recordDet->setTag(detObj["tag"].toString());
  530. recordDet->setBlastRecordUuid(projectUuid);
  531. recordDet->setEquipmentRecordUuid(equipmentUuid);
  532. recordDet->setCreatedAt(QDateTime::currentDateTime());
  533. if (daoDet.addHBlastRecordDet(*recordDet)) {
  534. recordDets.append(recordDet);
  535. } else {
  536. Logger::getInstance().error(QString("Failed to insert record det. data %1")
  537. .arg(QJsonDocument(recordDet->ToJson()).toJson(QJsonDocument::Compact)));
  538. delete recordDet;
  539. continue;
  540. }
  541. }
  542. return recordDets;
  543. }