#include "firingwidget.h" #include "ui_firingwidget.h" #include "../countdownwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "../global.h" #define ANSI_COLOR_GREEN "\x1B[32m" #define ANSI_COLOR_RESET "\x1B[0m" firingWidget::firingWidget(const int &row, const bool &select, const QString &uuid, QWidget *parent) : QWidget(parent), ui(new Ui::firingWidget), m_uuid(uuid), m_row(row), m_select(select), dao(DatabaseManager::getInstance().getDatabase()), daoDet(DatabaseManager::getInstance().getDatabase()), daoReg(DatabaseManager::getInstance().getDatabase()) { ui->setupUi(this); ui->pushButton_2->setText("立即测试"); ui->textEdit->setStyleSheet("border: none;background: transparent;"); ui->frame_2->setStyleSheet("border: none;background: transparent;"); QFrame *frame = ui->frame_2; // 使用你为 QFrame 设置的对象名称 navProgress = new NavProgress(frame); ui->verticalLayout->setContentsMargins(0, 30, 0, 0); ui->scrollArea->setStyleSheet("background: rgba(0, 0, 0, 22); border-radius: 20px;"); ui->verticalLayout->addWidget(navProgress); mqttThread = new MqttThread(this); QStringList topics = {"hxgc/" + uuid + "/B"}; mqttThread->setConnectionInfo("114.55.233.194", 1883, "hxgc", "hxgc123456", "P" + uuid, topics); connect(mqttThread, &MqttThread::mqttConnected, this, &firingWidget::onMqttConnected); mqttThread->start(); connect(mqttThread, &MqttThread::messageAndTopicReceived, this, &firingWidget::handleMessageAndTopic); connect(this, &firingWidget::lastStageChanged, this, &firingWidget::onLastStageChanged); connect(this, &firingWidget::updateData, this, &firingWidget::onBlastSucess); startBlasting(); } firingWidget::~firingWidget() { delete ui; } void firingWidget::sendMqttMessage(const QString &topic, const QByteArray &message) { if (mqttThread && m_isMqttConnected) { emit mqttThread->sendMessageRequested(topic, message); } else { qDebug() << "MQTT 未连接,无法发送消息"; } } void firingWidget::startBlasting() { // TODO 检测起爆器是否在线 QTimer::singleShot(1000, this, [this]() { lastStage=0; emit lastStageChanged(0); }); } void firingWidget::on_pushButton_2_clicked() { emit countdown(m_uuid, topic, "message"); } bool firingWidget::uploadToDanLing(const QJsonObject &jsonObj) { QString htid = jsonObj["project_htid"].toString(); QString htm = ""; // QString xmbh = jsonObj["project_xmbh"].toString(); QString sbbh = jsonObj["equipment_sn"].toString(); QString bprysfz = jsonObj["operator_identity"].toString(); QString dwdm = jsonObj["company_code"].toString(); QString xtm = ""; // QString jd = jsonObj["blast_longitude"].toString(); QString bpsj = jsonObj["blast_time"].toString(); QString wd = jsonObj["blast_latitude"].toString(); QStringList uidList; QJsonArray regs = jsonObj["regs"].toArray(); for (const auto ® : regs) { QJsonObject regObj = reg.toObject(); QJsonArray dets = regObj["dets"].toArray(); for (const auto &det : dets) { QJsonObject detObj = det.toObject(); uidList.append(detObj["uid"].toString()); } } QString uid = uidList.join(","); QString plainText = QString("{\"htid\":\"%1\",\"htm\":\"%2\",\"xmbh\":\"%3\",\"sbbh\":\"%4\"," "\"bprysfz\":\"%5\",\"dwdm\":\"%6\",\"xtm\":\"%7\",\"jd\":\"%8\"," "\"bpsj\":\"%9\",\"wd\":\"%10\",\"uid\":\"%11\"}") .arg(htid) .arg(htm) .arg(xmbh) .arg(sbbh) .arg(bprysfz) .arg(dwdm) .arg(xtm) .arg(jd) .arg(bpsj) .arg(wd) .arg(uid); Des3Encryption des3; QByteArray key = "jadl12345678912345678912"; QByteArray encryptedData = des3.des3Encrypt(plainText.toUtf8(), key); QByteArray base64Encoded = encryptedData.toBase64(); QString encodedJson = QUrl::toPercentEncoding(base64Encoded); QString baseUrl = "http://test.mbdzlg.com/mbdzlgtxzx/servlet/DzlgSysbJsonServlert"; QUrl url(baseUrl); QUrlQuery query; query.addQueryItem("param", encodedJson); url.setQuery(query); QNetworkAccessManager manager; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QByteArray postData; QNetworkReply *reply = manager.post(request, postData); QEventLoop loop; QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); if (reply->error() == QNetworkReply::NoError) { QByteArray responseData = reply->readAll(); qDebug() << "Response:" << QString(responseData); } else { qDebug() << "Error:" << reply->errorString(); } reply->deleteLater(); return true; } bool firingWidget::recordBlastReg(const QJsonObject &jsonObj) { QJsonArray regsArray = jsonObj["regs"].toArray(); for (const auto ®Value : regsArray) { QJsonObject regObj = regValue.toObject(); HBlastRegRecord recordReg; reg_uuid = QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-")); recordReg.setUuid(reg_uuid); recordReg.setEquipSn(regObj["equipment_sn"].toString()); recordReg.setEquipVersion(regObj["equipment_version"].toString()); recordReg.setRegDetoCount(regObj["reg_deto_count"].toString().toInt()); recordReg.setErrorDetoCount(regObj["error_deto_count"].toString().toInt()); recordReg.setAfterTestBusV(regObj["after_test_bus_v"].toString()); recordReg.setAfterTestBusI(regObj["after_test_bus_i"].toString()); recordReg.setBusLeakageCurrentI(regObj["bus_leakage_current_i"].toString()); recordReg.setNetChargedV(regObj["net_charged_v"].toString()); recordReg.setNetChargedI(regObj["net_charged_i"].toString()); recordReg.setBeforeBlastingV(regObj["before_blasting_v"].toString()); recordReg.setBeforeBlastingI(regObj["before_blasting_i"].toString()); recordReg.setRecordUuid(blast_uuid); recordReg.setCreatedAt(QDateTime::currentDateTime()); // 插入数据到数据库 if (!daoReg.saveHBlastRegRecord(recordReg)) { return false; } } return true; } void firingWidget::handleMessageAndTopic(const QByteArray &message, const QMqttTopicName &topic) { QString msgText = QString("Topic: %1, Message: %2").arg(topic.name(), QString(message)); QTextEdit *textEdit = ui->scrollAreaWidgetContents->findChild("textEdit"); if (textEdit) { textEdit->append(msgText); } int stage = 0; QJsonDocument jsonDoc = QJsonDocument::fromJson(message); if (!jsonDoc.isNull() && jsonDoc.isObject()) { QJsonObject jsonObj = jsonDoc.object(); if (jsonObj.contains("type") && jsonObj["type"].toInt() == 1) { if (jsonObj.contains("data") && jsonObj["data"].isObject()) { QJsonObject dataObject = jsonObj["data"].toObject(); stage = dataObject["stage"].toInt(); if (stage != lastStage) { lastStage = stage; switch (stage) { case 0: navProgress->setState(0); ui->pushButton_2->setText("立即测试"); ui->pushButton_2->setEnabled(false); break; case 1: navProgress->setState(1); emit progressChanged(1, m_row); emit updateBlastStatus(1, m_row); ui->pushButton_2->setText("立即测试"); ui->pushButton_2->setEnabled(false); break; case 2: ui->pushButton_2->setEnabled(true); emit progressChanged(2, m_row); emit updateBlastStatus(2, m_row); qDebug() << "stage:" << stage; ui->pushButton_2->setText("充电"); navProgress->setState(2); break; case 3: ui->pushButton_2->setEnabled(false); emit progressChanged(3, m_row); emit updateBlastStatus(3, m_row); ui->pushButton_2->setText("充电"); navProgress->setState(3); break; case 4: ui->pushButton_2->setEnabled(true); emit progressChanged(4, m_row); emit updateBlastStatus(4, m_row); ui->pushButton_2->setText("起爆"); navProgress->setState(4); break; case 5: ui->pushButton_2->setEnabled(false); emit progressChanged(5, m_row); emit updateBlastStatus(5, m_row); emit updateButton(5, m_row); ui->pushButton_2->setText("起爆"); navProgress->setState(5); break; case 6: ui->pushButton_2->setEnabled(false); emit progressChanged(6, m_row); emit updateBlastStatus(6, m_row); emit updateProjectStatus(m_uuid); ui->pushButton_2->setText("已完成起爆"); navProgress->setState(6); break; case 7: qDebug() << "status:" << stage; ui->pushButton_2->setEnabled(false); emit progressChanged(0, m_row); // 发送进度值 emit updateBlastStatus(0, m_row); // 正在测试 ui->pushButton_2->setText("已完成起爆"); navProgress->setState(6); break; default: break; } emit lastStageChanged(lastStage); } } } if (jsonObj.contains("type") && jsonObj["type"].toInt() == 2) { if (jsonObj.contains("data") && jsonObj["data"].isObject()) { QJsonObject dataObject = jsonObj["data"].toObject(); emit updateData(dataObject); emit closeFiring(m_uuid); } } } } void firingWidget::onCountdownFinished(const QString &topic, const QString &message) { sendMqttMessage(topic, message.toUtf8()); } void firingWidget::onMqttConnected() { m_isMqttConnected = true; } void firingWidget::onButtonPressedReceived(const QString &topic, const QString &message) { QByteArray data = "\r\nDISABLE_BUTTON\r\n"; // 调用发送数据的方法 bool success = serialTool->sendData(data); if (success) { qDebug() << "Data sent successfully"; } else { qDebug() << "Failed to send data"; } emit countdown(m_uuid, topic, message); } // 状态改变 void firingWidget::onLastStageChanged(int newStage) { QString topic = "hxgc/" + m_uuid + "/P"; QString message; QString buttonText; switch (lastStage) { case 0: message = "起爆测试"; buttonText = "立即测试"; sendMqttMessage(topic, message.toUtf8()); break; case 2: message = "开始充电"; buttonText = "充电"; sendMqttMessage(topic, message.toUtf8()); break; case 4: message = "起爆"; buttonText = "起爆"; break; case 5: if (!m_select) { if (connection) { disconnect(connection); qDebug() << "Connection disconnected."; } if (connectionPress) { disconnect(connectionPress); qDebug() << "connectionPress disconnected."; } serialTool->releaseInstance(); } qDebug() << ANSI_COLOR_GREEN << "释放按键 5" << ANSI_COLOR_RESET; break; default: return; } if (!message.isEmpty()) { if (lastStage == 4 && !m_select) { bool success2; serialTool = SerialTool::getInstance(nullptr, &success2); if (serialTool) { QByteArray data = "\r\nENABLE_BUTTON\r\n"; bool success = serialTool->sendData(data); if (success) { qDebug() << "Data sent successfully"; } else { qDebug() << "Failed to send data"; } connection = connect(serialTool, &SerialTool::enableButtonReceived, [this]() { emit updateBlastStatus(10, m_row); }); connectionPress = connect(serialTool, &SerialTool::buttonPressedReceived, [this, topic, message]() { this->onButtonPressedReceived(topic, message); }); } else { qDebug() << "serialTool Not fond."; // 在准备起爆状态下 但是没有获取串口 lastStage = 10; } } else if (lastStage == 4 && m_select) { qDebug() << "多台起爆:待起爆状态"; emit selectSignal(m_uuid); } else { //???? qDebug() << "Stage 值变为: " << newStage << "发送消息" << message.toUtf8(); } } } void firingWidget::cancelBlasting() { QString message = "取消流程"; if (!message.isEmpty()) { sendMqttMessage(topic, message.toUtf8()); } } void firingWidget::on_sendTest_4_clicked() { // qDebug() << "navProgress 取消流程"; // QString message = "取消流程"; // if (!message.isEmpty()) { // sendMqttMessage(topic, message.toUtf8()); // } lat = labLat; lon = labLon; QSqlDatabase db = DatabaseManager::getInstance().getDatabase(); if (!db.transaction()) { qDebug() << "Failed to start transaction:" << db.lastError().text(); // return false; } // 假设的 JSON 数据 QString jsonData = R"( { "blast_latitude": "30.2039", "project_xmbh": "", "app_version": "1.52", "operator_identity": "330781198509079292", "blast_time": "2017-07-12 15:00:15", "regs": [ { "net_charged_v": "13499", "after_test_bus_i": "0", "after_test_bus_v": "7006", "equipment_version": "AK01_V3.2_240726", "bus_leakage_current_i": "0", "reg_deto_count": "2", "before_blasting_i": "1", "error_deto_count": "2", "net_charged_i": "0", "before_blasting_v": "13484", "dets": [ { "uid": "24211104F18004", "freq": "80000", "out_code": "2411104F18000", "tag": "1-1-1", "in_code": "045AC8360A4C0061", "status": "0x03", "delay_time": "0.0" }, { "uid": "24211104F18005", "freq": "80000", "out_code": "2411104F18001", "tag": "1-2-1", "in_code": "055AC8360A4C0088", "status": "0x03", "delay_time": "20.0" } ], "equipment_sn": "F34A0000001" } ], "reg_deto_count": "2", "project_name": "sidf", "operator_name": "樊工", "phone": "18611112222", "project_htid": "", "company_code": "3701234300003", "blast_longitude": "120.196", "error_deto_count": "2", "equipment_sn": "F34A0000001" } )"; QJsonDocument doc = QJsonDocument::fromJson(jsonData.toUtf8()); QJsonObject jsonObj = doc.object(); // 创建 HBlastRecord 对象 HBlastRecord record; record.setProjectName(jsonObj["project_name"].toString()); record.setProjectHtid(jsonObj["project_htid"].toString()); record.setProjectXmbh(jsonObj["project_xmbh"].toString()); record.setOperatorName(jsonObj["operator_name"].toString()); record.setPhone(jsonObj["phone"].toString()); record.setOperatorIdentity(jsonObj["operator_identity"].toString()); record.setEquipmentSn(jsonObj["equipment_sn"].toString()); record.setCompanyCode(jsonObj["company_code"].toString()); record.setAppVersion(jsonObj["app_version"].toString()); // record.setLongitude(jsonObj["blast_longitude"].toString()); // record.setLatitude(jsonObj["blast_latitude"].toString()); record.setLongitude(lat); record.setLatitude(lon); record.setRegDetCount(jsonObj["reg_deto_count"].toInt()); record.setErrorDetCount(jsonObj["error_deto_count"].toInt()); record.setBlastAt(QDateTime::fromString(jsonObj["blast_time"].toString(), "yyyy-MM-dd hh:mm:ss")); record.setCreatedAt(QDateTime::currentDateTime()); qDebug() << "currentDateTime." << QDateTime::currentDateTime(); record.setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-"))); // if (dao.addHBlastRecord(record)) { // qDebug() << "Record inserted successfully."; // }else{ // qDebug() << "Failed to insert record."; // } // if (!addDetData(jsonObj)) { // qDebug() << "Insert failed for UID:"; // 假设 record 有 uid 成员 // if (db.rollback()) { // qDebug() << "Transaction rolled back successfully."; // } else { // qDebug() << "Failed to roll back transaction:" << db.lastError().text(); // } // } // if (!addRegData(jsonObj)) { // if (db.rollback()) { // qDebug() << "Transaction rolled back successfully."; // } else { // qDebug() << "Failed to roll back transaction:" << db.lastError().text(); // } // } // db.commit(); if (lat == "定位失败" && lat == "未知" && lon == "定位失败" && lon == "未知") { // 数据出本地 不传丹灵 if (dao.addHBlastRecord(record)) { qDebug() << "Record inserted successfully."; } else { qDebug() << "Failed to insert record."; } if (!recordDetsData(jsonObj)) { qDebug() << "Insert failed for UID:"; // 假设 record 有 uid 成员 if (db.rollback()) { qDebug() << "Transaction rolled back successfully."; } else { qDebug() << "Failed to roll back transaction:" << db.lastError().text(); } } if (!recordBlastReg(jsonObj)) { if (db.rollback()) { qDebug() << "Transaction rolled back successfully."; } else { qDebug() << "Failed to roll back transaction:" << db.lastError().text(); } } db.commit(); } // danUpload(jsonObj); // if (db.commit()) { // qDebug() << "Transaction committed successfully."; // } else { // qDebug() << "Failed to commit transaction:" << db.lastError().text(); // } } // 处理爆破成功,安全验证装置通过MQTT传回的数据 void firingWidget::onBlastSucess(const QJsonObject &jsonObj) { Logger::getInstance().info(QString("收到爆破完成回传记录. data: %1").arg(QJsonDocument(jsonObj).toJson(QJsonDocument::Indented))); blast_uuid = QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-")); lat = labLat; lon = labLon; saveDataToLocalDB(jsonObj); uploadToServer(jsonObj); if (lat == "定位失败" && lat == "未知" && lon == "定位失败" && lon == "未知"){ QMessageBox::critical(nullptr, "错误", "未获取有效定位数据,数据将暂不上传丹灵"); // 数据:存本地 不传丹灵 } // TODO location数据如果错误,不提交丹灵 // danUpload(jsonObj); // if (db.commit()) { // qDebug() << "Transaction committed successfully."; // } else { // qDebug() << "Failed to commit transaction:" << db.lastError().text(); // } } /* Id int `json:"-" comment:"主键编码"` // 主键编码 Uuid string `json:"uuid" comment:""` ProjectName string `json:"project_name" comment:"工程名称"` ProjectHtid string `json:"project_htid" comment:"合同编号"` ProjectXmbh string `json:"project_xmbh" comment:"项目编号"` OperatorName string `json:"operator_name" comment:"操作员"` Phone string `json:"phone" comment:"操作员电话"` OperatorIdentity string `json:"operator_identity" comment:"操作员身份证"` EquipmentSn string `json:"equipment_sn" comment:"设备序列号"` CompanyCode string `json:"company_code" comment:"公司代码"` AppVersion string `json:"app_version" comment:"app版本"` Longitude string `json:"blast_longitude" comment:"经度"` Latitude string `json:"blast_latitude" comment:"纬度"` EquipmentCount string `json:"equipment_count" comment:"设备数量"` RegDetCount string `json:"reg_deto_count" comment:"注册雷管数量"` ErrorDetCount string `json:"error_deto_count" comment:"异常雷管数量"` BlastAt string `json:"blast_time" comment:"爆破时间"` Regs []HBlastRecordEquipmentInsertReq `json:"regs"` WBlasterId string `json:"w_blaster_id"` */ void firingWidget::uploadToServer(const QJsonObject &jsonObj) { // upload blast project // upload blast reg dets // upload blast dets data } void firingWidget::saveDataToLocalDB(const QJsonObject &jsonObj) { QSqlDatabase db = DatabaseManager::getInstance().getDatabase(); if (!db.transaction()) { Logger::getInstance().critical(QString("Failed to start DB trasaction. Error: %1").arg(db.lastError().text())); return; } if (!recordBlastData(jsonObj)) { if (db.rollback()) { qDebug() << "Transaction rolled back successfully."; } else { qDebug() << "Failed to roll back transaction:" << db.lastError().text(); } } if (!recordBlastReg(jsonObj)) { if (db.rollback()) { qDebug() << "Transaction rolled back successfully."; } else { qDebug() << "Failed to roll back transaction:" << db.lastError().text(); } } if (!recordDetsData(jsonObj)) { qDebug() << "Insert failed for UID:"; // 假设 record 有 uid 成员 if (db.rollback()) { qDebug() << "Transaction rolled back successfully."; } else { qDebug() << "Failed to roll back transaction:" << db.lastError().text(); } } db.commit(); } HBlastRecord* firingWidget::recordBlastData(const QJsonObject &jsonObj) { HBlastRecord record; record.setProjectName(jsonObj["project_name"].toString()); record.setProjectHtid(jsonObj["project_htid"].toString()); record.setProjectXmbh(jsonObj["project_xmbh"].toString()); record.setOperatorName(jsonObj["operator_name"].toString()); record.setPhone(jsonObj["phone"].toString()); record.setOperatorIdentity(jsonObj["operator_identity"].toString()); record.setEquipmentSn(jsonObj["equipment_sn"].toString()); record.setCompanyCode(jsonObj["company_code"].toString()); record.setAppVersion(jsonObj["app_version"].toString()); record.setLongitude(jsonObj["blast_longitude"].toString()); record.setLatitude(jsonObj["blast_latitude"].toString()); // record.setLongitude(lat); // record.setLatitude(lon); record.setRegDetCount(jsonObj["reg_deto_count"].toString().toInt()); record.setErrorDetCount(jsonObj["error_deto_count"].toString().toInt()); QDateTime blastTime = QDateTime::fromString(jsonObj["blast_time"].toString(), "yyyy-MM-dd hh:mm:ss +08:00"); blastTime.setTimeZone(QTimeZone(QByteArrayLiteral("Asia/Shanghai"))); record.setBlastAt(blastTime); record.setCreatedAt(QDateTime::currentDateTime()); qDebug() << "currentDateTime." << QDateTime::currentDateTime(); record.setUuid(blast_uuid); if (dao.addHBlastRecord(record)) { qDebug() << "Record inserted successfully."; return &record; } else { qDebug() << "Failed to insert record."; return nullptr; } } bool firingWidget::recordDetsData(const QJsonObject &jsonObj) { QJsonArray regsArray = jsonObj["regs"].toArray(); for (const auto ®Value : regsArray) { QJsonObject regObj = regValue.toObject(); QJsonArray detsArray = regObj["dets"].toArray(); for (const auto &detValue : detsArray) { QJsonObject detObj = detValue.toObject(); HBlastRecordDet recordDet; recordDet.setId(0); recordDet.setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-"))); recordDet.setOutCode(detObj["out_code"].toString()); recordDet.setInnerCode(detObj["in_code"].toString()); recordDet.setUid(detObj["uid"].toString()); recordDet.setStatus(detObj["status"].toString()); recordDet.setFreq(detObj["freq"].toString()); recordDet.setDelayTime(detObj["delay_time"].toString()); recordDet.setTag(detObj["tag"].toString()); recordDet.setCreatedAt(QDateTime::currentDateTime()); recordDet.setBlastRecordId(blast_uuid); recordDet.setRegId(reg_uuid); recordDet.setCreatedAt(QDateTime::currentDateTime()); if (!daoDet.addHBlastRecordDet(recordDet)) { return false; } } } return true; }