feat: 新增收集式校验错误弹窗及工位报警语音播报

新增 ErrorListDialog 组件用于统一展示结构化校验错误信息,实现报错一次收全;新增工位报警语音播报功能,通过浏览器 SpeechSynthesis 播放本工位相关报警;调整物料类别及序列号字段文案,移除「其他」类别;新增工单实际开始字段及采集方式配置;优化 AGV 及 PlcSend 页签刷新逻辑;新增看板物料追溯及工位报警接口;删除 PLC 强制写 M 位及相关测试代码;同步数据库字段注释及补丁。
This commit is contained in:
SunYF
2026-10-20 16:36:26 +08:00
parent f743cf21fb
commit b0c048d9aa
126 changed files with 4603 additions and 1639 deletions
@@ -133,6 +133,12 @@ export const offlineFinish = (data) => request.post('/api/workpiece/done', data)
// → {hasMismatch, stationNo, plcBit, detail, options, graceWindow}
export const mismatchCheck = (data) => request.post('/api/plc/mismatch/check', data)
// ---------- 本工位相关报警(谁受影响谁播报,2026-10-20) ----------
// 终端 30 秒轮询:?stationNo=&minutes= → [ {id,type,level,target,title,content,createdAt} ]
// 仅返回最近 minutes 分钟内 UNREAD 且命中「工位N」的报警;MES 不可达静默返回 []
export const getStationAlerts = (stationNo, minutes = 10) =>
request.get('/api/alerts/station', { params: { stationNo, minutes } })
// ---------- 工位停单 / 恢复接单(代理 MES 内部 API) ----------
// 停单/恢复:{stationNo, paused, reason}(paused=true 停止接单,false 恢复)
export const pauseStation = (data) => request.post('/api/station/pause', data)
+9 -1
View File
@@ -52,6 +52,14 @@ export const helpWorkstation = {
{ name: '结果 合格/不合格', source: '系统自动判定。依据扭矩/角度是否在工艺标准范围内。', purpose: '该颗螺丝是否合格;有不合格必须复检', fill: '不合格时按告警横幅提示优先复检该工件' }
]
},
{
title: '检测确认与操作工签字(业务说明)',
overview: '作业页里,带"检测确认"或"操作工签字"的工艺步骤,做完必须确认/签字才能报工流转。',
fields: [
{ name: '检测确认', source: '工艺步骤配置(MES 下发)。', purpose: '声明这道步骤已自检合格,作为"合格"的前置证据', fill: '该步骤动作做完后点「检测确认」;不确认则报工被拦、工件不能流转' },
{ name: '操作工签字', source: '当前登录账号(本机操作人)。', purpose: '记录"这步是我做的、我确认合格",按操作工身份留痕', fill: '由当前登录人确认;不签字则报工被拦、工件不能流转' }
]
},
{
title: '底部三大按钮',
fields: [
@@ -106,7 +114,7 @@ export const helpOnline = {
title: '领料确认(按物料清单核对)',
overview: '按产品物料清单列出本台应领物料,操作员逐项核对后勾选确认。',
fields: [
{ name: '应领料清单', source: 'MES 物料清单。按产品编码查询。', purpose: '列明单台用量、图号、规格、管理方式、装配工位,指导备料', fill: '对照实物逐项核对,确认无误后勾选「我已核对」' },
{ name: '应领料清单', source: 'MES 物料清单。按产品编码查询。', purpose: '列明单台用量、图号、规格、序列号、装配工位,指导备料', fill: '对照实物逐项核对,确认无误后勾选「我已核对」' },
{ name: '已核对勾选', source: '操作员确认。', purpose: '未勾选则无法提交建档,防止漏料上线', fill: '核对完成后勾选;有物料清单时必须勾选' }
]
},
@@ -77,10 +77,12 @@ export const currentStepId = computed(() => currentStep.value?.id || 0)
// ---------- 派生数据 ----------
export const taskSteps = computed(() => (Array.isArray(state.task?.steps) ? state.task.steps : []))
export const manualSteps = computed(() => taskSteps.value.filter((s) => s.collectType === 'MANUAL'))
// 人工录入步骤:手填/扫码(2026-10-19 采集方式新增「扫码」,与手填等价,采一串字符串)
export const manualSteps = computed(() => taskSteps.value.filter((s) => s.collectType === 'MANUAL' || s.collectType === 'SCAN'))
export const autoSteps = computed(() => taskSteps.value.filter((s) => s.collectType === 'AUTO'))
// 拧紧工艺步骤(需要拧紧枪的步骤):应拧颗数 = 拧紧步骤数量,每个拧紧步骤录入一条扭矩数据
export const torqueSteps = computed(() => autoSteps.value.filter((s) => s.isTorque))
// 拧紧工艺步骤(需要拧紧枪的步骤)= 采集方式为「拧紧枪自动(AUTO)」的步骤:应拧颗数 = 拧紧步骤数量,每个拧紧步骤录入一条扭矩数据
// (2026-10-19:is_torque 字段已删,与 collectType=AUTO 完全重复,统一按采集方式判定)
export const torqueSteps = computed(() => autoSteps.value)
export const torqueStepCount = computed(() => torqueSteps.value.length)
// 某拧紧步骤已录入的记录(tightRows 已按当前工件 SN 过滤,按 stepId 匹配)
export const torqueRowOfStep = (stepId) =>
@@ -0,0 +1,35 @@
// 工位终端语音播报(2026-10-20「谁受影响谁播报」):
// 复用大屏 SpeechSynthesis 方案,中文播报本工位相关报警;无播音设备时静默降级。
// 去重由调用方负责(Main.vue 按 alert id 记账),本工具只负责把文本读出来。
let muted = false
export function isSpeechSupported() {
return typeof window !== 'undefined' && 'speechSynthesis' in window
}
export function setSpeechMuted(v) {
muted = !!v
if (muted && isSpeechSupported()) window.speechSynthesis.cancel()
}
export function isSpeechMuted() {
return muted
}
// speak 播报一段中文文本;正在播报时排队( SpeechSynthesis 自带队列),
// 单条最长 120 字,避免长文本拖太久。
export function speak(text) {
if (!text || muted || !isSpeechSupported()) return
const t = String(text).slice(0, 120)
try {
const u = new SpeechSynthesisUtterance(t)
u.lang = 'zh-CN'
u.rate = 1
u.pitch = 1
u.volume = 1
window.speechSynthesis.speak(u)
} catch {
/* 无播音设备/浏览器不支持:静默降级 */
}
}
@@ -22,6 +22,9 @@
待同步 {{ pendingTotal }}<template v-if="deadTotal"> · 待处理 {{ deadTotal }}</template>
</el-button>
<el-button size="large" @click="wlRef?.open()">我的工作量</el-button>
<el-button size="large" :title="speechMuted ? '语音播报已关闭,点击开启' : '语音播报中,点击静音'" @click="toggleSpeechMuted">
{{ speechMuted ? '🔇' : '🔊' }}
</el-button>
<span class="user-name">{{ user.name || user.username || '-' }}</span>
<span class="clock">{{ clock }}</span>
<el-button size="large" type="danger" plain @click="logout">退出</el-button>
@@ -71,7 +74,7 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessage, ElNotification } from 'element-plus'
import WorkPanel from './panels/WorkPanel.vue'
import MaterialPanel from './panels/MaterialPanel.vue'
import PdfPanel from './panels/PdfPanel.vue'
@@ -89,7 +92,8 @@ import {
helpPdf,
helpWorkstation
} from '../help'
import { stationLogout } from '../api'
import { stationLogout, getStationAlerts } from '../api'
import { speak, setSpeechMuted } from '../utils/speech'
import { clearAuth } from '../utils/request'
import {
hasNg,
@@ -143,6 +147,94 @@ let timerTask = null
let timerTight = null
let timerStats = null
let timerClock = null
let alertES = null // 本机报警 SSE(EventSource,断线自动重连)
// ---------- 本工位报警语音播报(谁受影响谁播报,2026-10-20 事件驱动) ----------
// 平时走 EventSource /api/alerts/stream(后端长连 MES,按本机工位过滤后推送);
// 断线由 EventSource 自动重连,重连成功后一次性调 GET /api/alerts/station 补拉最近报警(非轮询)。
// 同一条报警只播一次(localStorage 记账,上限 500 条,刷新/重启不重播)。
const SPEAK_SEEN_KEY = 'ws_spoken_alert_ids'
const SPEAK_MUTE_KEY = 'ws_speech_muted'
const speechMuted = ref(localStorage.getItem(SPEAK_MUTE_KEY) === '1')
function toggleSpeechMuted() {
speechMuted.value = !speechMuted.value
localStorage.setItem(SPEAK_MUTE_KEY, speechMuted.value ? '1' : '0')
setSpeechMuted(speechMuted.value)
}
setSpeechMuted(speechMuted.value)
function loadSpokenIds() {
try {
return new Set(JSON.parse(localStorage.getItem(SPEAK_SEEN_KEY) || '[]'))
} catch {
return new Set()
}
}
function persistSpokenIds(set) {
// 只留最近 500 条,防 localStorage 无限膨胀
const arr = [...set].slice(-500)
localStorage.setItem(SPEAK_SEEN_KEY, JSON.stringify(arr))
}
// handleAlerts 处理一批报警(事件推送/补拉共用):去重 → 语音播报 + 通知条
function handleAlerts(list) {
if (!Array.isArray(list) || !list.length) return
const spoken = loadSpokenIds()
let changed = false
// 按时间正序播报(旧→新),符合事件发生顺序
const sorted = [...list].sort((a, b) => (a.id || 0) - (b.id || 0))
for (const a of sorted) {
const id = a.id
if (!id || spoken.has(id)) continue
spoken.add(id)
changed = true
speak(`工位报警:${a.title || a.content || ''}`)
ElNotification({
title: '本工位报警',
message: a.title || a.content || '',
type: 'warning',
duration: 10000
})
}
if (changed) persistSpokenIds(spoken)
}
function connectAlertStream() {
if (!stationNo.value || alertES) return
let everFailed = false // 断过线才在重连成功后补拉,平时事件即实时
try {
alertES = new EventSource('/api/alerts/stream')
alertES.addEventListener('station.alert', (e) => {
try {
handleAlerts([JSON.parse(e.data)])
} catch { /* 脏帧忽略 */ }
})
alertES.onopen = () => {
if (everFailed) {
everFailed = false
// 断线期间可能漏推:重连成功后一次性补拉最近 10 分钟报警(非轮询)
pollStationAlerts()
}
}
alertES.onerror = () => { everFailed = true }
} catch {
alertES = null // 浏览器不支持 SSE:静默降级,无播报
}
}
// pollStationAlerts 一次性补拉(仅断线重连后调用)
async function pollStationAlerts() {
if (!stationNo.value) return
let list = null
try {
list = await getStationAlerts(stationNo.value, 10)
} catch {
return // 静默:MES/终端后端不可达不提示不播报
}
handleAlerts(list)
}
function tickClock() {
const d = new Date()
@@ -186,6 +278,7 @@ onMounted(async () => {
timerTask = setInterval(loadTask, 5000) // 任务 5 秒
timerTight = setInterval(loadTight, 2000) // 拧紧结果 2 秒
timerStats = setInterval(loadStats, 10000) // 同步统计 10 秒
connectAlertStream() // 本机报警事件流(SSE,断线自动重连)
timerClock = setInterval(() => {
tickClock()
loadPoints() // 点位台账 10 秒
@@ -199,6 +292,7 @@ onBeforeUnmount(() => {
clearInterval(timerTight)
clearInterval(timerStats)
clearInterval(timerClock)
if (alertES) { alertES.close(); alertES = null }
})
</script>
@@ -205,7 +205,8 @@ function fmt(v) {
return String(v).replace('T', ' ').slice(0, 16)
}
function wpStatusText(s) {
return { ONLINE: '已上线', PROCESSING: '在制', DONE: '已完工' }[s] || s || '-'
// DONE=完工(与 MES 工件六态口径统一,2026-10-19)
return { ONLINE: '已上线', PROCESSING: '在制', DONE: '完工' }[s] || s || '-'
}
function wpStatusType(s) {
return { ONLINE: 'info', PROCESSING: 'primary', DONE: 'success' }[s] || 'info'
@@ -70,7 +70,7 @@
<el-table-column label="单台用量" width="100" align="center">
<template #default="{ row }">{{ row.unitQty }}</template>
</el-table-column>
<el-table-column label="管理方式" width="130" align="center">
<el-table-column label="序列号" width="130" align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.snMode === 1 ? 'primary' : 'warning'">
{{ row.snMode === 1 ? '序列号=是' : '序列号=否' }}
@@ -141,19 +141,19 @@ const orders = ref([])
const loadingOrder = ref(false)
const submitting = ref(false)
// SN 口径按产品型号/物料档案 sn_mode 分流(2026-09-30 解耦定稿):
// SN 口径按产品型号/物料档案「序列号(是/否)」分流(2026-09-30 解耦定稿,2026-10-19 术语统一):
// 1=序列号=是:SN 输入必填,扫已在 WMS 入库登记的来料SN,工件 SN=来料SN(不自动发号);
// 2=序列号=否:提交后系统自动发号(提交时若未填则本地自动生成);
// 0=未选择:不可建档,提示先去产品型号/物料档案选择序列号管理方式。
// 0=未选择:不可建档,提示先去产品型号/物料档案选择「序列号(是/否)」。
const snPlaceholder = computed(() => {
if (product.snMode === 1) return '请扫描来料SN(已在WMS入库登记)'
if (product.snMode === 2) return '提交后系统自动发号'
return '请先在产品型号/物料档案选择序列号管理方式'
return '请先在产品型号/物料档案选择「序列号(是/否)」'
})
const snTip = computed(() => {
if (product.snMode === 1) return '该产品为「序列号=是」:请扫描来料SN(需已在 WMS 入库登记),建档后工件 SN = 来料SN,不再自动发号。'
if (product.snMode === 2) return '该产品为「序列号=否」:提交后系统自动发号,全程可追溯;成品 SN 与工件 SN 一致。'
return '该产品的序列号管理方式未选择:请先在 MES 产品型号/物料档案选择「序列号=是/否」,否则无法建档上线。'
return '该产品未选择「序列号(是/否)」:请先在 MES 产品型号/物料档案设置,否则无法建档上线。'
})
// 待流转在制品:MES 已按 scope=pending 过滤(ONLINE 未分配工位),此处直接透出
@@ -222,7 +222,7 @@ const canSubmit = computed(
const blockTip = computed(() => {
if (!form.orderNo) return '请先选择工单号'
if (!form.pointNo) return '请选择工件当前位置(无空闲点位时请联系班长协调)'
if (product.snMode === 0) return '请先在产品型号/物料档案选择序列号管理方式'
if (product.snMode === 0) return '请先在产品型号/物料档案选择「序列号(是/否)」'
if (product.snMode === 1 && !form.sn) return '请扫描来料SN(已在WMS入库登记)'
if (bomItems.value.length && !form.materialChecked) return '请勾选「已按物料清单核对领料」'
return ''
@@ -98,7 +98,16 @@
<el-tag size="large" :type="stepDisplay(s).type" effect="dark">{{ stepDisplay(s).text }}</el-tag>
</div>
<div class="step-input">
<!-- 扫码步骤(2026-10-19 新增采集方式):采一串字符串,用文本输入;手填步骤用数字输入 -->
<el-input
v-if="s.collectType === 'SCAN'"
v-model="stepValues[s.id]"
size="large"
class="num-input"
placeholder="扫码采集(一串字符串)"
/>
<el-input-number
v-else
v-model="stepValues[s.id]"
size="large"
:controls-position="'right'"
@@ -207,6 +216,19 @@
<el-button size="large" @click="ackMismatch('bind_known')">绑定已知(关联到已有工件)</el-button>
</div>
</el-dialog>
<!-- 操作工签字确认(需求B 双签第一签):需签字步骤逐项核对勾选,全部确认后才允许报工 -->
<el-dialog v-model="signDlg.show" title="操作工签字确认" width="560px" :close-on-click-modal="false" append-to-body @close="onSignCancel">
<div class="sign-tip">以下步骤需您本人签字确认。请核对步骤与录入内容后逐项勾选,全部确认后方可报工。</div>
<div v-for="s in signDlg.steps" :key="s.id" class="sign-row">
<el-checkbox v-model="signChecks[s.id]" size="large">{{ s.name || ('步骤 ' + s.seq) }}</el-checkbox>
<span class="sign-content">录入内容:{{ signStepContent(s) }}</span>
</div>
<template #footer>
<el-button size="large" @click="onSignCancel">取消</el-button>
<el-button type="primary" size="large" :disabled="!allSigned" @click="onSignConfirm">确认签字并报工</el-button>
</template>
</el-dialog>
</div>
</template>
@@ -251,6 +273,7 @@ import {
stepValues,
stationNo,
submitTorqueStep,
taskSteps,
torqueDoneCount,
torqueRowOfStep,
torqueStepCount,
@@ -486,6 +509,18 @@ function buildStepsPayload() {
const payload = []
for (const s of manualSteps.value) {
const raw = stepValues.value[s.id]
// 扫码步骤(2026-10-19 新增采集方式):采一串字符串,value 置 0、text 带原字符串(与手填非数值同口径)
if (s.collectType === 'SCAN') {
const txt = raw === null || raw === undefined ? '' : String(raw)
payload.push({
stepId: s.id,
name: s.name,
value: null,
text: `${s.name}: ${txt || '未录入'}`,
checked: !!stepChecks.value[s.id]
})
continue
}
const val = raw === null || raw === undefined || raw === '' ? null : Number(raw)
// checked:needCheck 步骤的「检测确认」结果,随报工一并上报,MES 服务端会强校验,防止绕过前端
payload.push({
@@ -508,6 +543,46 @@ function buildStepsPayload() {
return payload
}
/* ---------- 操作工签字确认(需求B 双签第一签) ----------
待签步骤:本工位工艺流程中配置了「需操作工签字」的步骤。
报工提交前弹窗逐项确认(步骤名 + 录入内容),全部勾选后才允许提交;
签字随报工载荷 signs 提交,MES 服务端强校验后落 step_sign_record(signRole=OPERATOR,
含签字人/时间/轮次),缺签字 MES 直接拒报工。 */
const pendingSignSteps = computed(() =>
taskSteps.value.filter((s) => s.needOperatorSign)
)
const signDlg = reactive({ show: false, steps: [] })
const signChecks = ref({})
const allSigned = computed(
() => signDlg.steps.length > 0 && signDlg.steps.every((s) => signChecks.value[s.id])
)
// 待签步骤的录入内容展示:手填/扫码=录入值;拧紧(自动采集)=已采集扭矩与判定
function signStepContent(s) {
if (s.collectType === 'AUTO') {
const row = torqueRowOfStep(s.id)
return row ? `拧紧 ${row.torque} N·m(${row.result === 'OK' ? '合格' : '不合格'})` : '未采集'
}
const v = stepValues.value[s.id]
if (v === null || v === undefined || v === '') return '未录入'
return String(v)
}
let signResolver = null
// 打开签字弹窗,返回 Promise:true=已全部确认签字;false=取消/关闭(调用方中止提交)
function openSignDialog() {
signDlg.steps = pendingSignSteps.value
signChecks.value = {}
signDlg.show = true
return new Promise((resolve) => { signResolver = resolve })
}
function onSignConfirm() {
signDlg.show = false
if (signResolver) { signResolver(true); signResolver = null }
}
function onSignCancel() {
signDlg.show = false
if (signResolver) { signResolver(false); signResolver = null }
}
async function onProcessDone() {
if (!canReport.value) {
ElMessage.warning(blockTip.value || '当前不满足报工条件')
@@ -540,6 +615,22 @@ async function onProcessDone() {
} catch {
return
}
// 操作工签字(需求B 双签第一签):存在需签字步骤时,先弹签字确认窗,未全部确认不允许提交
let signs = []
if (pendingSignSteps.value.length) {
if (!operatorName()) {
ElMessage.warning('未获取到操作人身份,请重新登录后再报工')
return
}
const signed = await openSignDialog()
if (!signed) return
signs = pendingSignSteps.value.map((s) => ({
stepId: s.id,
signRole: 'OPERATOR',
signer: operatorName(),
remark: ''
}))
}
try {
const data = await reportProcessDone({
sn: sn.value,
@@ -547,6 +638,7 @@ async function onProcessDone() {
flowId: flowId.value,
stationNo: stationNo.value,
steps: buildStepsPayload(),
signs,
operator: operatorName(),
// 作业时长(P0-3):上料时刻为起点、本次报工时刻为终点,同源于终端时钟,MES 据此算 durationSec
startedAt: startedAt.value || '',
@@ -955,6 +1047,28 @@ defineExpose({ focusScan })
color: #e6a23c;
font-size: 15px;
}
.sign-tip {
font-size: 16px;
line-height: 1.6;
margin-bottom: 12px;
}
.sign-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 8px;
border-bottom: 1px solid #ebeef5;
font-size: 17px;
}
.sign-row:last-child {
border-bottom: none;
}
.sign-content {
color: #606266;
font-size: 15px;
text-align: right;
}
@media (max-width: 1280px) {
.work-panel {
grid-template-columns: 1fr 1fr;
@@ -0,0 +1,155 @@
package alertstream
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"sync"
"time"
"bj_power_workstation/internal/mes"
"github.com/zeromicro/go-zero/core/logx"
)
// Manager 工位报警事件流(谁受影响谁播报,2026-10-20 轮询改事件驱动):
// 后台长连接 MES GET /api/internal/station/alerts/stream(SSE,X-API-TOKEN 鉴权),
// 只认 station.alert 事件;按本机固定工位号过滤「工位N」相关报警后,广播给本机前端订阅者。
// 断线自动重连(3 秒退避);前端断线重连后的一次性补拉走 GET /api/alerts/station(前端自己调)。
type Manager struct {
mc *mes.Client
stationNo int
mu sync.Mutex
clients map[chan string]struct{}
}
// New 新建报警流管理器。
func New(mc *mes.Client, stationNo int) *Manager {
return &Manager{
mc: mc,
stationNo: stationNo,
clients: make(map[chan string]struct{}),
}
}
// Subscribe 本机前端订阅(每个 EventSource 连接一个 channel)。
func (m *Manager) Subscribe() chan string {
ch := make(chan string, 32)
m.mu.Lock()
m.clients[ch] = struct{}{}
m.mu.Unlock()
return ch
}
// Unsubscribe 取消订阅并关闭 channel。
func (m *Manager) Unsubscribe(ch chan string) {
m.mu.Lock()
if _, ok := m.clients[ch]; ok {
delete(m.clients, ch)
close(ch)
}
m.mu.Unlock()
}
func (m *Manager) broadcast(data string) {
m.mu.Lock()
defer m.mu.Unlock()
for ch := range m.clients {
select {
case ch <- data:
default: // 订阅者堆积(前端卡死)直接丢帧,下一条报警自然追上
}
}
}
// Run 主循环:连 MES SSE → 解析分发 → 断线 3 秒重连,直到 ctx 取消。
func (m *Manager) Run(ctx context.Context) {
if m.stationNo <= 0 {
logx.Errorf("报警事件流未启动:Station.StationNo=%d 无效", m.stationNo)
return
}
for {
select {
case <-ctx.Done():
return
default:
}
if err := m.runOnce(ctx); err != nil {
logx.Errorf("工位报警事件流断开,3 秒后重连: %v", err)
}
select {
case <-ctx.Done():
return
case <-time.After(3 * time.Second):
}
}
}
func (m *Manager) runOnce(ctx context.Context) error {
body, err := m.mc.GetStream("/api/internal/station/alerts/stream", nil)
if err != nil {
return err
}
defer body.Close()
logx.Infof("工位报警事件流已连接 MES(工位%d)", m.stationNo)
defer logx.Infof("工位报警事件流连接关闭(工位%d)", m.stationNo)
rd := bufio.NewReader(body)
event := ""
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
line, rerr := rd.ReadString('\n')
if rerr != nil {
if rerr == io.EOF {
return fmt.Errorf("MES 流关闭(EOF)")
}
return rerr
}
line = strings.TrimRight(line, "\r\n")
switch {
case strings.HasPrefix(line, "event:"):
event = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
case strings.HasPrefix(line, "data:"):
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if event == "station.alert" && data != "" {
m.dispatch(data)
}
event = ""
default:
// 空行/心跳注释(": ping")忽略
}
}
}
// dispatch 解析报警 JSON,命中本工位(target/content/title 含「工位N」)才广播。
type alertPayload struct {
ID int `json:"id"`
Type string `json:"type"`
Level string `json:"level"`
Target string `json:"target"`
Title string `json:"title"`
Content string `json:"content"`
}
func (m *Manager) dispatch(data string) {
var a alertPayload
if err := json.Unmarshal([]byte(data), &a); err != nil {
return
}
hit := strings.Contains(a.Target, "工位"+strconv.Itoa(m.stationNo)) ||
strings.Contains(a.Content, "工位"+strconv.Itoa(m.stationNo)) ||
strings.Contains(a.Title, "工位"+strconv.Itoa(m.stationNo))
if !hit {
return
}
m.broadcast(data)
}
@@ -0,0 +1,47 @@
package handler
import (
"fmt"
"net/http"
"time"
"bj_power_workstation/internal/svc"
)
// alertsStreamHandler GET /api/alerts/stream(本机 SSE,免鉴权)
// 终端前端 EventSource 订阅本端点(同源、EventSource 无法携带 JWT,故走免鉴权组;
// 数据已经 alertstream.Manager 按本机固定工位号过滤,仅本机 LAN 可达,敏感度低)。
// 收到 MES station.alert 即转发;15 秒心跳注释行防空闲断链;前端断开由 r.Context().Done() 感知。
func alertsStreamHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fl, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
ch := ctx.AlertStream.Subscribe()
defer ctx.AlertStream.Unsubscribe(ch)
fl.Flush()
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
for {
select {
case data := <-ch:
if _, err := fmt.Fprintf(w, "event: station.alert\ndata: %s\n\n", data); err != nil {
return
}
fl.Flush()
case <-ticker.C:
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
return
}
fl.Flush()
case <-r.Context().Done():
return
}
}
}
}
@@ -18,6 +18,8 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) {
{Method: http.MethodGet, Path: "/api/config", Handler: configHandler(ctx)},
// 工艺文件免鉴权直链(query 传名,支持日期子目录;供 iframe/window.open)
{Method: http.MethodGet, Path: "/pdfview", Handler: pdfViewHandler(ctx)},
// 本机工位报警 SSE(免鉴权:EventSource 无法携带 JWT;数据已按本机工位过滤,LAN 内低敏感)
{Method: http.MethodGet, Path: "/api/alerts/stream", Handler: alertsStreamHandler(ctx)},
// 前端静态托管
{Method: http.MethodGet, Path: "/", Handler: indexHandler(ctx.WebFS)},
{Method: http.MethodGet, Path: "/assets/:file", Handler: assetHandler(ctx.WebFS)},
@@ -82,6 +84,9 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) {
{Method: http.MethodPost, Path: "/api/workpiece/online", Handler: onlineHandler(ctx)},
{Method: http.MethodPost, Path: "/api/workpiece/done", Handler: doneHandler(ctx)},
// 本工位相关报警(谁受影响谁播报,2026-10-20):终端前端轮询 + 语音播报
{Method: http.MethodGet, Path: "/api/alerts/station", Handler: stationAlertsHandler(ctx)},
// PLC↔MES 对账(#8 T2/T3 终端事件驱动检查,不轮询):代理 MES 内部接口,MES 不可达静默跳过
{Method: http.MethodPost, Path: "/api/plc/mismatch/check", Handler: plcMismatchCheckHandler(ctx)},
},
@@ -0,0 +1,42 @@
package handler
import (
"net/http"
"net/url"
"strconv"
"strings"
"bj_power_workstation/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
// stationAlertsHandler GET /api/alerts/station?stationNo=&minutes=
// 代理 MES GET /api/internal/station/alerts(谁受影响谁播报,2026-10-20)。
// 终端前端 30 秒轮询本工位相关报警;MES 不可达/业务拒绝静默返回空列表,不影响作业。
func stationAlertsHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
stationNo := atoi(strings.TrimSpace(r.URL.Query().Get("stationNo")), 0)
minutes := atoi(strings.TrimSpace(r.URL.Query().Get("minutes")), 10)
if stationNo <= 0 {
ok(w, []any{})
return
}
body, _, err := ctx.Mes.Get("/api/internal/station/alerts", url.Values{
"stationNo": {strconv.Itoa(stationNo)},
"minutes": {strconv.Itoa(minutes)},
})
if err != nil {
// MES 不可达:静默返回空,终端语音播报不因后端抖动而报错刷屏
logx.Errorf("工位报警查询 MES 不可达,静默跳过: %v", err)
ok(w, []any{})
return
}
if msg := mesRespCode(body); msg != "" {
logx.Errorf("工位报警查询 MES 业务拒绝,静默跳过: %s", msg)
ok(w, []any{})
return
}
passJSON(w, body)
}
}
+32 -3
View File
@@ -38,6 +38,7 @@ type Client struct {
token string // X-API-TOKEN 共享内部 token(项目间)
stationToken string // 工位登录态 JWT(Bearer):方案 B 报工链路可信身份凭证
httpClient *http.Client
streamClient *http.Client // SSE 长连接专用(无总超时)
mu sync.Mutex
Touch func() // 每次以「当前有效登录态」发起的调用触发,用于刷新工位空闲计时(核实4)
@@ -45,9 +46,10 @@ type Client struct {
func New(baseURL, token string) *Client {
return &Client{
baseURL: strings.TrimRight(baseURL, "/"),
token: token,
httpClient: &http.Client{Timeout: 10 * time.Second},
baseURL: strings.TrimRight(baseURL, "/"),
token: token,
httpClient: &http.Client{Timeout: 10 * time.Second},
streamClient: &http.Client{}, // SSE 长连接专用:无总超时,靠服务端心跳+断线重连兜底
}
}
@@ -83,6 +85,33 @@ func (c *Client) Post(path string, body any) ([]byte, http.Header, error) {
}
// GetStream 发起 SSE 长连接(工位报警事件流,2026-10-20):仅 X-API-TOKEN 鉴权,
// 不携带/不刷新工位登录态(长连接期间登录态可能过期,SSE 鉴权只认项目间 token)。
// 使用独立的无超时 http.Client(默认 httpClient 的 10s 总超时会掐断长连接);
// 调用方负责关闭返回的 ReadCloser,断线重连由调用方(alertstream.Manager)负责。
func (c *Client) GetStream(path string, query url.Values) (io.ReadCloser, error) {
u := c.baseURL + path
if len(query) > 0 {
u += "?" + query.Encode()
}
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-TOKEN", c.token)
req.Header.Set("Accept", "text/event-stream")
resp, err := c.streamClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("MES %s 返回 %d:%s", path, resp.StatusCode, truncate(string(body), 200))
}
return resp.Body, nil
}
// do 执行请求:Bearer 固定使用当前登录态 JWT(c.stationToken)。
// 仅在「当前登录态有效」时刷新空闲计时(核实4)。
func (c *Client) do(method, u string, body io.Reader) ([]byte, http.Header, error) {
@@ -3,6 +3,7 @@ package svc
import (
"io/fs"
"bj_power_workstation/internal/alertstream"
"bj_power_workstation/internal/config"
"bj_power_workstation/internal/mes"
"bj_power_workstation/internal/pdfcache"
@@ -13,11 +14,12 @@ import (
// ServiceContext 服务上下文:配置 + 本地存储 + MES 客户端 + 同步器 + PDF 缓存 + 前端静态资源 + 拧紧枪 OP 接入
type ServiceContext struct {
Config config.Config
Store *store.Store
Mes *mes.Client
Syncer *syncer.Syncer
PdfCache *pdfcache.Cache
WebFS fs.FS // go:embed 的 web/static 子文件系统
Tightening *tightening.Manager
Config config.Config
Store *store.Store
Mes *mes.Client
Syncer *syncer.Syncer
PdfCache *pdfcache.Cache
WebFS fs.FS // go:embed 的 web/static 子文件系统
Tightening *tightening.Manager
AlertStream *alertstream.Manager // 工位报警事件流(SSE 事件驱动播报)
}
+14 -7
View File
@@ -10,6 +10,7 @@ import (
"runtime"
"time"
"bj_power_workstation/internal/alertstream"
"bj_power_workstation/internal/config"
"bj_power_workstation/internal/handler"
"bj_power_workstation/internal/mes"
@@ -117,6 +118,11 @@ func main() {
tm := tightening.NewManager(c.Tightening)
go tm.Run(rootCtx)
// 工位报警事件流(谁受影响谁播报,2026-10-20):长连接 MES SSE,按本机工位过滤后广播给本机前端;
// 断线自动重连;前端 EventSource 订阅 /api/alerts/stream,断线重连后一次性补拉 /api/alerts/station。
am := alertstream.New(mc, c.Station.StationNo)
go am.Run(rootCtx)
// 扫码中间件(键盘 HID 注入):Enable=true 时后台监听 7757,接收网络型扫码枪(iData PAD / 新大陆手机)
// 推送并模拟键盘注入当前光标窗口(任意输入框自动填入,前端无需轮询)。7757 被占用时仅记日志、不影响主程序。
if c.Scanner.Enabled {
@@ -131,13 +137,14 @@ func main() {
pdc := pdfcache.New(c.PdfCache.Dir)
ctx := &svc.ServiceContext{
Config: c,
Store: st,
Mes: mc,
Syncer: sy,
PdfCache: pdc,
WebFS: staticFS,
Tightening: tm,
Config: c,
Store: st,
Mes: mc,
Syncer: sy,
PdfCache: pdc,
WebFS: staticFS,
Tightening: tm,
AlertStream: am,
}
server := rest.MustNewServer(c.RestConf)
+1 -1
View File
@@ -6,7 +6,7 @@
<title>工位终端</title>
<!-- 系统图标:工位终端屏(内联 SVG,避免依赖外部文件) -->
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='6' fill='%231668dc'/><rect x='6' y='7' width='20' height='14' rx='2' fill='none' stroke='%23fff' stroke-width='2'/><path d='M12 25h8M16 21v4' stroke='%23fff' stroke-width='2' stroke-linecap='round'/></svg>">
<script type="module" crossorigin src="/assets/index-Bm3gHHuw.js"></script>
<script type="module" crossorigin src="/assets/index-BoHSfWZs.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Dz4RGjfJ.css">
</head>
<body>