firingwidget.cpp 28 KB

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