feat(vision): 状态栏增加相机状态

This commit is contained in:
lidg
2026-10-29 11:57:47 +08:00
parent a7af930a0a
commit 31454722a0
9 changed files with 92 additions and 26 deletions
+7
View File
@@ -1,5 +1,12 @@
# VisionGuide 独立进程接入交付记录
## 2026-10-28:单实例与启动复用
- VisionGuide 默认开启 `ssp_visionguide_v1` IPC。SDK 初始化及主窗口创建前,以固定用户数据目录下的 QLockFile 保证同用户单实例;重复启动正常退出,不初始化相机。`--ipc-name` 仍可覆盖端点名,但不绕过单实例锁。升级时先关闭不支持该锁的旧版本。
- ssp“启动”先连接现有实例,仅端点不存在或拒绝连接才创建一次子进程;已有服务可在 executablePath 无效时复用。旧连接尚未释放导致 hello 前断开时,在原截止时间内重连,不重复创建进程。初始化、测量和取料协议保持原约定。
- 退出只关闭自身启动且 PID 匹配的服务。发送 shutdown 后保持管道直到进程退出,避免立即关闭导致请求未读;原有 3 秒延迟强杀绑定启动代次,不影响随后启动的新进程。
- 验证:ssp IPC 16 passed、实际入口/SDK替身 5 passed、32位客户端/64位服务端跨进程 9 passed,共 30 passed。ssp 32/64位、VisionGuide Debug/Release 编译及运行库部署通过;未运行真实相机/PLC。设计见 `docs/superpowers/specs/2026-10-28-vision-single-instance-design.md`。测试仍遵循既有 Git 忽略规则,未自动提交。
## 2026-10-28:按最新确认改为拍照到位前置流程
本节是当前执行协议;下方早期记录中的 850–854 五信号握手、视觉必须 ready 才能启动生产、视觉失败即人工锁定均已被本节替代。
+4
View File
@@ -2,6 +2,8 @@
两端使用 Qt 5.14 的 QLocalSocket / QLocalServer。每帧为 4 字节无符号大端长度,随后为 UTF-8 JSON object;长度必须为 1..1048576。支持分包和连续多帧,非法帧断开。一次只允许一个控制客户端、一个测量。消息不含图像。
VisionGuide 默认监听 `ssp_visionguide_v1`,可用 `--ipc-name` 覆盖。启动时在 SDK 初始化和主窗口创建前,使用用户数据目录下的固定 QLockFile 保证同用户单实例;不同 IPC 名及程序副本也不能同时初始化相机。重复实例正常退出。ssp“启动”先尝试连接,只有端点不存在或拒绝连接才启动一次程序;握手失败不再启动进程。“连接”仅连接已有程序。复用外部实例时不发送 shutdown;仅自身启动且 PID 匹配的子进程可由 ssp 关闭。
## 公共字段
所有请求/响应含 `protocol_version:1`、字符串 `type`、字符串 `request_id`、字符串 `server_session_id`。服务进程每次启动产生新 session。`hello` 请求的 session 为空;响应提供本进程 session。后续请求必须使用该 session。所有 request_id 不重复使用;断线不自动重发,旧 session / 已终止请求的结果不可使用。
@@ -26,6 +28,8 @@
状态响应还提供字符串 `server_process_id`。ssp 只有在该值与自身 QProcess 启动的子进程 PID 一致时才发送 shutdown;连接外部实例时退出仅断开。
向自身实例发送 shutdown 后保持管道,直到子进程退出;保留原有 3 秒强杀兜底,回调仅针对该启动代次。关闭期间不再处理业务应答,避免清空会话后误把退出应答当作会话错误而提前断管道。
## measure 请求
```json
+1 -12
View File
@@ -176,8 +176,6 @@ void RackPage::updateTrayCells(const QList<TraySlot> &traySlots)
const QStringList colors = QStringList()
<< "#90a4ae" << "#f9a825" << "#1e88e5" << "#8e24aa"
<< "#2e7d32" << "#d32f2f" << "#ef6c00";
const QStringList names = QStringList()
<< "空" << "待" << "正检" << "反检" << "OK" << "NG" << "异常";
for (int index = 0; index < trayCells.size(); ++index) {
const int rowNo = index / 7 + 1;
@@ -191,10 +189,8 @@ void RackPage::updateTrayCells(const QList<TraySlot> &traySlots)
}
QString state = "EMPTY";
int workpieceId = 0;
if (slot) {
state = slot->state;
workpieceId = slot->workpieceId;
}
int stateIndex = 0;
@@ -212,14 +208,7 @@ void RackPage::updateTrayCells(const QList<TraySlot> &traySlots)
stateIndex = 6;
}
const QString workpieceText = workpieceId > 0
? QString("工件 %1").arg(workpieceId) : QString();
trayCells.at(index)->setText(QString("%1-%2\n%3%4")
.arg(rowNo)
.arg(columnNo)
.arg(names.at(stateIndex))
.arg(workpieceText.isEmpty() ? QString()
: "\n" + workpieceText));
trayCells.at(index)->setText(QString("%1-%2").arg(rowNo).arg(columnNo));
trayCells.at(index)->setStyleSheet(
QString("QLabel { background: %1; border: 1px solid #ffffff; "
"border-radius: 3px; color: white; font-size: 11px; }")
+2 -1
View File
@@ -101,7 +101,8 @@ VisionPage::VisionPage(VisionService *service, QWidget *parent)
if (status.contains("initialization")) {
const QJsonObject initialization = status.value("initialization").toObject();
QStringList details;
for (const QString &camera : QStringList() << "left" << "right") {
const QStringList cameras = QStringList() << "left" << "right";
for (const QString &camera : cameras) {
const QJsonObject state = initialization.value(camera).toObject();
details.append(QString("%1:连接%2 / 参数%3 / 白平衡%4")
.arg(camera == "left" ? "左相机" : "右相机",
+54 -12
View File
@@ -51,6 +51,7 @@ VisionService::VisionService(const VisionConfig &config, QObject *parent)
m_initializeTimer->setSingleShot(true);
connect(m_connectTimer, &QTimer::timeout, this, &VisionService::connectAttempt);
connect(m_socket, &QLocalSocket::connected, this, [this]() {
m_startIfUnavailable = false;
m_connectTimer->stop();
m_buffer.clear();
m_session.clear();
@@ -60,12 +61,29 @@ VisionService::VisionService(const VisionConfig &config, QObject *parent)
});
connect(m_socket, &QLocalSocket::readyRead, this, &VisionService::readMessages);
connect(m_socket, &QLocalSocket::disconnected, this, [this]() {
if (!m_connecting)
if (m_connecting) {
// The previous controller may still be disconnecting. Retry hello
// within the original deadline without launching another process.
m_pollTimer->stop();
m_commands.clear();
m_helloId.clear();
m_buffer.clear();
m_connectTimer->start();
} else {
failConnection("视觉进程连接已断开");
}
});
// Qt 5.14 exposes error(...), not the newer errorOccurred socket signal.
connect(m_socket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
this, [this](QLocalSocket::LocalSocketError) {
this, [this](QLocalSocket::LocalSocketError error) {
if (m_connecting && m_startIfUnavailable) {
m_startIfUnavailable = false;
if (error == QLocalSocket::ServerNotFoundError || error == QLocalSocket::ConnectionRefusedError)
launchProcess();
else
failConnection(m_socket->errorString());
return;
}
if (!m_connecting)
failConnection(m_socket->errorString());
});
@@ -100,8 +118,12 @@ VisionService::VisionService(const VisionConfig &config, QObject *parent)
failConnection(m_process->errorString());
});
connect(m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
this, [this](int code, QProcess::ExitStatus) {
this, [this](int code, QProcess::ExitStatus status) {
emit logMessage(QString("视觉子进程已退出,退出码 %1").arg(code));
// A simultaneous launch can lose the instance lock. Keep waiting for
// the winning process rather than aborting its pending IPC connection.
if (m_connecting && code == 0 && status == QProcess::NormalExit)
return;
if (m_serverProcessId == QString::number(m_process->processId()) || m_connecting)
failConnection("视觉子进程已退出");
});
@@ -175,6 +197,7 @@ void VisionService::disconnectService()
return;
}
if (!m_request.isEmpty()) cancel(m_request.value("request_id").toString());
m_startIfUnavailable = false;
m_connecting = false;
m_connectTimer->stop();
m_pollTimer->stop();
@@ -185,12 +208,19 @@ void VisionService::disconnectService()
void VisionService::startService()
{
if (m_process->state() != QProcess::NotRunning || m_connecting
|| m_socket->state() == QLocalSocket::ConnectedState)
if (m_connecting || m_socket->state() == QLocalSocket::ConnectedState)
return;
m_startIfUnavailable = m_process->state() == QProcess::NotRunning;
connectService();
}
void VisionService::launchProcess()
{
if (!m_connecting || m_shuttingDown)
return;
const QFileInfo executable(m_config.executablePath);
if (!executable.isFile()) {
emit logMessage("请在 config.ini 配置有效的 VisionGuide executablePath");
failConnection("请在 config.ini 配置有效的 VisionGuide executablePath");
return;
}
QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
@@ -209,9 +239,10 @@ void VisionService::startService()
environment.insert("PATH", cleanPath.join(';'));
m_process->setProcessEnvironment(environment);
m_process->setWorkingDirectory(executable.absolutePath());
++m_processGeneration;
m_connectElapsed.restart();
m_process->start(executable.absoluteFilePath(),
QStringList() << "--ipc-name" << m_config.ipcName << "--background");
connectService();
}
void VisionService::connectAttempt()
@@ -254,6 +285,10 @@ bool VisionService::sendMessage(const QJsonObject &message)
void VisionService::readMessages()
{
if (m_shuttingDown) {
if (m_socket->isOpen()) m_socket->readAll();
return;
}
m_buffer.append(m_socket->readAll());
while (m_buffer.size() >= 4) {
const quint32 size = qFromBigEndian<quint32>(reinterpret_cast<const uchar *>(m_buffer.constData()));
@@ -472,19 +507,25 @@ void VisionService::shutdown()
if (m_shuttingDown) return;
m_shuttingDown = true;
if (!m_request.isEmpty()) cancel(m_request.value("request_id").toString());
if (m_process->state() != QProcess::NotRunning
&& m_serverProcessId == QString::number(m_process->processId()) && !m_session.isEmpty()) {
const bool ownsServer = m_process->state() != QProcess::NotRunning
&& m_serverProcessId == QString::number(m_process->processId()) && !m_session.isEmpty();
if (ownsServer) {
sendCommand("shutdown");
m_socket->flush();
QTimer::singleShot(3000, m_process, [this]() {
if (m_process->state() != QProcess::NotRunning) m_process->kill();
const quint64 generation = m_processGeneration;
QTimer::singleShot(3000, m_process, [this, generation]() {
if (generation == m_processGeneration && m_process->state() != QProcess::NotRunning)
m_process->kill();
});
}
m_startIfUnavailable = false;
m_connecting = false;
m_connectTimer->stop();
m_pollTimer->stop();
m_initializeTimer->stop();
m_socket->disconnectFromServer();
// Keep the owned server's pipe open until it has read shutdown and exited.
// Closing immediately can discard unread data on Windows named pipes.
if (!ownsServer) m_socket->disconnectFromServer();
m_ready = false;
m_session.clear();
publishAvailability();
@@ -515,6 +556,7 @@ void VisionService::finishMeasurement(const QJsonObject &result)
void VisionService::failConnection(const QString &message)
{
const bool hadConnection = m_connecting || !m_session.isEmpty() || !m_request.isEmpty();
m_startIfUnavailable = false;
m_connecting = false;
m_connectTimer->stop();
m_pollTimer->stop();
+3
View File
@@ -45,6 +45,7 @@ signals:
void logMessage(const QString &message);
private:
void launchProcess();
void connectAttempt();
void readMessages();
void handleMessage(const QJsonObject &message);
@@ -83,6 +84,8 @@ private:
bool m_maintenanceAllowed = false;
bool m_diagnostic;
bool m_connecting;
bool m_startIfUnavailable = false;
quint64 m_processGeneration = 0;
bool m_shuttingDown;
};
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 4.11.0, 2026-10-28T00:07:08. -->
<!-- Written by QtCreator 4.11.0, 2026-10-28T20:48:37. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
+19
View File
@@ -19,6 +19,7 @@
#include <QLabel>
#include <QListWidget>
#include <QStackedWidget>
#include <QTimer>
#include <QVBoxLayout>
Widget::Widget(QWidget *parent)
@@ -38,6 +39,7 @@ Widget::Widget(QWidget *parent)
, plcStatusLabel(nullptr)
, robotStatusLabel(nullptr)
, safetyStatusLabel(nullptr)
, cameraStatusLabel(nullptr)
{
ui->setupUi(this);
setWindowTitle("小轴多参数上下料单元管控系统");
@@ -103,9 +105,14 @@ void Widget::setupTopBar(QVBoxLayout *rootLayout)
plcStatusLabel = UiHelpers::makeBadge("PLC:未采集", "#607d8b");
robotStatusLabel = UiHelpers::makeBadge("机器人:未采集", "#607d8b");
safetyStatusLabel = UiHelpers::makeBadge("安全回路:未采集", "#607d8b");
cameraStatusLabel = UiHelpers::makeBadge(
ConfigManager::instance().visionConfig().enabled
? "相机:离线" : "相机:未启用",
"#607d8b");
topLayout->addWidget(plcStatusLabel);
topLayout->addWidget(robotStatusLabel);
topLayout->addWidget(safetyStatusLabel);
topLayout->addWidget(cameraStatusLabel);
rootLayout->addWidget(topBar);
}
@@ -184,6 +191,18 @@ void Widget::setupMainArea(QVBoxLayout *rootLayout)
connect(visionService, &VisionService::logMessage, this, [this](const QString &message) {
appendLog("生产日志", "视觉引导", "通信/测量", message, "记录");
});
connect(visionService, &VisionService::availabilityChanged,
this, [this](bool ready, bool, const QString &session) {
if (!ConfigManager::instance().visionConfig().enabled) {
cameraStatusLabel->setText("相机:未启用");
} else if (session.isEmpty()) {
cameraStatusLabel->setText("相机:离线");
} else {
cameraStatusLabel->setText(ready ? "相机:就绪" : "相机:在线");
}
});
if (ConfigManager::instance().visionConfig().enabled)
QTimer::singleShot(0, visionService, &VisionService::startService);
}
void Widget::appendLog(const QString &type, const QString &module, const QString &action,
+1
View File
@@ -47,6 +47,7 @@ private:
QLabel *plcStatusLabel;
QLabel *robotStatusLabel;
QLabel *safetyStatusLabel;
QLabel *cameraStatusLabel;
};
#endif // WIDGET_H