firingwidget.cpp 28 KB

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