From: kyz Date: Fri, 28 Aug 2026 03:57:08 +0000 (+0800) Subject: init X-Git-Url: http://kyz.pub/gitweb/?a=commitdiff_plain;h=db4400bc2ee4df44a9c0252da1f6f24f893991bd;p=yn%2Fagridetect_ui.git init --- db4400bc2ee4df44a9c0252da1f6f24f893991bd diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f36a984 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +build/ +*.o +~* +tags +cscope.* +ui_* +qrc_* +moc_* +.gitignore +*stash +Makefile +agridetect_ui + diff --git a/agridetect_ui.pro b/agridetect_ui.pro new file mode 100644 index 0000000..3a0ce0f --- /dev/null +++ b/agridetect_ui.pro @@ -0,0 +1,50 @@ +QT += core gui dbus + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = agridetect_ui +TEMPLATE = app + +DEFINES += QT_DEPRECATED_WARNINGS + +CONFIG += c++11 + +SOURCES += \ + main.cpp \ + poweronwindow.cpp \ + homewindow.cpp \ + loginpage.cpp \ + testpage.cpp \ + recordpage.cpp \ + settingpage.cpp \ + debugpage.cpp \ + selftestpage.cpp \ + dbusmanager.cpp + +HEADERS += \ + poweronwindow.h \ + homewindow.h \ + loginpage.h \ + testpage.h \ + recordpage.h \ + settingpage.h \ + debugpage.h \ + selftestpage.h \ + dbusmanager.h + +FORMS += \ + poweron.ui \ + home.ui \ + login.ui \ + test.ui \ + record.ui \ + setting.ui \ + debug.ui \ + selftest.ui + +RESOURCES += \ + res/test.qrc + +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target diff --git a/dbus.md b/dbus.md new file mode 100644 index 0000000..34ada24 --- /dev/null +++ b/dbus.md @@ -0,0 +1,403 @@ +# Qt 与主控通信协议 + +## 1. 通信架构 + +| 角色 | 运行端 | 说明 | +|------|--------|------| +| **Server(服务端)** | 主控设备端(C 程序) | 提供 DBus 服务,处理客户端请求,维护设备状态 | +| **Client(客户端)** | Qt UI 界面 | 定时发送查询指令,接收响应,更新用户界面 | + +### 通信模式 + +采用 **Client 主动轮询** 模式: + +``` +Qt Client 主控 Server + | | + | 定时 query_state | + |------------------->| + | | + | JSON 状态响应 | + |<-------------------| + | | + | 用户操作 execute | + |------------------->| + | | + | JSON 执行结果 | + |<-------------------| +``` + +1. Qt 客户端**定时**(如 500ms)发送 `query_state` 查询指令 +2. 服务端返回当前完整设备状态 JSON,Qt 根据状态刷新界面 +3. 用户点击按钮时,Qt 发送 `execute` 指令携带操作参数 +4. 服务端执行动作并返回结果 + +--- + +## 2. DBus 接口定义 + +| 项目 | 值 | +|------|-----| +| **Service** | `com.yn.ui` | +| **Path** | `/com/yn/ui` | +| **Interface** | `com.yn.ui.interface` | + +### Methods + +| 方法名 | 功能 | 参数(输入) | 返回值(输出) | +|--------|------|-------------|---------------| +| `query_state` | 查询设备当前完整状态 | 无(或空 JSON) | 设备状态 JSON 字符串 | +| `query_params` | 查询设备当前参数 | 无(或空 JSON) | 设备参数 JSON 字符串 | +| `update_params` | 更新设备参数 | 设备参数 JSON 字符串 | 执行结果 JSON 字符串 | +| `user_cmd` | 执行用户操作指令 | 操作 JSON 字符串 | 执行结果 JSON 字符串 | + +> 所有参数和返回值均为 **JSON 字符串**(DBus 类型为 `s` / string)。 + +--- + +## 3. JSON 通用格式规范 + +### 3.1 请求通用结构 + +读取状态请求示例 + +```json +{ + "cmd": "query_state", +} +``` +读取参数请求示例 + +```json +{ + "cmd": "query_params", +} +``` + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `cmd` | string | 是 | 命令名 | + + +### 3.2 响应通用结构 + +状态响应示例 + +```json +{ + "cmd": "query_state", + "code": 0, + "data": { + //根据不同状态,返回不同内容 + "state": 0, + "msg": "init", + "result": [], + "timer": {}, + "step": 0, + "fault": 0, + "dbg_act": {} + } +} +``` + +设备状态响应字段说明 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `cmd` | string | 是 | 对应请求的命令名 | +| `code` | int | 是 | 错误码,0 成功 | +| `data` | object | 是 | 响应数据体 | + +设备状态响应data字段说明 + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `state` | int | 是 | 状态码:0-7 见设备状态码定义 | +| `msg` | string | 是 | 状态描述信息 见设备状态码定义| +| `result` | array | 否 | 测试结果数组 | +| `timer` | object | 否 | 测试倒计时信息 | +| `step` | int | 否 | 当前测试步骤 | +| `fault` | int | 否 | 故障码,见设备状态码定义 | +| `dbg_act` | object | 否 | 调试动作编号,1-10,测试结果:0:待测试,1:测试中,2:测试通过,-1:测试失败 | + +共 **8 种**工作状态: + +| code | msg | 说明 | +|---|------|--| +| 0 | `init` | 开机初始化中 | +| 1 | `selftest` | 开机自检中 | +| 2 | `selftest_failed` | 开机自检失败 | +| 3 | `ready` | 就绪 | +| 4 | `test` | 检测中 | +| 5 | `test_pause` | 检测暂停 | +| 6 | `test_fault` | 检测异常退出 | +| 7 | `debug` | 调试模式 | + + +init 状态 +开机后设备进入初始状态,直到自检开始。 +```json +"data":{ + "state":0, + "msg":"init" +} +``` + +selftest 状态 +自检状态,设备会自动进行自检,测试结果通过result字段返回, 返回的是一个数组, +每个数组元素为对应设备的测试结果,0:待测试,1:测试通过,-1:测试失败,2:测试中, + +**外设列表,对应result字段的数组第一个到第7个元素:** +| ID| 键名 | 设备名称 | +|---|------------|----------| +| 1 |`vortex` | 涡动仪 | +| 2 |`centrifuge` | 离心机 | +| 3 |`pipette_1` | 移液器 1 | +| 4 |`pipette_2` | 移液器 2 | +| 5 |`pipette_3` | 移液器 3 | +| 6 |`pipette_4` | 移液器 4 | +| 7 |`robot_arm` | 机械臂 | + +**result字段定义:** +| 值 | 含义 | +|----|------| +| 0 | 未检测 / 等待检测 | +| 1 | 检测通过 | +| 2 | 检测中 | +| -1 | 检测失败 | + +```json +"data":{ + "state":1, + "msg":"selftest", + "res":[ 1,1,1,1,-1,1,2,0], //测试状态,0:待测试,1:测试通过,-1:测试失败,2:测试中, +} +``` + +selftest_failed 状态 +测试结束,全部res字段为 1(成功) 或 -1 (失败),无 0 和 2 的状态 +```json +"data":{ + "state":2, + "msg":"selftest_failed", + "res":[ 1,1,1,1,-1,1,1,1,0], //自测结果,2:pass, -1:fail, 0:未测试 +} +``` + +ready 状态 +自检完成后进入就绪状态,等待用户操作。 +```json +"data":{ + "state":3, + "msg":"ready" +} +``` + +test 状态 +检测状态,就绪状态下,用户点击开始测试,进入检测状态 +step字段表示当前进行到的测试步骤,从1开始,到完成。 +对于离心机和涡动仪,total_time 和remain_time测试倒计时信息,单位为秒。 + +step对应的动作说明: +| `step` | 动作 | 说明 | +|------|--------|------| +| 1 | 加提取液 | 机器臂将离心管移动到在移液器1工位, 移液器吸取提取液,加入离心管中 | +| 2 | 涡动 | 机器臂将离心管移动到涡动仪工位, 启动涡动仪,开始计时,时间到了关闭涡动仪 | +| 3 | 离心 | 机器臂将离心管移动到离心机工位, 启动离心机,开始计时,时间到了关闭离心机 | +| 4 | 提取样本液 | 机器臂将离心管移动到移液器2工位, 从离心管中提取样本液,机器臂将离心管移动到废弃仓工位,机器臂将新的离心管移动到移液器3工位,移液器3加入样本液 | +| 5 | 加提取液 | 机器臂将样本液离心管移动到移液器3工位, 移液器吸取提取液,加入样本液中 | +| 6 | 涡动 | 机器臂将离心管移动到涡动仪工位, 启动涡动仪,开始计时,时间到了关闭涡动仪 | +| 7 | 提取样本液 | 机器臂将离心管移动到移液器4工位, 从离心管中提取样本液,机器臂将离心管移动到废弃仓工位 | +| 8 | 提取样本液 | 移液器4 将样本滴入试纸 | +| 9 | 等待结果 | 计时等待8分钟 | +| 10 | 拍照分析 | 机器臂移动到移液器4工位, 拍照分析样本结果 | +| 11 | 检测完成 | 显示检测结果 | + +```json +"data":{ + "state":4, + "msg":"test", + "step":2, //测试中当前位置,从1开始: 1--n + "timer":{ + "total":120, //测试总时间,单位:秒 + "remain":10, //剩余时间,单位:秒 + } +} +``` + +test_fault 状态 +当检测中出现故障,状态进入检测失败状态,显示当前故障原因 +**故障码(`code`)定义:** + +| fault | 含义 | +|--------|------| +| `0` | 无故障 | +| `-1` | 机械臂通信故障 | +| `-2` | 移液器控制故障 | +| `-3` | 涡动仪控制故障 | +| `-4` | 离心机控制故障 | +| `-5` | 样本未就绪 | +| `-6` | 样本放置目的地失败 | +| `-7` | 未知 / 其他故障 | +| `-100` | 自检失败(通用) | +| `-200` | 自动检测异常(通用) | + +```json +"data":{ + "state":5, + "msg":"test_failed", + "step":1, //测试故障停止,当前位置 + "fault":1 //故障码,1:机器人通信故障,2:设备通信故障,3:样本未就绪,4:移动失败,5:其他故障 +} +``` + +test_pause 状态 +当检测中按下暂停按钮,状态进入检测暂停状态,显示当前暂停位置 +测试中如果按下暂停,会将当前步骤执行完后,再暂停。 +```json +"data":{ + "state":6, + "msg":"test_pause", + "step":1, //当前暂停,当前位置,恢复时从暂停位置继续 +} +``` + +test_finish 状态 +测试完成,状态进入检测完成状态,显示测试结果 +```json +"data":{ + "state":7, + "msg":"test_finish", + "res": 1, //测结果,1:pass, 0:fail +} +``` + +debug 状态 +就绪状态下,用户点击调试按钮,进入调试状态,显示调试动作按钮,点击调试动作按钮,会执行对应的动作。 +res字段表示调试动作执行结果,0:待测试,1:测试中,2:测试通过,-3:测试中止。 + +```json +"data":{ + "state":8, + "msg":"debug", + "dbg_act":{ + "id":1, //1-10:调试动作编号, + "res":0 //测试结果,0:待测试,1:测试中,2:测试通过,-1:测试失败 + } +} +``` + +参数响应示例 + +```json +{ + "cmd": "query_params", + "code": 0, + "msg": "ok", + "data": { + //参数对象 + //TODO: 定义参数字段 + } +} +``` + +### 4 命令定义 +用户界面点击按钮,会发送对应的命令到服务端。 +dbus的method: user_cmd + +#### 4.1 点击 开始检测 +点击开始检测按钮,进入检测状态。 +命令格式: +```json +{ + "cmd": "test_start", +} +``` +#### 4.2 点击 暂停 +点击暂停按钮,进入暂停检测状态。 +暂停后点击"开始",恢复执行检测 +命令格式: +```json +{ + "cmd": "test_pause", +} +``` +#### 4.3 点击 停止 +点击停止按钮,停止检测,回到就绪状态。 +命令格式: +```json +{ + "cmd": "test_stop", +} +``` + +#### 4.4 点击 登陆 +点击登陆按钮,发送登陆信息。 +命令格式: +```json +{ + "cmd": "login", + "data": { + "user": "admin", + "pwd": "123456", + } +} +``` +#### 4.5 点击 退出登陆 +点击退出按钮,发送退出信息。 +命令格式: +```json +{ + "cmd": "logout", + "data": { + "user": "admin", + } +} +``` +#### 4.5 点击 调试执行 +点击调试执行按钮,发送调试执行信息。 +命令格式: +```json +{ + "cmd": "debug", + "data": { + "action": 1, //1-10:调试动作编号, + } +} +``` + +### 标准动作名列表 + +| `action` 值 | 说明 | +|--------------|------| +| `vortex_start` | 启动涡动仪 | +| `vortex_stop` | 停止涡动仪 | +| `centrifuge_start` | 启动离心机 | +| `centrifuge_stop` | 停止离心机 | +| `pipette_1_aspirate` | 移液器 1 吸液 | +| `pipette_1_dispense` | 移液器 1 排液 | +| `pipette_2_aspirate` | 移液器 2 吸液 | +| `pipette_2_dispense` | 移液器 2 排液 | +| `pipette_3_aspirate` | 移液器 3 吸液 | +| `pipette_3_dispense` | 移液器 3 排液 | +| `pipette_4_aspirate` | 移液器 4 吸液 | +| `pipette_4_dispense` | 移液器 4 排液 | +| `robot_move_home` | 机械臂回原点 | +| `robot_move_pipette` | 机械臂移至移液器位 | +| `robot_move_vortex` | 机械臂移至涡动仪位 | +| `robot_move_centrifuge` | 机械臂移至离心机位 | + +> 动作名可根据实际功能扩展,建议使用 `{设备}_{动作}` 命名风格保持一致。 + +--- + + +**常用错误码:** +| `code` | 含义 | +|--------|------| +| `0` | 成功 | +| `400` | 请求参数错误 | +| `404` | 未知命令 | +| `405` | 当前状态不允许该操作 | +| `500` | 服务端内部错误 | +| `501` | 功能未实现 | \ No newline at end of file diff --git a/dbusmanager.cpp b/dbusmanager.cpp new file mode 100644 index 0000000..1c38411 --- /dev/null +++ b/dbusmanager.cpp @@ -0,0 +1,323 @@ +#include "dbusmanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QMutex DBusManager::s_dbusMutex; + +Q_GLOBAL_STATIC(DBusManager, s_instance) +DBusManager* DBusManager::instance() { return s_instance(); } + +static QByteArray unpackJsonBytes(const QVariant &v) +{ + if (v.type() == QVariant::String) + return v.toString().toUtf8(); + if (v.canConvert()) { + QVariant inner = v.value().variant(); + if (inner.type() == QVariant::String) return inner.toString().toUtf8(); + return inner.toByteArray(); + } + return v.toByteArray(); +} + +DBusManager::DBusManager(QObject *parent) + : QObject(parent) + , m_interface(nullptr) + , m_pollTimer(new QTimer(this)) + , m_pollIntervalMs(0) + , m_connected(false) + , m_lastState(-1) +{ + m_pollTimer->setSingleShot(false); + connect(m_pollTimer, &QTimer::timeout, + this, &DBusManager::onPollingTimeout, Qt::UniqueConnection); + + setupDBusConnection(); + + auto *checkTimer = new QTimer(this); + checkTimer->setInterval(5000); + connect(checkTimer, &QTimer::timeout, this, &DBusManager::checkConnection, Qt::UniqueConnection); + checkTimer->start(); +} + +DBusManager::~DBusManager() +{ + stopPolling(); + if (m_interface) { + delete m_interface; + m_interface = nullptr; + } +} + +void DBusManager::setupDBusConnection() +{ + QDBusConnection bus = QDBusConnection::systemBus(); + if (!bus.isConnected()) { + emit errorOccurred("DBus system bus未连接 (检查 /var/run/dbus/system_bus_socket)"); + return; + } + if (!bus.registerObject("/client", this, QDBusConnection::ExportAllSlots)) { + emit errorOccurred(QString("注册对象失败: %1").arg(bus.lastError().message())); + } +} + +void DBusManager::setService(const QString &service, const QString &path, + const QString &interface) +{ + QMutexLocker locker(&s_dbusMutex); + QDBusConnection bus = QDBusConnection::systemBus(); + + if (m_interface) { + bus.disconnect(m_serviceName, m_objectPath, m_interfaceName, QString(), + this, SLOT(onServerSignal(const QDBusMessage&))); + delete m_interface; + m_interface = nullptr; + } + + m_serviceName = service; + m_objectPath = path; + m_interfaceName = interface; + + m_interface = new QDBusInterface(m_serviceName, m_objectPath, m_interfaceName, + QDBusConnection::systemBus(), this); + + bool ok = bus.connect(m_serviceName, m_objectPath, m_interfaceName, + QString(), this, SLOT(onServerSignal(const QDBusMessage&))); + if (!ok) { + emit errorOccurred(QString("订阅服务端signal失败: %1").arg(bus.lastError().message())); + } + + locker.unlock(); + checkConnection(); +} + +void DBusManager::startPolling(int intervalMs) +{ + m_pollIntervalMs = intervalMs; + m_pollTimer->setInterval(intervalMs); + if (m_connected) { + m_pollTimer->start(); + } +} + +void DBusManager::stopPolling() +{ + if (m_pollTimer->isActive()) m_pollTimer->stop(); +} + +/* ====================== 语义化协议API ====================== */ +bool DBusManager::queryState() +{ + QJsonObject body; + body["cmd"] = "query_state"; + return sendCommand("query_state", body); +} + +bool DBusManager::queryParams() +{ + QJsonObject body; + body["cmd"] = "query_params"; + return sendCommand("query_params", body); +} + +bool DBusManager::updateParams(const QJsonObject ¶ms) +{ + QJsonObject body = params; + if (!body.contains("cmd")) body["cmd"] = "update_params"; + return sendCommand("update_params", body); +} + +bool DBusManager::sendUserCmd(const QString &cmd, const QJsonObject &data) +{ + QJsonObject body; + body["cmd"] = cmd; + if (!data.isEmpty()) body["data"] = data; + return sendCommand("user_cmd", body); +} + +/* ====================== 低层通用发送 ====================== */ +bool DBusManager::sendCommand(const QString &method, const QJsonObject &jsonBody) +{ + QMutexLocker locker(&s_dbusMutex); + if (!m_interface) { + emit errorOccurred(QString("[%1] DBus接口未初始化").arg(method)); + return false; + } + + QString jsonStr = QString::fromUtf8( + QJsonDocument(jsonBody).toJson(QJsonDocument::Compact)); + + QDBusPendingCall pcall = m_interface->asyncCallWithArgumentList( + method, { QVariant::fromValue(jsonStr) }); + + auto *watcher = new QDBusPendingCallWatcher(pcall, this); + connect(watcher, &QDBusPendingCallWatcher::finished, + this, [this, method](QDBusPendingCallWatcher *self) { + QDBusMessage reply = self->reply(); + self->deleteLater(); + + if (reply.type() == QDBusMessage::ErrorMessage) { + emit errorOccurred(QString("----[%1] DBus错误: %2").arg(method, reply.errorMessage())); + return; + } + const QList &args = reply.arguments(); + if (args.isEmpty()) return; + + QByteArray raw = unpackJsonBytes(args.first()); + if (raw.isEmpty()) return; + + QJsonParseError err; + QJsonDocument doc = QJsonDocument::fromJson(raw, &err); + if (err.error != QJsonParseError::NoError) { + emit errorOccurred(QString("[%1] 响应JSON解析失败: %2, raw=%3") + .arg(method, err.errorString(), QString::fromUtf8(raw.left(200)))); + return; + } + if (!doc.isObject()) { + emit errorOccurred(QString("[%1] 响应非JSON对象: %2").arg(method, QString::fromUtf8(raw))); + return; + } + QJsonObject obj = doc.object(); + QString cmd = obj.value("cmd").toString(method); + int code = obj.value("code").toInt(-1); + QJsonObject data = obj.value("data").toObject(); + + if (code != 0) { + QString msg = obj.value("msg").toString(QString()); + emit errorOccurred(QString("[%1] 业务错误 code=%2, msg=%3") + .arg(cmd).arg(code).arg(msg)); + } + + emit responseReceived(cmd, code, data); + + if (code == 0) { + if (cmd == QLatin1String("query_state")) { + if (!data.isEmpty()) { + m_lastState = data.value("state").toInt(m_lastState); + m_lastStateData = data; + emit stateUpdated(data); + } + } else if (cmd == QLatin1String("query_params")) { + if (!data.isEmpty()) emit paramsUpdated(data); + } else if (data.contains("state") || cmd == QLatin1String("state_changed")) { + /* user_cmd / 信号也可能附带状态增量 */ + QJsonObject s = data.contains("state") && data.value("state").isObject() + ? data.value("state").toObject() + : data; + m_lastState = s.value("state").toInt(m_lastState); + m_lastStateData = s; + emit stateUpdated(s); + } + } + }, Qt::UniqueConnection); + + return true; +} + +void DBusManager::onPollingTimeout() +{ + queryState(); +} + +void DBusManager::onServerSignal(const QDBusMessage &msg) +{ + const QList &args = msg.arguments(); + if (args.isEmpty()) return; + + QByteArray raw = unpackJsonBytes(args.first()); + if (raw.isEmpty()) return; + + QJsonParseError err; + QJsonDocument doc = QJsonDocument::fromJson(raw, &err); + if (err.error != QJsonParseError::NoError) { + emit errorOccurred(QString("Signal JSON解析失败: %1, raw=%2") + .arg(err.errorString(), QString::fromUtf8(raw.left(200)))); + return; + } + if (!doc.isObject()) return; + QJsonObject obj = doc.object(); + + QString signalName = msg.member(); + if (obj.contains("signal")) signalName = obj.value("signal").toString(signalName); + emit signalReceived(signalName, obj); + + /* 推送的状态更新:state_changed 信号 或 顶层含state/data 结构 */ + if (obj.contains("cmd") && obj.contains("code")) { + QString cmd = obj.value("cmd").toString(signalName); + int code = obj.value("code").toInt(-1); + QJsonObject data = obj.value("data").toObject(); + if (code == 0) { + if (cmd == QLatin1String("query_state") || signalName == QLatin1String("state_changed")) { + m_lastState = data.value("state").toInt(m_lastState); + m_lastStateData = data; + emit stateUpdated(data); + } else if (cmd == QLatin1String("query_params")) + emit paramsUpdated(data); + } + } else if (signalName == QLatin1String("state_changed")) { + QJsonObject data = obj.contains("data") ? obj.value("data").toObject() : obj; + m_lastState = data.value("state").toInt(m_lastState); + m_lastStateData = data; + emit stateUpdated(data); + } +} + +void DBusManager::checkConnection() +{ + QMutexLocker locker(&s_dbusMutex); + if (!m_interface) { + locker.unlock(); + bool connected = false; + if (connected != m_connected) { + m_connected = connected; + if (m_pollTimer->isActive()) m_pollTimer->stop(); + emit connectionChanged(m_connected); + } + return; + } + + QDBusConnection bus = QDBusConnection::systemBus(); + locker.unlock(); + + /* 通过查询DBus总线的NameHasOwner标准接口检测服务名 + * 不依赖服务端是否实现了特定method(如ping) */ + QDBusMessage msg = QDBusMessage::createMethodCall( + QStringLiteral("org.freedesktop.DBus"), + QStringLiteral("/org/freedesktop/DBus"), + QStringLiteral("org.freedesktop.DBus"), + QStringLiteral("NameHasOwner")); + msg << m_serviceName; + + QDBusPendingCall pcall = bus.asyncCall(msg); + auto *watcher = new QDBusPendingCallWatcher(pcall, this); + connect(watcher, &QDBusPendingCallWatcher::finished, + this, [this](QDBusPendingCallWatcher *self) { + self->deleteLater(); + bool connected = false; + if (self->isValid() && !self->isError()) { + QDBusMessage reply = self->reply(); + const QList &args = reply.arguments(); + if (!args.isEmpty()) + connected = args.first().toBool(); + } + if (connected != m_connected) { + m_connected = connected; + if (m_connected) { + if (m_pollIntervalMs > 0 && !m_pollTimer->isActive()) + m_pollTimer->start(); + } else { + if (m_pollTimer->isActive()) + m_pollTimer->stop(); + } + emit connectionChanged(m_connected); + } + }, Qt::UniqueConnection); +} \ No newline at end of file diff --git a/dbusmanager.h b/dbusmanager.h new file mode 100644 index 0000000..f1a4cc9 --- /dev/null +++ b/dbusmanager.h @@ -0,0 +1,78 @@ +#ifndef DBUSMANAGER_H +#define DBUSMANAGER_H + +#include +#include +#include +#include +#include + +class QDBusInterface; +class QDBusMessage; + +class DBusManager : public QObject +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "com.yn.ui.client") + +public: + static DBusManager* instance(); + + explicit DBusManager(QObject *parent = nullptr); + ~DBusManager(); + + void setService(const QString &service, const QString &path, + const QString &interface); + + void startPolling(int intervalMs = 500); + void stopPolling(); + + /* ---------- 协议语义化API (对应 dbus.md Methods) ---------- */ + bool queryState(); + bool queryParams(); + bool updateParams(const QJsonObject ¶ms); + bool sendUserCmd(const QString &cmd, const QJsonObject &data = QJsonObject()); + + /* ---------- 低层通用发送 ---------- */ + bool sendCommand(const QString &method, const QJsonObject &jsonBody = QJsonObject()); + + /* ---------- 最新状态快照(方便定时器/页面判断,不需要各自存一份) ---------- */ + int lastState() const { return m_lastState; } + QJsonObject lastStateData() const { return m_lastStateData; } + +signals: + void connectionChanged(bool connected); + void responseReceived(const QString &cmd, int code, const QJsonObject &data); + void signalReceived(const QString &signalName, const QJsonObject &obj); + void errorOccurred(const QString &errorMsg); + + /* 上层UI订阅:query_state 成功解析出 data */ + void stateUpdated(const QJsonObject &data); + /* 上层UI订阅:query_params 成功解析出 data */ + void paramsUpdated(const QJsonObject &data); + +public slots: + void onServerSignal(const QDBusMessage &msg); + +private slots: + void onPollingTimeout(); + +private: + void setupDBusConnection(); + void checkConnection(); + + QDBusInterface *m_interface; + QTimer *m_pollTimer; + int m_pollIntervalMs; + + QString m_serviceName; + QString m_objectPath; + QString m_interfaceName; + bool m_connected; + int m_lastState; + QJsonObject m_lastStateData; + + static QMutex s_dbusMutex; +}; + +#endif \ No newline at end of file diff --git a/debug.ui b/debug.ui new file mode 100644 index 0000000..f72b4fa --- /dev/null +++ b/debug.ui @@ -0,0 +1,377 @@ + + + DebugPage + + + + 0 + 0 + 1120 + 700 + + + + false + + + QWidget#DebugPage{ + border-image: url(:/res/debug_1120x700.png); +} + + + + + 30 + 10 + 181 + 71 + + + + TextLabel + + + + + + 640 + 10 + 421 + 61 + + + + TextLabel + + + + + + 630 + 580 + 351 + 71 + + + + TextLabel + + + + + + 20 + 120 + 141 + 91 + + + + 1 + + + + + + 170 + 120 + 141 + 91 + + + + 2 + + + + + + 330 + 120 + 141 + 91 + + + + 3 + + + + + + 480 + 120 + 141 + 91 + + + + 4 + + + + + + 640 + 120 + 141 + 91 + + + + 5 + + + + + + 800 + 120 + 141 + 91 + + + + 6 + + + + + + 950 + 120 + 141 + 91 + + + + 7 + + + + + + 640 + 270 + 141 + 91 + + + + 12 + + + + + + 170 + 270 + 141 + 91 + + + + 9 + + + + + + 330 + 270 + 141 + 91 + + + + 10 + + + + + + 950 + 270 + 141 + 91 + + + + 14 + + + + + + 480 + 270 + 141 + 91 + + + + 11 + + + + + + 20 + 270 + 141 + 91 + + + + 8 + + + + + + 800 + 270 + 141 + 91 + + + + 13 + + + + + + 640 + 420 + 141 + 91 + + + + 19 + + + + + + 170 + 420 + 141 + 91 + + + + 16 + + + + + + 330 + 420 + 141 + 91 + + + + 17 + + + + + + 950 + 420 + 141 + 91 + + + + 21 + + + + + + 480 + 420 + 141 + 91 + + + + 18 + + + + + + 20 + 420 + 141 + 91 + + + + 15 + + + + + + 800 + 420 + 141 + 91 + + + + 20 + + + + + + 20 + 570 + 141 + 91 + + + + 22 + + + + + + 170 + 570 + 141 + 91 + + + + 23 + + + + + + 1000 + 570 + 91 + 81 + + + + start + + + + + + + + diff --git a/debugpage.cpp b/debugpage.cpp new file mode 100644 index 0000000..a518c0b --- /dev/null +++ b/debugpage.cpp @@ -0,0 +1,161 @@ +#include "debugpage.h" +#include "ui_debug.h" +#include "dbusmanager.h" +#include +#include +#include +#include + +struct DbgActionMap { int idx; const char *action; }; +static const DbgActionMap namedActions[] = { + { 11, "vortex_start" }, + { 12, "vortex_stop" }, + { 13, "centrifuge_start" }, + { 14, "centrifuge_stop" }, + { 15, "pipette_1_aspirate" }, + { 16, "pipette_1_dispense" }, + { 17, "pipette_2_aspirate" }, + { 18, "pipette_2_dispense" }, + { 19, "pipette_3_aspirate" }, + { 20, "pipette_3_dispense" }, + { 21, "pipette_4_aspirate" }, + { 22, "pipette_4_dispense" }, + { 23, "robot_move_home" }, + { -1, nullptr } +}; + +static const char *dbgActResText(int v) +{ + switch (v) { + case 0: return "待执行"; + case 1: return "执行中"; + case 2: return "通过"; + case -1: return "失败"; + case -3: return "中止"; + default: return "状态未知"; + } +} +static QString dbgActResColor(int v) +{ + switch (v) { + case 1: return "#f39c12"; + case 2: return "#2ecc71"; + case -1: case -3: return "#e74c3c"; + default: return "#95a5a6"; + } +} + +DebugPage::DebugPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::DebugPage), + m_lastStep(0) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + QList steps = { + ui->btn_dbg_1, ui->btn_dbg_2, ui->btn_dbg_3, ui->btn_dbg_4, ui->btn_dbg_5, + ui->btn_dbg_6, ui->btn_dbg_7, ui->btn_dbg_8, ui->btn_dbg_9, ui->btn_dbg_10, + ui->btn_dbg_11, ui->btn_dbg_12, ui->btn_dbg_13, ui->btn_dbg_14, ui->btn_dbg_15, + ui->btn_dbg_16, ui->btn_dbg_17, ui->btn_dbg_18, ui->btn_dbg_19, ui->btn_dbg_20, + ui->btn_dbg_21, ui->btn_dbg_22, ui->btn_dbg_23 + }; + + for (int i = 0; i < steps.size(); ++i) { + int idx = i + 1; + QPushButton *btn = steps[i]; + if (idx >= 1 && idx <= 10) { + btn->setProperty("action_type", "int"); + btn->setProperty("action_int", idx); + btn->setText(QStringLiteral("动作 %1").arg(idx)); + } else { + for (int k = 0; namedActions[k].idx > 0; ++k) { + if (namedActions[k].idx == idx) { + btn->setProperty("action_type", "str"); + btn->setProperty("action_str", QString::fromUtf8(namedActions[k].action)); + btn->setText(QString::fromUtf8(namedActions[k].action)); + break; + } + } + } + btn->setEnabled(false); + connect(btn, &QPushButton::clicked, this, &DebugPage::onDbgStepClicked, Qt::UniqueConnection); + } + ui->lab_dbg_step->clear(); + ui->lab_dbg_info->clear(); + ui->lab_dbg_title->setText(QStringLiteral("调试模式(未激活)")); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &DebugPage::updateFromState, Qt::UniqueConnection); + connect(ui->btn_dbg_start, &QPushButton::clicked, + this, &DebugPage::onDbgStartClicked, Qt::UniqueConnection); +} + +DebugPage::~DebugPage() { delete ui; } + +static QJsonValue actionFromBtn(QPushButton *btn, int *outIntTag = nullptr) +{ + QString t = btn->property("action_type").toString(); + if (t == "str") { + if (outIntTag) *outIntTag = -1; + return QJsonValue(btn->property("action_str").toString()); + } + int v = btn->property("action_int").toInt(0); + if (outIntTag) *outIntTag = v; + return QJsonValue(v); +} + +void DebugPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + bool inDebug = (state == 8); + + ui->lab_dbg_title->setText(inDebug ? QStringLiteral("调试模式(激活)") + : QStringLiteral("调试模式(未激活)")); + + QList allBtns = findChildren(QRegularExpression("btn_dbg_\\d+")); + for (auto *b : allBtns) b->setEnabled(inDebug); + ui->btn_dbg_start->setEnabled(inDebug); + + if (!data.contains("dbg_act")) return; + QJsonObject d = data.value("dbg_act").toObject(); + QJsonValue id = d.value("id"); + int res = d.value("res").toInt(0); + + QString stepText; + if (id.isDouble()) stepText = QStringLiteral("%1").arg(id.toInt()); + else stepText = id.toString(); + ui->lab_dbg_step->setText(stepText); + + ui->lab_dbg_info->setText(QStringLiteral("%1").arg(QString::fromUtf8(dbgActResText(res)))); + ui->lab_dbg_info->setStyleSheet(QStringLiteral("color:%1; font-weight:bold;") + .arg(dbgActResColor(res))); +} + +void DebugPage::onDbgStepClicked() +{ + QPushButton *btn = qobject_cast(sender()); + if (!btn) return; + + int intTag = 0; + QJsonValue act = actionFromBtn(btn, &intTag); + if (intTag > 0 && intTag <= 10) m_lastStep = intTag; + + QJsonObject data; + if (act.isDouble()) data["action"] = act.toInt(); + else if (act.isString()) data["action"] = act.toString(); + else data["action"] = intTag; + + DBusManager::instance()->sendUserCmd("debug", data); +} + +void DebugPage::onDbgStartClicked() +{ + QJsonObject data; + if (m_lastStep > 0) { + data["action"] = m_lastStep; + } else { + data["action"] = "start"; + } + DBusManager::instance()->sendUserCmd("debug", data); +} \ No newline at end of file diff --git a/debugpage.h b/debugpage.h new file mode 100644 index 0000000..0cce48c --- /dev/null +++ b/debugpage.h @@ -0,0 +1,31 @@ +#ifndef DEBUGPAGE_H +#define DEBUGPAGE_H + +#include +#include + +namespace Ui { +class DebugPage; +} + +class DebugPage : public QWidget +{ + Q_OBJECT + +public: + explicit DebugPage(QWidget *parent = nullptr); + ~DebugPage(); + +public slots: + void updateFromState(const QJsonObject &state); + +private slots: + void onDbgStepClicked(); + void onDbgStartClicked(); + +private: + Ui::DebugPage *ui; + int m_lastStep; +}; + +#endif \ No newline at end of file diff --git a/home.ui b/home.ui new file mode 100644 index 0000000..dbaa62e --- /dev/null +++ b/home.ui @@ -0,0 +1,168 @@ + + + HomePage + + + + 0 + 0 + 1280 + 800 + + + + QWidget#HomePage{ + border-image: url(:/res/home_1280x800.png); +} + + + + + 10 + 120 + 141 + 111 + + + + Login + + + + + + 10 + 240 + 141 + 111 + + + + test + + + + + + 10 + 370 + 141 + 111 + + + + record + + + + + + 10 + 490 + 141 + 111 + + + + setting + + + + + + 10 + 620 + 141 + 111 + + + + debug + + + + + + 0 + 0 + 381 + 91 + + + + TextLabel + + + + + + 520 + 0 + 291 + 91 + + + + TextLabel + + + + + + 840 + 0 + 131 + 91 + + + + TextLabel + + + + + + 980 + 0 + 91 + 91 + + + + TextLabel + + + + + + 1080 + 0 + 191 + 91 + + + + TextLabel + + + + + + 160 + 100 + 1120 + 700 + + + + 0 + + + + + + + + + + diff --git a/homewindow.cpp b/homewindow.cpp new file mode 100644 index 0000000..46c30cf --- /dev/null +++ b/homewindow.cpp @@ -0,0 +1,295 @@ +#include "homewindow.h" +#include "ui_home.h" +#include "dbusmanager.h" +#include +#include +#include + +static const char *stepNames[] = { + "", + "加提取液", // 1 + "涡动", // 2 + "离心", // 3 + "提取样本液(移液器2)",// 4 + "加提取液(移液器3)", // 5 + "涡动", // 6 + "提取样本液(移液器4)",// 7 + "滴入试纸", // 8 + "等待结果", // 9 + "拍照分析", // 10 + "检测完成" // 11 +}; + +/* 放构造函数之前:否则构造函数里的 lambda 会报 stopTimerIf "not declared" */ +static void stopTimerIf(QTimer *t) { if (t && t->isActive()) t->stop(); } + +HomeWindow::HomeWindow(QWidget *parent) : + QWidget(parent), + ui(new Ui::HomePage), + m_loggedUser(QStringLiteral("未登录")), + m_forceTestFallback(false) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + resize(1280, 800); + + m_loginPage = new LoginPage(); + connect(m_loginPage, &LoginPage::userLoggedIn, this, &HomeWindow::setLoggedUser, Qt::UniqueConnection); + m_testPage = new TestPage(); + m_recordPage = new RecordPage(); + m_settingPage = new SettingPage(); + m_debugPage = new DebugPage(); + m_selftestPage = new SelftestPage(); + + while (ui->stackedWidget->count() > 0) { + QWidget *w = ui->stackedWidget->widget(0); + ui->stackedWidget->removeWidget(w); + delete w; + } + ui->stackedWidget->addWidget(m_selftestPage); // 0 + ui->stackedWidget->addWidget(m_loginPage); // 1 + ui->stackedWidget->addWidget(m_testPage); // 2 + ui->stackedWidget->addWidget(m_recordPage); // 3 + ui->stackedWidget->addWidget(m_settingPage); // 4 + ui->stackedWidget->addWidget(m_debugPage); // 5 + ui->stackedWidget->setCurrentWidget(m_selftestPage); + + /* 10秒保底:到时强制切到检测页,避免状态无响应时卡死在自检页 */ + m_selftestTimer = new QTimer(this); + m_selftestTimer->setSingleShot(true); + connect(m_selftestTimer, &QTimer::timeout, this, &HomeWindow::onSelftestTimeout); + m_selftestTimer->start(10000); + + /* 顶栏本地时钟 1s/次 */ + m_clockTimer = new QTimer(this); + m_clockTimer->setInterval(1000); + connect(m_clockTimer, &QTimer::timeout, this, &HomeWindow::onClockTick); + m_clockTimer->start(); + if (ui->lab_date) { + ui->lab_date->setStyleSheet(QStringLiteral("color:white; font-size:30px; font-weight:bold;")); + ui->lab_date->setAlignment(Qt::AlignCenter); + } + if (ui->lab_time) { + ui->lab_time->setStyleSheet(QStringLiteral("color:white; font-size:36px; font-weight:bold;")); + ui->lab_time->setAlignment(Qt::AlignCenter); + } + if (ui->lab_user) ui->lab_user->setStyleSheet(QStringLiteral("color:white; font-size:22px;")); + if (ui->lab_signal) ui->lab_signal->setStyleSheet(QStringLiteral("color:white; font-size:22px;")); + if (ui->lab_test_type) ui->lab_test_type->setStyleSheet(QStringLiteral("color:white; font-size:22px;")); + onClockTick(); + ui->lab_user->setText(m_loggedUser); + ui->lab_signal->setText(QStringLiteral("正常")); + + connect(ui->btn_login, &QPushButton::clicked, this, &HomeWindow::onBtnLoginClicked, Qt::UniqueConnection); + connect(ui->btn_test, &QPushButton::clicked, this, &HomeWindow::onBtnTestClicked, Qt::UniqueConnection); + connect(ui->btn_record, &QPushButton::clicked, this, &HomeWindow::onBtnRecordClicked, Qt::UniqueConnection); + connect(ui->btn_setting, &QPushButton::clicked, this, &HomeWindow::onBtnSettingClicked, Qt::UniqueConnection); + connect(ui->btn_debug, &QPushButton::clicked, this, &HomeWindow::onBtnDebugClicked, Qt::UniqueConnection); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &HomeWindow::onStateUpdated, Qt::UniqueConnection); + + /* 开机默认:左侧栏全部禁用(只有等自检成功 state>=3 才开放) */ + setSidebarButtonsEnabled(false); + + /* 自检失败页:点"重新自检"按钮 → 发送 exit_selftest_failed 命令给后端, + 后端会强制回到 DEV_INIT 重跑整套自检 */ + connect(m_selftestPage, &SelftestPage::restartSelftestRequested, this, [this]() { + stopTimerIf(m_selftestTimer); + /* 又要重跑自检 → 左侧栏立即回到禁用态,直到下一次自检成功 */ + setSidebarButtonsEnabled(false); + if (DBusManager::instance()) { + DBusManager::instance()->sendUserCmd(QStringLiteral("exit_selftest_failed")); + } + }, Qt::UniqueConnection); +} + +HomeWindow::~HomeWindow() +{ + delete ui; +} + +void HomeWindow::setSidebarButtonsEnabled(bool enabled) +{ + if (ui->btn_login) ui->btn_login->setEnabled(enabled); + if (ui->btn_test) ui->btn_test->setEnabled(enabled); + if (ui->btn_record) ui->btn_record->setEnabled(enabled); + if (ui->btn_setting) ui->btn_setting->setEnabled(enabled); + if (ui->btn_debug) ui->btn_debug->setEnabled(enabled); +} + +void HomeWindow::setLoggedUser(const QString &user) +{ + m_loggedUser = user.isEmpty() ? QStringLiteral("未登录") : user; + ui->lab_user->setText(m_loggedUser); +} + +void HomeWindow::onBtnLoginClicked() +{ + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_loginPage); +} +void HomeWindow::onBtnTestClicked() +{ + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_testPage); +} +void HomeWindow::onBtnRecordClicked() +{ + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_recordPage); +} +void HomeWindow::onBtnSettingClicked() +{ + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_settingPage); +} +void HomeWindow::onBtnDebugClicked() +{ + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_debugPage); +} + +void HomeWindow::onSelftestTimeout() +{ + DBusManager *dbus = DBusManager::instance(); + int state = dbus ? dbus->lastState() : -1; + + /* 一次都没收到状态的话,立刻主动查询一次,再等一轮,避免在服务端初始化 + 还没响应完时误判为"卡自检",直接把用户踢去 test 页 */ + if (state < 0) { + if (dbus) dbus->queryState(); + m_selftestTimer->start(3000); + return; + } + + /* state==1(自检中) 时,再给它延长一次等待 (自检项多可能 >10s) */ + if (state == 1 /* DEV_SELFTESTING */) { + m_selftestTimer->start(10000); + return; + } + + /* DEV_SELFTEST_FAILED(state==2):绝对不能跳走,让用户看清楚故障详情。 + 这里再手动执行一次 switchPageByState,确保 UI 还在 selftest 页 + (极端情况下切错页能被纠正回来) */ + if (state == 2 /* DEV_SELFTEST_FAILED */) { + switchPageByState(state); + return; + } + + /* 只有 state >= 3(READY / AUTOTESTING 等),才认为机器已可使用, + 保底切到 test 页并解锁侧栏;其余情况一律不兜底解锁, + 防止后端卡死时用户误点去没初始化好的页面 */ + if (state >= 3) { + setSidebarButtonsEnabled(true); + m_forceTestFallback = true; + ui->stackedWidget->setCurrentWidget(m_testPage); + } +} + +void HomeWindow::onClockTick() +{ + QDateTime now = QDateTime::currentDateTime(); + static const char *weekDays[] = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; + int dow = now.date().dayOfWeek(); // 1=Mon ... 7=Sun + if (dow == 7) dow = 0; + ui->lab_date->setText(QStringLiteral("%1 %2") + .arg(now.toString("yyyy-MM-dd")) + .arg(QString::fromUtf8(weekDays[dow]))); + ui->lab_time->setText(now.toString("HH:mm:ss")); +} + +QString HomeWindow::stateText(int state, const QJsonObject &data) +{ + int step = data.value("step").toInt(0); + int fault = data.value("fault").toInt(0); + switch (state) { + case 0: return QStringLiteral("初始化"); + case 1: return QStringLiteral("自检中"); + case 2: return QStringLiteral("自检失败"); + case 3: return QStringLiteral("就绪"); + case 4: { + QString s = (step >= 1 && step <= 11) ? QStringLiteral("检测中 步骤%1/11 %2") + .arg(step).arg(QString::fromUtf8(stepNames[step])) + : QStringLiteral("检测中"); + QJsonObject timer = data.value("timer").toObject(); + int remain = timer.value("remain").toInt(0); + if (remain > 0) s += QStringLiteral(" 剩%1s").arg(remain); + return s; + } + case 5: return QStringLiteral("已暂停 %1").arg( + (step >= 1 && step <= 11) ? QString::fromUtf8(stepNames[step]) : QString()); + case 6: { + QStringList fmts; + fmts << QStringLiteral("无故障") + << QStringLiteral("机械臂通信故障") << QStringLiteral("移液器故障") + << QStringLiteral("涡动仪故障") << QStringLiteral("离心机故障") + << QStringLiteral("样本未就绪") << QStringLiteral("移动失败") + << QStringLiteral("其他故障"); + QString f = (qAbs(fault) < fmts.size()) ? fmts[qAbs(fault)] + : QStringLiteral("故障码%1").arg(fault); + return QStringLiteral("检测异常(%1)").arg(f); + } + case 7: { + int r = data.value("res").toInt(-1); + if (r == 1) return QStringLiteral("检测完成: 通过"); + if (r == 0) return QStringLiteral("检测完成: 失败"); + return QStringLiteral("检测完成"); + } + case 8: return QStringLiteral("调试模式"); + default: break; + } + return data.value("msg").toString(QStringLiteral("未知状态%1").arg(state)); +} + +void HomeWindow::switchPageByState(int state) +{ + /* 用户手动切过 或 10秒保底触发 后,不再从检测页跳回自检页,避免影响用户操作 */ + QWidget *cur = ui->stackedWidget->currentWidget(); + bool stickToCurrent = (m_forceTestFallback && cur == m_testPage) + || cur == m_loginPage || cur == m_recordPage + || cur == m_settingPage || cur == m_debugPage; + + switch (state) { + case 0: case 1: + /* 初始化 / 自检中:左侧栏保持禁用,直到自检成功 READY */ + setSidebarButtonsEnabled(false); + if (!stickToCurrent) ui->stackedWidget->setCurrentWidget(m_selftestPage); + break; + case 2: + /* ====== 自检失败:左侧栏全部禁用,只允许在 selftest 页操作"重新自检"按钮 ====== */ + setSidebarButtonsEnabled(false); + if (!stickToCurrent) ui->stackedWidget->setCurrentWidget(m_selftestPage); + stopTimerIf(m_selftestTimer); + break; + case 3: case 4: case 5: case 6: case 7: + /* state==3 READY:自检成功,左侧栏解锁可用; + state==6/7 是 test 出错/完成,保持可用给用户看结果 */ + setSidebarButtonsEnabled(true); + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_testPage); + break; + case 8: + setSidebarButtonsEnabled(true); + stopTimerIf(m_selftestTimer); + ui->stackedWidget->setCurrentWidget(m_debugPage); + break; + default: + break; + } +} + +void HomeWindow::onStateUpdated(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + ui->lab_test_type->setText(stateText(state, data)); + + int fault = data.value("fault").toInt(0); + if (fault != 0) { + ui->lab_signal->setText(QStringLiteral("故障%1").arg(fault)); + } else { + ui->lab_signal->setText(QStringLiteral("正常")); + } + + if (state >= 0) switchPageByState(state); +} \ No newline at end of file diff --git a/homewindow.h b/homewindow.h new file mode 100644 index 0000000..82c69b8 --- /dev/null +++ b/homewindow.h @@ -0,0 +1,58 @@ +#ifndef HOMEWINDOW_H +#define HOMEWINDOW_H + +#include +#include +#include +#include +#include "loginpage.h" +#include "testpage.h" +#include "recordpage.h" +#include "settingpage.h" +#include "debugpage.h" +#include "selftestpage.h" + +namespace Ui { +class HomePage; +} + +class HomeWindow : public QWidget +{ + Q_OBJECT + +public: + explicit HomeWindow(QWidget *parent = nullptr); + ~HomeWindow(); + + void setLoggedUser(const QString &user); + +private slots: + void onBtnLoginClicked(); + void onBtnTestClicked(); + void onBtnRecordClicked(); + void onBtnSettingClicked(); + void onBtnDebugClicked(); + void onSelftestTimeout(); + void onClockTick(); + void onStateUpdated(const QJsonObject &state); + +private: + static QString stateText(int state, const QJsonObject &data); + void switchPageByState(int state); + /* 统一控制左侧栏 5 个导航按钮的启用/禁用(自检失败时全部禁用) */ + void setSidebarButtonsEnabled(bool enabled); + + Ui::HomePage *ui; + LoginPage *m_loginPage; + TestPage *m_testPage; + RecordPage *m_recordPage; + SettingPage *m_settingPage; + DebugPage *m_debugPage; + SelftestPage *m_selftestPage; + QTimer *m_selftestTimer; + QTimer *m_clockTimer; + QString m_loggedUser; + bool m_forceTestFallback; +}; + +#endif \ No newline at end of file diff --git a/login.ui b/login.ui new file mode 100644 index 0000000..4e7850a --- /dev/null +++ b/login.ui @@ -0,0 +1,85 @@ + + + LoginPage + + + + 0 + 0 + 1120 + 700 + + + + false + + + QWidget#LoginPage{ + border-image: url(:/res/login_1120x700.png); +} + + + + + 770 + 190 + 151 + 131 + + + + Login + + + + + + 320 + 60 + 381 + 61 + + + + status + + + + + + 770 + 360 + 141 + 131 + + + + Logout + + + + + + 320 + 240 + 391 + 61 + + + + + + + 320 + 370 + 391 + 61 + + + + + + + + + diff --git a/loginpage.cpp b/loginpage.cpp new file mode 100644 index 0000000..8d768a9 --- /dev/null +++ b/loginpage.cpp @@ -0,0 +1,60 @@ +#include "loginpage.h" +#include "ui_login.h" +#include "dbusmanager.h" +#include + +LoginPage::LoginPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::LoginPage) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &LoginPage::updateFromState, Qt::UniqueConnection); + connect(DBusManager::instance(), &DBusManager::responseReceived, + this, &LoginPage::onCmdResponse, Qt::UniqueConnection); + connect(ui->btn_login, &QPushButton::clicked, + this, &LoginPage::onBtnLoginClicked, Qt::UniqueConnection); + connect(ui->btn_login_2, &QPushButton::clicked, this, [this] { + QJsonObject data; data["action"] = "logout"; + DBusManager::instance()->sendUserCmd("login", data); + }, Qt::UniqueConnection); +} + +LoginPage::~LoginPage() { delete ui; } + +void LoginPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + QString title; + if (state >= 3 && state <= 7) title = QStringLiteral("用户登录"); + else if (state == 1 || state == 2) title = QStringLiteral("请等待自检完成"); + else if (state == 8) title = QStringLiteral("调试中 - 登录"); + if (!title.isEmpty()) ui->lab_login_state->setText(title); +} + +void LoginPage::onBtnLoginClicked() +{ + QString user = ui->edit_username->text().trimmed(); + QString pwd = ui->edit_password->text(); + if (user.isEmpty()) { + ui->edit_username->setFocus(); + return; + } + m_pendingUser = user; + + QJsonObject data; + data["user"] = user; + data["pwd"] = pwd; + DBusManager::instance()->sendUserCmd("login", data); +} + +void LoginPage::onCmdResponse(const QString &cmd, int code, const QJsonObject &data) +{ + if (cmd != QLatin1String("login")) return; + if (code == 0) { + emit userLoggedIn(m_pendingUser); + } + Q_UNUSED(data); +} diff --git a/loginpage.h b/loginpage.h new file mode 100644 index 0000000..6858a90 --- /dev/null +++ b/loginpage.h @@ -0,0 +1,34 @@ +#ifndef LOGINPAGE_H +#define LOGINPAGE_H + +#include +#include + +namespace Ui { +class LoginPage; +} + +class LoginPage : public QWidget +{ + Q_OBJECT + +public: + explicit LoginPage(QWidget *parent = nullptr); + ~LoginPage(); + +signals: + void userLoggedIn(const QString &user); + +public slots: + void updateFromState(const QJsonObject &state); + +private slots: + void onBtnLoginClicked(); + void onCmdResponse(const QString &cmd, int code, const QJsonObject &data); + +private: + Ui::LoginPage *ui; + QString m_pendingUser; +}; + +#endif \ No newline at end of file diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..dcd7878 --- /dev/null +++ b/main.cpp @@ -0,0 +1,78 @@ +#include "poweronwindow.h" +#include "homewindow.h" +#include "dbusmanager.h" +#include +#include +#include +#include +#include + +static const QString DBUS_SERVICE = "com.yn.ui"; +static const QString DBUS_PATH = "/com/yn/ui"; +static const QString DBUS_INTERFACE = "com.yn.ui.interface"; + +static QString ts() +{ + return QDateTime::currentDateTime().toString("[hh:mm:ss.zzz]"); +} + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + + qDebug() << ts() << "================================="; + qDebug() << ts() << "[DBG] 使用 SYSTEM BUS (socket: /var/run/dbus/system_bus_socket)"; + bool sockOk = QFile::exists(QStringLiteral("/var/run/dbus/system_bus_socket")); + qDebug() << ts() << "[DBG] DBus socket存在吗? " << (sockOk ? "YES" : "NO - dbus-daemon未启动!"); + bool confOk = QFile::exists(QStringLiteral("/etc/dbus-1/system.d/com.yn.ui.conf")); + qDebug() << ts() << "[DBG] 权限配置存在吗? " << (confOk ? "YES" : "NO - 服务端无法注册名字!"); + qDebug() << ts() << "================================="; + + DBusManager *dbus = DBusManager::instance(); + dbus->setService(DBUS_SERVICE, DBUS_PATH, DBUS_INTERFACE); + + QObject::connect(dbus, &DBusManager::connectionChanged, + [](bool connected) { + qDebug() << ts() << "DBus连接状态:" << (connected ? "已连接" : "已断开"); + }); + + QObject::connect(dbus, &DBusManager::responseReceived, + [](const QString &cmd, int code, const QJsonObject &data) { + QString json = QString::fromUtf8( + QJsonDocument(data).toJson(QJsonDocument::Compact)); + qDebug() << ts() << QString("响应[%1] code=%2").arg(cmd).arg(code) + << ":" << json; + }); + + QObject::connect(dbus, &DBusManager::signalReceived, + [](const QString &signalName, const QJsonObject &data) { + QString json = QString::fromUtf8( + QJsonDocument(data).toJson(QJsonDocument::Compact)); + qDebug() << ts() << "信号[" << signalName << "]:" << json; + }); + + QObject::connect(dbus, &DBusManager::errorOccurred, + [](const QString &errorMsg) { + qWarning() << ts() << "DBus错误:" << errorMsg; + }); + + dbus->startPolling(500); + + QStackedWidget mainStack; + mainStack.setWindowTitle("Agridetect"); + mainStack.resize(1280, 800); + + PowerOnWindow *powerOn = new PowerOnWindow(); + HomeWindow *home = new HomeWindow(); + + mainStack.addWidget(powerOn); + mainStack.addWidget(home); + mainStack.setCurrentWidget(powerOn); + mainStack.show(); + + QObject::connect(powerOn, &PowerOnWindow::powerOnFinished, &mainStack, [&](){ + mainStack.setCurrentWidget(home); + }); + + return a.exec(); +} \ No newline at end of file diff --git a/poweron.ui b/poweron.ui new file mode 100644 index 0000000..c3bf460 --- /dev/null +++ b/poweron.ui @@ -0,0 +1,26 @@ + + + poweronPage + + + + 0 + 0 + 1280 + 800 + + + + false + + + QWidget#poweronPage { + border-image: url(:/res/logo_1280x800.png); +} + + + + + + + diff --git a/poweronwindow.cpp b/poweronwindow.cpp new file mode 100644 index 0000000..9d812ef --- /dev/null +++ b/poweronwindow.cpp @@ -0,0 +1,22 @@ +#include "poweronwindow.h" +#include "ui_poweron.h" + +PowerOnWindow::PowerOnWindow(QWidget *parent) : + QWidget(parent), + ui(new Ui::poweronPage), + m_progressValue(0) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + resize(1280, 800); + + m_switchTimer = new QTimer(this); + m_switchTimer->setSingleShot(true); + connect(m_switchTimer, &QTimer::timeout, this, &PowerOnWindow::powerOnFinished); + m_switchTimer->start(2000); +} + +PowerOnWindow::~PowerOnWindow() +{ + delete ui; +} diff --git a/poweronwindow.h b/poweronwindow.h new file mode 100644 index 0000000..a05481a --- /dev/null +++ b/poweronwindow.h @@ -0,0 +1,29 @@ +#ifndef POWERONWINDOW_H +#define POWERONWINDOW_H + +#include +#include + +namespace Ui { +class poweronPage; +} + +class PowerOnWindow : public QWidget +{ + Q_OBJECT + +public: + explicit PowerOnWindow(QWidget *parent = nullptr); + ~PowerOnWindow(); + +signals: + void powerOnFinished(); + +private: + Ui::poweronPage *ui; + QTimer *m_progressTimer; + QTimer *m_switchTimer; + int m_progressValue; +}; + +#endif \ No newline at end of file diff --git a/record.ui b/record.ui new file mode 100644 index 0000000..04d4216 --- /dev/null +++ b/record.ui @@ -0,0 +1,114 @@ + + + RecordPage + + + + 0 + 0 + 1120 + 700 + + + + false + + + QWidget#RecordPage{ + border-image: url(:/res/record_1120x700.png); +} + + + + + 760 + 80 + 281 + 51 + + + + TextLabel + + + + + + 770 + 160 + 281 + 51 + + + + TextLabel + + + + + + 760 + 240 + 281 + 51 + + + + TextLabel + + + + + + 770 + 310 + 281 + 51 + + + + TextLabel + + + + + + 590 + 380 + 481 + 281 + + + + TextLabel + + + + + + 30 + 70 + 511 + 591 + + + + + + + 480 + 10 + 181 + 51 + + + + TextLabel + + + + + + + + diff --git a/recordpage.cpp b/recordpage.cpp new file mode 100644 index 0000000..a60c656 --- /dev/null +++ b/recordpage.cpp @@ -0,0 +1,90 @@ +#include "recordpage.h" +#include "ui_record.h" +#include "dbusmanager.h" +#include +#include +#include +#include +#include + +RecordPage::RecordPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::RecordPage) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &RecordPage::updateFromState, Qt::UniqueConnection); +} + +RecordPage::~RecordPage() { delete ui; } + +void RecordPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + + QString recordTitle; + switch (state) { + case 0: case 1: case 2: recordTitle = QStringLiteral("自检中 - 暂无记录"); break; + case 3: recordTitle = QStringLiteral("就绪 - 暂无记录"); break; + case 4: case 5: case 6: recordTitle = QStringLiteral("检测进行中"); break; + case 7: recordTitle = QStringLiteral("最近检测结果"); break; + case 8: recordTitle = QStringLiteral("调试模式"); break; + default: recordTitle = data.value("msg").toString(); break; + } + ui->lab_record_title->setText(recordTitle); + + static int s_seq = 0; + int finishRes = data.value("res").toInt(-1); + + /* number: 自增序号(格式 YYYYMMDD + NNNN) */ + if (state == 7 && finishRes >= 0) { + ++s_seq; + QString seqStr = QString("%1%2") + .arg(QDateTime::currentDateTime().toString("yyyyMMdd")) + .arg(s_seq, 4, 10, QChar('0')); + ui->lab_test_number->setText(seqStr); + + ui->lab_test_type->setText(QStringLiteral("标准检测")); + ui->lab_test_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); + ui->lab_test_result->setText(finishRes == 1 ? QStringLiteral("通过") + : QStringLiteral("失败")); + ui->lab_test_result->setStyleSheet(finishRes == 1 + ? QStringLiteral("color:#2ecc71; font-weight:bold;") + : QStringLiteral("color:#e74c3c; font-weight:bold;")); + + /* 列表里保留最近一条 */ + ui->list_test_record->clear(); + QString line = QString("%1 %2 %3 %4") + .arg(ui->lab_test_number->text(), 14) + .arg(ui->lab_test_type->text(), 10) + .arg(ui->lab_test_time->text(), 22) + .arg(ui->lab_test_result->text(), 6); + new QListWidgetItem(line, ui->list_test_record); + } + + /* 自检状态也列出自检结果概览 */ + if ((state == 1 || state == 2) && data.contains("res")) { + QJsonValue rv = data.value("res"); + if (rv.isArray()) { + QJsonArray arr = rv.toArray(); + int pass = 0, fail = 0, waiting = 0, testing = 0; + for (const QJsonValue &v : arr) { + int x = v.toInt(0); + if (x == 1) ++pass; + else if (x == -1) ++fail; + else if (x == 2) ++testing; + else ++waiting; + } + ui->lab_test_number->setText(QStringLiteral("—")); + ui->lab_test_type->setText(QStringLiteral("自检")); + ui->lab_test_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); + QString summary = QStringLiteral("通过%1 失败%2 检测中%3 等待%4") + .arg(pass).arg(fail).arg(testing).arg(waiting); + ui->lab_test_result->setText(summary); + ui->lab_test_rimage->setText(state == 2 ? QStringLiteral("自检失败") + : QStringLiteral("自检进行中")); + } + } +} \ No newline at end of file diff --git a/recordpage.h b/recordpage.h new file mode 100644 index 0000000..3e3d375 --- /dev/null +++ b/recordpage.h @@ -0,0 +1,26 @@ +#ifndef RECORDPAGE_H +#define RECORDPAGE_H + +#include +#include + +namespace Ui { +class RecordPage; +} + +class RecordPage : public QWidget +{ + Q_OBJECT + +public: + explicit RecordPage(QWidget *parent = nullptr); + ~RecordPage(); + +public slots: + void updateFromState(const QJsonObject &state); + +private: + Ui::RecordPage *ui; +}; + +#endif \ No newline at end of file diff --git a/res/debug_1120x700.png b/res/debug_1120x700.png new file mode 100644 index 0000000..5cf201c Binary files /dev/null and b/res/debug_1120x700.png differ diff --git a/res/home_1280x800.png b/res/home_1280x800.png new file mode 100644 index 0000000..3dd1ff5 Binary files /dev/null and b/res/home_1280x800.png differ diff --git a/res/login_1120x700.png b/res/login_1120x700.png new file mode 100644 index 0000000..5c9431c Binary files /dev/null and b/res/login_1120x700.png differ diff --git a/res/logo_1280x800.png b/res/logo_1280x800.png new file mode 100644 index 0000000..0c8e659 Binary files /dev/null and b/res/logo_1280x800.png differ diff --git a/res/record_1120x700.png b/res/record_1120x700.png new file mode 100644 index 0000000..638b03c Binary files /dev/null and b/res/record_1120x700.png differ diff --git a/res/selftest_1120x700.png b/res/selftest_1120x700.png new file mode 100644 index 0000000..168fcbc Binary files /dev/null and b/res/selftest_1120x700.png differ diff --git a/res/setting_1120x700.png b/res/setting_1120x700.png new file mode 100644 index 0000000..e814ad1 Binary files /dev/null and b/res/setting_1120x700.png differ diff --git a/res/test.qrc b/res/test.qrc new file mode 100644 index 0000000..b7467b6 --- /dev/null +++ b/res/test.qrc @@ -0,0 +1,12 @@ + + + selftest_1120x700.png + debug_1120x700.png + home_1280x800.png + login_1120x700.png + logo_1280x800.png + record_1120x700.png + setting_1120x700.png + test_1120x700.png + + diff --git a/res/test_1120x700.png b/res/test_1120x700.png new file mode 100644 index 0000000..179efc9 Binary files /dev/null and b/res/test_1120x700.png differ diff --git a/selftest.ui b/selftest.ui new file mode 100644 index 0000000..0e4a53c --- /dev/null +++ b/selftest.ui @@ -0,0 +1,157 @@ + + + SelftestPage + + + + 0 + 0 + 1120 + 700 + + + + false + + + QWidget#SelftestPage{ + border-image: url(:/res/selftest_1120x700.png); + +} + + + + + 220 + 180 + 311 + 51 + + + + OK + + + + + + 450 + 50 + 181 + 61 + + + + SelfTest + + + + + + 230 + 310 + 311 + 51 + + + + OK + + + + + + 230 + 430 + 311 + 51 + + + + OK + + + + + + 230 + 550 + 311 + 51 + + + + OK + + + + + + 750 + 180 + 311 + 51 + + + + OK + + + + + + 740 + 310 + 311 + 51 + + + + OK + + + + + + 750 + 430 + 311 + 51 + + + + OK + + + + + + 750 + 550 + 311 + 51 + + + + OK + + + + + + 790 + 50 + 111 + 71 + + + + restart + + + + + + + + diff --git a/selftestpage.cpp b/selftestpage.cpp new file mode 100644 index 0000000..996b1ae --- /dev/null +++ b/selftestpage.cpp @@ -0,0 +1,123 @@ +#include "selftestpage.h" +#include "ui_selftest.h" +#include "dbusmanager.h" +#include +#include + +struct SelftestItem { QLabel *lab; int resIdx; const char *name; }; + +static QString resText(int v) +{ + switch (v) { + case 0: return QStringLiteral("待检测"); + case 1: return QStringLiteral("通过"); + case 2: return QStringLiteral("检测中"); + case -1: return QStringLiteral("失败"); + default: return QStringLiteral("状态%1").arg(v); + } +} +static QString resColor(int v) +{ + switch (v) { + case 1: return QStringLiteral("#2ecc71"); + case 2: return QStringLiteral("#f1c40f"); + case -1: return QStringLiteral("#e74c3c"); + default: return QStringLiteral("#95a5a6"); + } +} +static void applyRes(QLabel *lab, int v) +{ + if (!lab) return; + lab->setText(resText(v)); + lab->setStyleSheet(QStringLiteral("color:%1; font-weight:bold;").arg(resColor(v))); +} + +SelftestPage::SelftestPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::SelftestPage), + m_hasFault(false) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + if (ui->btn_selftest_restart) { + /* 初始:自检还没跑完,先禁用,等状态更新再决定是否点亮 */ + ui->btn_selftest_restart->setEnabled(false); + ui->btn_selftest_restart->setCursor(Qt::PointingHandCursor); + connect(ui->btn_selftest_restart, &QPushButton::clicked, + this, &SelftestPage::onRestartClicked, Qt::UniqueConnection); + } + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &SelftestPage::updateFromState, Qt::UniqueConnection); +} + +SelftestPage::~SelftestPage() { delete ui; } + +void SelftestPage::onRestartClicked() +{ + if (!ui->btn_selftest_restart || !ui->btn_selftest_restart->isEnabled()) return; + + /* 防连点:点完立刻禁用,等后端状态回到自检中/出新结果时再重新判定 */ + ui->btn_selftest_restart->setEnabled(false); + + emit restartSelftestRequested(); +} + +void SelftestPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + QString msg = data.value("msg").toString(); + + QString title; + if (state == 0) title = QStringLiteral("初始化中…"); + else if (state == 1) title = QStringLiteral("开机自检中"); + else if (state == 2) title = QStringLiteral("自检失败"); + else title = msg; + if (!title.isEmpty()) ui->lab_selftest_title->setText(title); + + if (!data.contains("res") && !data.contains("result")) { + /* 没有自检结果数组:根据 state 兜底决定按钮 */ + m_hasFault = (state == 2); + } else { + QJsonArray arr = data.contains("res") ? data.value("res").toArray() + : data.value("result").toArray(); + if (arr.isEmpty()) { + m_hasFault = (state == 2); + } else { + auto at = [&](int i) -> int { + if (i < 0 || i >= arr.size()) return 0; + QJsonValue v = arr.at(i); + if (v.isBool()) return v.toBool() ? 1 : -1; + return v.toInt(0); + }; + + bool anyFail = false; + SelftestItem mapping[] = { + { ui->lab_selftest_ody_2, 0, "vortex" }, + { ui->lab_selftest_lxj, 1, "centrifuge" }, + { ui->lab_selftest_yyq_1, 2, "pipette_1" }, + { ui->lab_selftest_yyq_2, 3, "pipette_2" }, + { ui->lab_selftest_yyq_3, 4, "pipette_3" }, + { ui->lab_selftest_yyq_4, 5, "pipette_4" }, + { ui->lab_selftest_robot, 6, "robot_arm" }, + { ui->lab_selftest_4g, 7, "4g_module" }, + { nullptr, -1, nullptr } + }; + for (int i = 0; mapping[i].lab; ++i) { + int v = at(mapping[i].resIdx); + if (v < 0) anyFail = true; + applyRes(mapping[i].lab, v); + } + m_hasFault = anyFail; + } + } + + /* ===== 按钮使能策略 ===== + * ✅ 使能: state == 2 (DEV_SELFTEST_FAILED) && 有失败项 + * ❌ 禁用: 其它任何情况(自检中 / 自检通过 / 还没开始 / 不在自检页等)*/ + if (ui->btn_selftest_restart) { + bool enable = (state == 2 /* DEV_SELFTEST_FAILED */) && m_hasFault; + ui->btn_selftest_restart->setEnabled(enable); + } +} \ No newline at end of file diff --git a/selftestpage.h b/selftestpage.h new file mode 100644 index 0000000..9e8caab --- /dev/null +++ b/selftestpage.h @@ -0,0 +1,36 @@ +#ifndef SELFTESTPAGE_H +#define SELFTESTPAGE_H + +#include +#include + +namespace Ui { +class SelftestPage; +} + +class SelftestPage : public QWidget +{ + Q_OBJECT + +public: + explicit SelftestPage(QWidget *parent = nullptr); + ~SelftestPage(); + +signals: + /* 用户点击"重新自检":要求后端重跑自检流程 */ + void restartSelftestRequested(); + +public slots: + void updateFromState(const QJsonObject &state); + +private slots: + void onRestartClicked(); + +private: + Ui::SelftestPage *ui; + /* 缓存是否存在失败项(res 数组有任何一个 <0 的), + 和 state==SELFTEST_FAILED 一起决定按钮是否可点 */ + bool m_hasFault; +}; + +#endif \ No newline at end of file diff --git a/setting.ui b/setting.ui new file mode 100644 index 0000000..1deb3a6 --- /dev/null +++ b/setting.ui @@ -0,0 +1,208 @@ + + + SettingPage + + + + 0 + 0 + 1120 + 700 + + + + false + + + QWidget#SettingPage{ + border-image: url(:/res/setting_1120x700.png); +} + + + + + 420 + 110 + 121 + 91 + + + + read + + + + + + 420 + 210 + 121 + 81 + + + + write + + + + + + 980 + 90 + 121 + 91 + + + + read + + + + + + 980 + 180 + 121 + 91 + + + + write + + + + + + 30 + 110 + 371 + 51 + + + + DEVICE IP: 192.168.10.100 + + + + + + 30 + 250 + 371 + 51 + + + + remote: 200.200.200.200 + + + + + + 30 + 180 + 371 + 51 + + + + rob: 192.168.10.100 + + + + + + 770 + 120 + 201 + 51 + + + + test type + + + + + + 850 + 180 + 101 + 51 + + + + 5:00 + + + + + + 860 + 250 + 101 + 51 + + + + 3000 + + + + + + 820 + 310 + 101 + 51 + + + + 5:00 + + + + + + 820 + 380 + 101 + 51 + + + + 5:00 + + + + + + 850 + 450 + 101 + 51 + + + + 1000 + + + + + + 420 + 0 + 181 + 61 + + + + TextLabel + + + + + + + + diff --git a/settingpage.cpp b/settingpage.cpp new file mode 100644 index 0000000..adf5377 --- /dev/null +++ b/settingpage.cpp @@ -0,0 +1,80 @@ +#include "settingpage.h" +#include "ui_setting.h" +#include "dbusmanager.h" + +SettingPage::SettingPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::SettingPage) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &SettingPage::updateFromState, Qt::UniqueConnection); + connect(DBusManager::instance(), &DBusManager::paramsUpdated, + this, &SettingPage::updateFromParams, Qt::UniqueConnection); + + connect(ui->btn_ip_read, &QPushButton::clicked, this, &SettingPage::onBtnIpReadClicked, Qt::UniqueConnection); + connect(ui->btn_ip_write, &QPushButton::clicked, this, &SettingPage::onBtnIpWriteClicked, Qt::UniqueConnection); + connect(ui->btn_para_read, &QPushButton::clicked, this, &SettingPage::onBtnParaReadClicked, Qt::UniqueConnection); + connect(ui->btn_para_write, &QPushButton::clicked, this, &SettingPage::onBtnParaWriteClicked, Qt::UniqueConnection); +} + +SettingPage::~SettingPage() { delete ui; } + +void SettingPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + QString title = QStringLiteral("系统设置"); + if (state == 8) title = QStringLiteral("系统设置(调试模式)"); + ui->lab_setting_title->setText(title); +} + +void SettingPage::updateFromParams(const QJsonObject &p) +{ + if (p.contains("dev_ip")) ui->lab_dev_ip->setText(p.value("dev_ip").toString()); + if (p.contains("rob_ip")) ui->lab_rob_ip->setText(p.value("rob_ip").toString()); + if (p.contains("srv_ip")) ui->lab_srv_ip->setText(p.value("srv_ip").toString()); + if (p.contains("test_type")) ui->lab_test_type->setText(p.value("test_type").toString()); + if (p.contains("lxj_time")) ui->lab_lxj_time->setText(p.value("lxj_time").toString()); + if (p.contains("lxj_speed")) ui->lab_lxj_speed->setText(p.value("lxj_speed").toString()); + if (p.contains("ody_time_1")) ui->lab_ody_time_1->setText(p.value("ody_time_1").toString()); + if (p.contains("ody_time_2")) ui->lab_ody_time_2->setText(p.value("ody_time_2").toString()); + if (p.contains("ody_speed")) ui->lab_ody_speed->setText(p.value("ody_speed").toString()); +} + +void SettingPage::onBtnIpReadClicked() { DBusManager::instance()->queryParams(); } +void SettingPage::onBtnParaReadClicked() { DBusManager::instance()->queryParams(); } + +void SettingPage::onBtnIpWriteClicked() +{ + QJsonObject p; + p["cmd"] = "update_params"; + p["dev_ip"] = ui->lab_dev_ip->text().trimmed(); + p["rob_ip"] = ui->lab_rob_ip->text().trimmed(); + p["srv_ip"] = ui->lab_srv_ip->text().trimmed(); + /* 其它参数也带上,避免丢失 */ + p["test_type"] = ui->lab_test_type->text(); + p["lxj_time"] = ui->lab_lxj_time->text(); + p["lxj_speed"] = ui->lab_lxj_speed->text(); + p["ody_time_1"] = ui->lab_ody_time_1->text(); + p["ody_time_2"] = ui->lab_ody_time_2->text(); + p["ody_speed"] = ui->lab_ody_speed->text(); + DBusManager::instance()->updateParams(p); +} + +void SettingPage::onBtnParaWriteClicked() +{ + QJsonObject p; + p["cmd"] = "update_params"; + p["dev_ip"] = ui->lab_dev_ip->text().trimmed(); + p["rob_ip"] = ui->lab_rob_ip->text().trimmed(); + p["srv_ip"] = ui->lab_srv_ip->text().trimmed(); + p["test_type"] = ui->lab_test_type->text(); + p["lxj_time"] = ui->lab_lxj_time->text(); + p["lxj_speed"] = ui->lab_lxj_speed->text(); + p["ody_time_1"] = ui->lab_ody_time_1->text(); + p["ody_time_2"] = ui->lab_ody_time_2->text(); + p["ody_speed"] = ui->lab_ody_speed->text(); + DBusManager::instance()->updateParams(p); +} \ No newline at end of file diff --git a/settingpage.h b/settingpage.h new file mode 100644 index 0000000..6c965d2 --- /dev/null +++ b/settingpage.h @@ -0,0 +1,33 @@ +#ifndef SETTINGPAGE_H +#define SETTINGPAGE_H + +#include +#include + +namespace Ui { +class SettingPage; +} + +class SettingPage : public QWidget +{ + Q_OBJECT + +public: + explicit SettingPage(QWidget *parent = nullptr); + ~SettingPage(); + +public slots: + void updateFromState(const QJsonObject &state); + void updateFromParams(const QJsonObject ¶ms); + +private slots: + void onBtnIpReadClicked(); + void onBtnIpWriteClicked(); + void onBtnParaReadClicked(); + void onBtnParaWriteClicked(); + +private: + Ui::SettingPage *ui; +}; + +#endif \ No newline at end of file diff --git a/test.ui b/test.ui new file mode 100644 index 0000000..717000b --- /dev/null +++ b/test.ui @@ -0,0 +1,260 @@ + + + TestPage + + + + 0 + 0 + 1120 + 700 + + + + QWidget#TestPage{ + border-image: url(:/res/test_1120x700.png); +} + + + + + 450 + 20 + 181 + 51 + + + + TextLabel + + + + + + 20 + 90 + 241 + 81 + + + + TextLabel + + + + + + 290 + 90 + 241 + 81 + + + + true + + + 3. + + + + + + 20 + 190 + 241 + 81 + + + + TextLabel + + + + + + 290 + 190 + 241 + 81 + + + + TextLabel + + + + + + 20 + 290 + 241 + 81 + + + + TextLabel + + + + + + 290 + 290 + 241 + 81 + + + + TextLabel + + + + + + 20 + 390 + 241 + 81 + + + + TextLabel + + + + + + 290 + 400 + 241 + 81 + + + + TextLabel + + + + + + 20 + 490 + 241 + 81 + + + + TextLabel + + + + + + 290 + 490 + 241 + 81 + + + + TextLabel + + + + + + 20 + 590 + 201 + 81 + + + + TextLabel + + + + + + 290 + 590 + 231 + 81 + + + + TextLabel + + + + + + 560 + 90 + 161 + 151 + + + + PushButton + + + + + + 750 + 90 + 161 + 151 + + + + PushButton + + + + + + 940 + 90 + 161 + 151 + + + + PushButton + + + + + + 550 + 260 + 551 + 381 + + + + TextLabel + + + + + + 30 + 20 + 121 + 51 + + + + 恩诺沙星 + + + + + + + + diff --git a/testpage.cpp b/testpage.cpp new file mode 100644 index 0000000..1ea1416 --- /dev/null +++ b/testpage.cpp @@ -0,0 +1,128 @@ +#include "testpage.h" +#include "ui_test.h" +#include "dbusmanager.h" +#include +#include + +static const char *tStepNames[] = { + "", + "加提取液", + "涡动", + "离心", + "提取样本液(ç§»2)", + "加提取液(ç§»3)", + "涡动", + "提取样本液(ç§»4)", + "滴入试纸", + "等待结果", + "拍照分析", + "检测完成" +}; + +static void setStepLabel(QLabel *lab, int stepIdx, int currentStep, int deviceState) +{ + if (!lab) return; + const char *name = (stepIdx >= 1 && stepIdx <= 11) ? tStepNames[stepIdx] : ""; + QString text = QStringLiteral("%1.%2").arg(stepIdx, 2).arg(QString::fromUtf8(name)); + + bool finished = (deviceState == 7) || (currentStep > 0 && stepIdx < currentStep); + bool current = (currentStep > 0 && stepIdx == currentStep); + + if (finished) { + lab->setText(text + " ✓"); + lab->setStyleSheet("color:#2ecc71; font-weight:bold;"); + } else if (current) { + lab->setText(text + " 进行中"); + lab->setStyleSheet("color:#f39c12; font-weight:bold; background:#fff6e0;"); + } else { + lab->setText(text); + lab->setStyleSheet("color:#95a5a6;"); + } +} + +TestPage::TestPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::TestPage) +{ + ui->setupUi(this); + setAttribute(Qt::WA_StyledBackground, true); + + connect(DBusManager::instance(), &DBusManager::stateUpdated, + this, &TestPage::updateFromState, Qt::UniqueConnection); + connect(ui->btn_test_start, &QPushButton::clicked, this, &TestPage::onBtnStartClicked, Qt::UniqueConnection); + connect(ui->btn_test_pause, &QPushButton::clicked, this, &TestPage::onBtnPauseClicked, Qt::UniqueConnection); + connect(ui->btn_test_stop, &QPushButton::clicked, this, &TestPage::onBtnStopClicked, Qt::UniqueConnection); +} + +TestPage::~TestPage() { delete ui; } + +void TestPage::updateFromState(const QJsonObject &data) +{ + int state = data.value("state").toInt(-1); + int step = data.value("step").toInt(0); + int fault = data.value("fault").toInt(0); + int finalRes = data.value("res").toInt(-1); + + QString head; + switch (state) { + case 0: head = QStringLiteral("初始化"); break; + case 1: head = QStringLiteral("自检中"); break; + case 2: head = QStringLiteral("自检失败"); break; + case 3: head = QStringLiteral("就绪 - 点击开始"); break; + case 4: head = QStringLiteral("自动检测中"); break; + case 5: head = QStringLiteral("已暂停"); break; + case 6: head = QStringLiteral("检测异常"); break; + case 7: head = (finalRes == 1) ? QStringLiteral("检测完成:通过 ✓") + : QStringLiteral("检测完成:失败 ✗"); + break; + case 8: head = QStringLiteral("调试模式"); break; + default: head = data.value("msg").toString(); break; + } + ui->lab_title->setText(head); + + /* 按钮使能 */ + ui->btn_test_start->setEnabled(state == 3 || state == 5); + ui->btn_test_pause->setEnabled(state == 4); + ui->btn_test_stop ->setEnabled(state == 4 || state == 5 || state == 6); + + /* 信息栏 */ + QString info; + QJsonObject timer = data.value("timer").toObject(); + int total = timer.value("total").toInt(0); + int remain = timer.value("remain").toInt(0); + if (total > 0) { + info = QStringLiteral("计时: %1/%2s ").arg(remain).arg(total); + } + if (fault != 0) { + info += QStringLiteral(" 故障码:%1").arg(fault); + } + if (state == 7 && finalRes >= 0) { + info += QStringLiteral(" 结果:%1").arg(finalRes == 1 ? "通过" : "失败"); + } + ui->lab_test_info->setText(info); + + /* 步骤标签 1..10 → lab_test_1..10;步骤11 → lab_test_11_1 + lab_test_11_2 */ + QLabel *lab10[] = { + nullptr, ui->lab_test_1, ui->lab_test_2, ui->lab_test_3, ui->lab_test_4, + ui->lab_test_5, ui->lab_test_6, ui->lab_test_7, ui->lab_test_8, + ui->lab_test_9, ui->lab_test_10 + }; + for (int i = 1; i <= 10; ++i) setStepLabel(lab10[i], i, step, state); + + /* 步骤11:lab_test_11_1 显示步骤名,lab_test_11_2 显示最终结果 */ + setStepLabel(ui->lab_test_11_1, 11, step, state); + if (state == 7) { + ui->lab_test_11_2->setText(finalRes == 1 ? QStringLiteral("通过 ✓") + : QStringLiteral("失败 ✗")); + ui->lab_test_11_2->setStyleSheet(finalRes == 1 + ? QStringLiteral("color:#2ecc71; font-weight:bold;") + : QStringLiteral("color:#e74c3c; font-weight:bold;")); + } else { + ui->lab_test_11_2->setText(QString()); + ui->lab_test_11_2->setStyleSheet(QString()); + } +} + +void TestPage::onBtnStartClicked() { DBusManager::instance()->sendUserCmd("start_detect"); } +void TestPage::onBtnPauseClicked() { DBusManager::instance()->sendUserCmd("pause_detect"); } +void TestPage::onBtnStopClicked() { DBusManager::instance()->sendUserCmd("stop_detect"); } \ No newline at end of file diff --git a/testpage.h b/testpage.h new file mode 100644 index 0000000..7bde63f --- /dev/null +++ b/testpage.h @@ -0,0 +1,31 @@ +#ifndef TESTPAGE_H +#define TESTPAGE_H + +#include +#include + +namespace Ui { +class TestPage; +} + +class TestPage : public QWidget +{ + Q_OBJECT + +public: + explicit TestPage(QWidget *parent = nullptr); + ~TestPage(); + +public slots: + void updateFromState(const QJsonObject &state); + +private slots: + void onBtnStartClicked(); + void onBtnPauseClicked(); + void onBtnStopClicked(); + +private: + Ui::TestPage *ui; +}; + +#endif \ No newline at end of file