feat(scan): 扫码链路诊断埋点与长时间运行自愈(事件类型锁重置/空闲重挂监听)+现场诊断面板

This commit is contained in:
liufumingren 2026-09-25 00:35:19 +08:00
parent 87b798659d
commit 1eb8a1dfe5
6 changed files with 868 additions and 5 deletions

View File

@ -0,0 +1,200 @@
<template>
<view v-if="visible" class="diag-mask" @click="handleClose">
<view class="diag-panel" @click.stop>
<view class="diag-head">
<text class="diag-title">扫码诊断</text>
<view class="diag-head-actions">
<text class="diag-action" @click="refresh">刷新</text>
<text class="diag-action" @click="copyText">复制</text>
<text class="diag-action diag-action--danger" @click="clearLog">清空</text>
<text class="diag-action diag-action--close" @click="handleClose">×</text>
</view>
</view>
<scroll-view class="diag-body" scroll-y>
<text class="diag-text">{{ text }}</text>
</scroll-view>
<view class="diag-foot">
<text class="diag-foot-text">{{ hint }}</text>
</view>
</view>
</view>
</template>
<script>
import { diagText, diagClear } from '@/core/scan-diag'
/**
* 扫码诊断面板(现场可读,无需 adb)
* 打开方式由宿主页面决定(打包页=3 秒内连点标题 5 次)。
* 数据来自 src/core/scan-diag.js,与 logcat(tag: WMSScan) 同源。
*/
export default {
name: 'ScanDiagPanel',
props: {
visible: {
type: Boolean,
default: false,
},
},
emits: ['close'],
data() {
return {
text: '',
hint: '复制后可直接发到群里;真机也可用 adb logcat -s WMSScan 查看',
}
},
watch: {
visible(value) {
if (value) {
this.refresh()
this.startTimer()
} else {
this.stopTimer()
}
},
},
beforeUnmount() {
this.stopTimer()
},
methods: {
startTimer() {
this.stopTimer()
this.timer = setInterval(() => {
this.refresh()
}, 1000)
},
stopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
},
refresh() {
try {
this.text = diagText()
} catch (e) {
this.text = `诊断信息生成失败:${e && e.message}`
}
},
copyText() {
try {
uni.setClipboardData({
data: this.text,
success: () => {
uni.showToast({ title: '诊断信息已复制', icon: 'none' })
},
fail: () => {
uni.showToast({ title: '复制失败,请截图上报', icon: 'none' })
},
})
} catch (e) {
uni.showToast({ title: '复制失败,请截图上报', icon: 'none' })
}
},
clearLog() {
try {
diagClear()
} catch (e) {
// 忽略
}
this.refresh()
uni.showToast({ title: '日志已清空', icon: 'none' })
},
handleClose() {
this.$emit('close')
},
},
}
</script>
<style scoped>
/* 诊断面板固定用 px:不随页面 rem 缩放变化,保证任何缩放系数下都可读 */
.diag-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.6);
z-index: 3000;
display: flex;
align-items: center;
justify-content: center;
}
.diag-panel {
width: 76vw;
max-width: 900px;
height: 74vh;
background-color: #1e1e1e;
border-radius: 6px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.diag-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background-color: #2b2b2b;
border-bottom: 1px solid #3c3c3c;
}
.diag-title {
color: #ffffff;
font-size: 15px;
font-weight: bold;
}
.diag-head-actions {
display: flex;
align-items: center;
}
.diag-action {
color: #4ea1ff;
font-size: 13px;
padding: 4px 10px;
border: 1px solid #3c3c3c;
border-radius: 4px;
margin-left: 8px;
}
.diag-action--danger {
color: #ff7875;
}
.diag-action--close {
color: #dddddd;
font-size: 16px;
padding: 2px 10px;
}
.diag-body {
flex: 1;
padding: 10px 12px;
overflow: hidden;
}
.diag-text {
color: #d4d4d4;
font-size: 12px;
line-height: 18px;
font-family: Consolas, Menlo, 'Courier New', monospace;
white-space: pre-wrap;
word-break: break-all;
}
.diag-foot {
padding: 6px 12px;
background-color: #2b2b2b;
border-top: 1px solid #3c3c3c;
}
.diag-foot-text {
color: #909399;
font-size: 11px;
}
</style>

360
src/core/scan-diag.js Normal file
View File

@ -0,0 +1,360 @@
/**
* 扫码链路诊断(长时间运行可追踪)
*
* 背景:真机上「长时间使用后扫码没反应」这类问题无法现场复现,必须留下可事后追溯的证据链。
* 本模块提供三件事:
* 1. 事件环形缓冲 + 计数器(按键到达 / 各门控丢弃 / 自愈次数 / 成功识别),
* 节流持久化到 storage:应用被杀或重启后日志仍在(诊断面板或 storage 可读)。
* 2. 真机同步写 logcat(tag: WMSScan),release 包也能 `adb logcat -s WMSScan` 事后追踪。
* 3. 60 秒健康心跳:记录区间内按键数 / 丢弃增量 / 门控快照,
* 可精确定位「哪一分钟开始收不到按键」以及当时的门控状态。
*
* 约定:本模块只做记录,不做任何业务决策,任何异常都不得向上抛。
*/
const STORAGE_KEY = 'scanDiagLog:v1'
const LOGCAT_TAG = 'WMSScan'
// 内存中保留的事件条数
const MAX_EVENTS = 300
// 持久化到 storage 的事件条数(控制体积,约 10KB)
const MAX_PERSIST_EVENTS = 160
const PERSIST_THROTTLE_MS = 2000
// 健康心跳间隔(心跳里带门控快照,是"何时开始不响应"的关键线索)
const HEALTH_INTERVAL_MS = 60 * 1000
// 同一丢弃原因的最小记录间隔(计数照常累加,避免刷屏)
const DROP_LOG_MIN_INTERVAL_MS = 30 * 1000
// 超过该空闲时长后恢复的第一下按键单独记一条 key-resume
const KEY_RESUME_GAP_MS = 60 * 1000
const state = {
scope: 'unknown',
startedAt: Date.now(),
events: [],
counters: { keys: 0, keysBySource: {}, flushes: 0, heals: 0, drops: {} },
gates: {},
prevCounters: null,
lastKeyAt: 0,
lastHealthAt: 0,
healthKeys: 0,
healthDrops: 0,
healthHeals: 0,
dropLoggedAt: {},
loaded: false,
persistedAt: 0,
persistTimer: null,
logcatClass: null,
}
// ---------- 基础工具 ----------
function hasUni() {
return typeof uni !== 'undefined' && !!uni && typeof uni.setStorageSync === 'function'
}
function pad2(n) {
return String(n).padStart(2, '0')
}
function fmtClock(ts) {
const d = new Date(ts)
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
}
function fmtDuration(ms) {
const totalSec = Math.max(0, Math.floor(ms / 1000))
if (totalSec < 60) {
return `${totalSec}s`
}
const totalMin = Math.floor(totalSec / 60)
if (totalMin < 60) {
return `${totalMin}m${pad2(totalSec % 60)}s`
}
return `${Math.floor(totalMin / 60)}h${pad2(totalMin % 60)}m`
}
/** 只保留可读的轻量字段,避免把大对象写进日志 */
function tidy(data) {
if (!data || typeof data !== 'object') {
return undefined
}
const out = {}
Object.keys(data).forEach((key) => {
const value = data[key]
if (value === undefined || value === null) {
return
}
const type = typeof value
if (type === 'number' || type === 'boolean' || type === 'string') {
out[key] = value
}
})
return Object.keys(out).length ? out : undefined
}
function dataText(data) {
const tidyData = tidy(data)
if (!tidyData) {
return ''
}
return (
' ' +
Object.keys(tidyData)
.map((key) => `${key}=${tidyData[key]}`)
.join(' ')
)
}
function totalDrops() {
return Object.keys(state.counters.drops).reduce((sum, key) => sum + state.counters.drops[key], 0)
}
/** 真机同步写 logcat:release 包 console 不可见,只能靠 logcat 事后追踪 */
function logcat(line) {
try {
if (typeof plus === 'undefined' || !plus || !plus.android) {
return
}
if (!state.logcatClass) {
state.logcatClass = plus.android.importClass('android.util.Log')
}
state.logcatClass.i(LOGCAT_TAG, String(line))
} catch (e) {
// 忽略:日志失败绝不影响业务
}
}
// ---------- 持久化 ----------
function persistNow() {
if (!hasUni()) {
return
}
state.persistedAt = Date.now()
try {
uni.setStorageSync(STORAGE_KEY, {
v: 1,
savedAt: state.persistedAt,
scope: state.scope,
counters: state.counters,
gates: state.gates,
events: state.events.slice(-MAX_PERSIST_EVENTS),
})
} catch (e) {
// 忽略:存储失败不影响业务
}
}
function schedulePersist() {
if (state.persistTimer) {
return
}
const wait = Math.max(0, PERSIST_THROTTLE_MS - (Date.now() - state.persistedAt))
state.persistTimer = setTimeout(() => {
state.persistTimer = null
persistNow()
}, wait)
}
function load() {
if (state.loaded) {
return
}
state.loaded = true
if (!hasUni()) {
return
}
try {
const raw = uni.getStorageSync(STORAGE_KEY)
if (raw && typeof raw === 'object' && Array.isArray(raw.events)) {
state.events = raw.events
.filter((item) => item && item.t && item.msg)
.slice(-MAX_PERSIST_EVENTS)
if (raw.counters && typeof raw.counters === 'object') {
// 上次运行的累计值仅作参考,不并入本次计数
state.prevCounters = raw.counters
}
}
} catch (e) {
// 忽略
}
}
// ---------- 写入事件 ----------
function push(kind, message, data) {
const entry = { t: Date.now(), kind, msg: `${message}${dataText(data)}` }
state.events.push(entry)
if (state.events.length > MAX_EVENTS) {
state.events.splice(0, state.events.length - MAX_EVENTS)
}
// 按键逐条记录会刷屏,只计数(key-resume 会单独 push)
if (kind !== 'key') {
logcat(`${fmtClock(entry.t)} [${kind}] ${entry.msg}`)
schedulePersist()
}
return entry
}
// ---------- 对外 API ----------
/** 页面进入时声明作用域(同一 scope 重复调用不产生新标记) */
export function diagBegin(scope) {
load()
const next = String(scope || 'unknown')
if (state.scope === next) {
return
}
state.scope = next
const prev = state.prevCounters
push('note', `session-start scope=${next}${prev ? ` 上次运行=${JSON.stringify(prev)}` : ''}`)
}
/** 更新门控快照(会随健康心跳一起落盘,是定位"为何没反应"的核心依据) */
export function diagSetGates(gates) {
const tidyGates = tidy(gates)
if (!tidyGates) {
return
}
state.gates = Object.assign({}, state.gates, tidyGates)
}
/**
* 记录一次按键到达(在任何门控判断之前调用)。
* 用于区分「按键根本没到 JS」和「到了 JS 但被门控丢掉」。
*/
export function diagKey(source) {
const now = Date.now()
const gap = state.lastKeyAt ? now - state.lastKeyAt : 0
state.lastKeyAt = now
state.counters.keys += 1
const key = String(source || 'unknown')
state.counters.keysBySource[key] = (state.counters.keysBySource[key] || 0) + 1
if (gap > KEY_RESUME_GAP_MS) {
// 长时间无按键后的第一下:定位"卡住→恢复"的时间点
push('key', `key-resume source=${key} 空闲=${fmtDuration(gap)}`)
}
}
/** 记录一次被丢弃的按键(reason 区分门控,便于统计各原因占比) */
export function diagDrop(reason, data) {
const key = String(reason || 'unknown')
state.counters.drops[key] = (state.counters.drops[key] || 0) + 1
const count = state.counters.drops[key]
const now = Date.now()
const last = state.dropLoggedAt[key] || 0
if (count === 1 || now - last >= DROP_LOG_MIN_INTERVAL_MS || count % 100 === 0) {
state.dropLoggedAt[key] = now
push('drop', `reason=${key} count=${count}`, data)
}
}
/** 记录一次成功识别出的扫码结果 */
export function diagFlush(info) {
state.counters.flushes += 1
push('flush', `#${state.counters.flushes}`, info)
}
/** 记录一次自愈动作(事件类型锁重置 / 监听重挂等) */
export function diagHeal(reason, data) {
state.counters.heals += 1
push('heal', `reason=${reason} count=${state.counters.heals}`, data)
}
/** 记录任意备注(生命周期、提交动作、状态切换等) */
export function diagNote(name, data) {
load()
push('note', String(name || ''), data)
}
/** 健康心跳:默认 60s 一条,含区间按键数/丢弃增量/门控快照 */
export function diagHeartbeat(force) {
const now = Date.now()
if (!force && now - state.lastHealthAt < HEALTH_INTERVAL_MS) {
return
}
const keys = state.counters.keys - state.healthKeys
const drops = totalDrops() - state.healthDrops
const heals = state.counters.heals - state.healthHeals
const idleAgo = state.lastKeyAt ? fmtDuration(now - state.lastKeyAt) : 'never'
state.lastHealthAt = now
state.healthKeys = state.counters.keys
state.healthDrops = totalDrops()
state.healthHeals = state.counters.heals
push(
'health',
`keys=${keys} drops=${drops} heals=${heals} flush累计=${state.counters.flushes} 最近按键=${idleAgo}前`,
state.gates
)
}
/** 立即落盘(页面 onHide/onUnload 时调用,避免节流窗口内丢日志) */
export function diagPersistNow() {
if (state.persistTimer) {
clearTimeout(state.persistTimer)
state.persistTimer = null
}
persistNow()
}
/** 结构化快照(面板/上报可用) */
export function diagSnapshot() {
return {
scope: state.scope,
uptimeMs: Date.now() - state.startedAt,
counters: {
keys: state.counters.keys,
keysBySource: Object.assign({}, state.counters.keysBySource),
flushes: state.counters.flushes,
heals: state.counters.heals,
drops: Object.assign({}, state.counters.drops),
},
gates: Object.assign({}, state.gates),
lastKeyAgoMs: state.lastKeyAt ? Date.now() - state.lastKeyAt : null,
events: state.events.slice(),
}
}
/** 纯文本摘要(现场截图/复制即可上报,无需 adb) */
export function diagText() {
const snapshot = diagSnapshot()
const lines = []
lines.push(
`【扫码诊断】scope=${snapshot.scope} 运行=${fmtDuration(snapshot.uptimeMs)} 现在=${fmtClock(Date.now())}`
)
lines.push(
`按键到达=${snapshot.counters.keys}` +
(snapshot.lastKeyAgoMs === null
? '(本次运行还没收到任何按键)'
: `(最近一次 ${fmtDuration(snapshot.lastKeyAgoMs)} 前)`)
)
lines.push(`按键来源=${JSON.stringify(snapshot.counters.keysBySource)}`)
lines.push(`成功识别=${snapshot.counters.flushes} 自愈=${snapshot.counters.heals}`)
const dropKeys = Object.keys(snapshot.counters.drops)
lines.push(
`丢弃统计=${
dropKeys.length
? dropKeys.map((key) => `${key}:${snapshot.counters.drops[key]}`).join(' ')
: '无'
}`
)
lines.push(`门控快照=${JSON.stringify(snapshot.gates)}`)
lines.push('---- 最近事件(新→旧) ----')
const events = snapshot.events
for (let i = events.length - 1; i >= 0 && i >= events.length - 80; i--) {
lines.push(`${fmtClock(events[i].t)} [${events[i].kind}] ${events[i].msg}`)
}
return lines.join('\n')
}
/** 清空日志(诊断面板手动清空,或问题确认消除后清空) */
export function diagClear() {
state.events = []
state.counters = { keys: 0, keysBySource: {}, flushes: 0, heals: 0, drops: {} }
state.healthKeys = 0
state.healthDrops = 0
state.healthHeals = 0
state.lastHealthAt = 0
state.dropLoggedAt = {}
push('note', 'log-cleared')
diagPersistNow()
}

View File

@ -5,8 +5,33 @@
* - 页面通过 registerScanReceiver 注册接收;同一时刻仅一个接收者
* - Enter 或超时(380ms/420ms)flush;长度 < minLength 的码直接丢弃
* - setScanPaused(true) 暂停捕获(如账号/密码输入框聚焦时)
*
* 长时间运行可追踪(配合 src/core/scan-diag.js):
* - 任何按键到达 JS 先计数(diagKey),再按门控丢弃原因分类计数(diagDrop),
* 由此可区分「按键根本没到」与「到了但被门控丢掉」。
* - 空闲后自动重置事件类型锁、长时间无按键强制重挂监听(自愈)。
*/
import {
diagKey,
diagDrop,
diagFlush,
diagHeal,
diagHeartbeat,
diagSetGates,
diagNote,
diagPersistNow,
} from './scan-diag'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型。
// 根因:本机实测只投递 keyup,若某次运行时锁被设成 'keydown'(其它来源的合成/注入事件),
// 之后所有真按键都会被事件类型过滤静默丢掉 → 表现为「扫着扫着彻底没反应」。
const IDLE_LOCK_RESET_MS = 1200
// 长时间(默认 10 分钟)没有任何按键到达时,强制重挂 plus/DOM 监听(防桥接回调静默失效)
const LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 自愈心跳间隔
const SELF_HEAL_INTERVAL_MS = 5000
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
// 这些 keyCode 与 ASCII 字母/数字区间重叠,必须优先于 ASCII 分支判断,
// 否则 KEYCODE_EQUALS=70 会被 ASCII 的 [65..90] 分支误读为 'F'。
@ -38,6 +63,10 @@ let timer = null
let domListenerAttached = false
let plusAttached = false
let lastAnyKeyAt = 0 // 最近一次按键到达(含被门控丢弃的),用于空闲判定
let rearmedForIdle = false // 本次空闲是否已重挂过监听(收到按键后复位)
let selfHealTimer = null
let selfHealStartedAt = 0
let plusKeyStyle = null // 'android' | 'ascii'
let plusShiftDown = false
let plusShiftPrev = false
@ -85,10 +114,12 @@ function flush(trigger, source) {
// 少于最小长度的码直接丢弃(可能是键盘误按/短码)
if (code.length < minLength) {
diagDrop('too-short', { length: code.length, minLength, trigger, source })
debug('code-dropped', { reason: 'too-short', code, length: code.length, minLength, trigger, source })
return
}
diagFlush({ trigger, source, length: code.length, durationMs })
debug('flush-buffer', { code, length: code.length, durationMs, trigger, source })
if (receiver && typeof receiver.onScanCode === 'function') {
@ -111,15 +142,31 @@ function appendChar(ch) {
timer = setTimeout(() => flush('timer', 'dom'), 380)
}
/**
* 记录「按键到达 JS」这一事实(必须在任何门控判断之前调用)。
* 返回距上一次按键的空闲时长,供事件类型锁自愈使用。
*/
function markKeyArrival(source) {
const now = Date.now()
const gap = lastAnyKeyAt ? now - lastAnyKeyAt : 0
lastAnyKeyAt = now
rearmedForIdle = false
diagKey(source)
return gap
}
// ---------- DOM(H5/Electron) ----------
function onDomKeydown(event) {
markKeyArrival('dom')
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'dom' })
return
}
const key = event?.key || ''
const isPrintable = key.length === 1
const isEnter = key === 'Enter'
if (!isPrintable && !isEnter) {
diagDrop('unmapped-dom-key', { key })
return
}
debug('key-captured', { key, paused })
@ -239,7 +286,15 @@ function isPlusEnterKey(keyCode, text) {
}
function handlePlusKeyEvent(event, type) {
const gap = markKeyArrival('plus')
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (plusKeyEventType && gap > IDLE_LOCK_RESET_MS) {
const locked = plusKeyEventType
plusKeyEventType = null
diagHeal('event-type-lock-idle-reset', { locked, gapMs: gap })
}
if (!receiver || paused) {
diagDrop(receiver ? 'paused' : 'no-receiver', { source: 'plus' })
return
}
const keyCode = Number((event && event.keyCode) || 0)
@ -263,6 +318,7 @@ function handlePlusKeyEvent(event, type) {
plusShiftPrev = plusShiftDown
const isEnter = isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { keyCode, type })
return
}
@ -271,6 +327,7 @@ function handlePlusKeyEvent(event, type) {
plusKeyEventType = type
}
if (plusKeyEventType !== type) {
diagDrop('event-type-locked', { keyCode, type, locked: plusKeyEventType })
return
}
@ -304,6 +361,8 @@ function ensurePlusListener() {
plus.key.addEventListener('keydown', onPlusKeyDown)
plus.key.addEventListener('keyup', onPlusKeyUp)
plusAttached = true
diagNote('plus-listener-attached')
diagSetGates({ plusAttached: true })
debug('plus-listener-attached')
// #endif
}
@ -322,6 +381,7 @@ function removePlusListener() {
plusKeyEventType = null
plusShiftDown = false
plusShiftPrev = false
diagSetGates({ plusAttached: false })
}
// ---------- 公共 API ----------
@ -340,6 +400,8 @@ export function registerScanReceiver(next) {
if (receiver) {
ensureDomListener()
ensurePlusListener()
diagSetGates({ receiver: true, minLength })
diagNote('receiver-registered')
debug('receiver-registered')
}
}
@ -354,11 +416,19 @@ export function unregisterScanReceiver(target) {
removeDomListener()
removePlusListener()
setScanPaused(false)
diagSetGates({ receiver: false, paused: false, buffer: 0 })
diagNote('receiver-unregistered')
}
/** 暂停/恢复捕获(账号/密码等输入框聚焦时暂停,并清空已缓冲的按键) */
export function setScanPaused(value) {
paused = !!value
const next = !!value
if (paused !== next) {
// 暂停标志卡住是最常见的"扫码没反应"原因,必须留痕
diagNote('setScanPaused', { value: next })
}
paused = next
diagSetGates({ paused })
if (paused) {
resetBuffer()
} else {
@ -371,6 +441,7 @@ export function setScanMinLength(value) {
const num = Number(value)
if (num >= 1) {
minLength = Math.floor(num)
diagSetGates({ minLength })
}
}
@ -383,3 +454,59 @@ export function resetScanBuffer() {
export function getScanMinLength() {
return minLength
}
/** 当前链路状态快照(诊断面板/日志用) */
export function getScanDiagState() {
return {
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType,
minLength,
bufferLength: buffer.length,
lastKeyAgoMs: lastAnyKeyAt ? Date.now() - lastAnyKeyAt : null,
}
}
/**
* 启动扫码链路自愈心跳(页面 onShow/activated 调用,onHide/deactivated 停止)
* - 每 5s 刷新门控快照 + 输出健康心跳(内部按 60s 节流);
* - 空闲超过 10 分钟仍无任何按键时,强制重挂 plus/DOM 监听(防桥接回调静默失效)。
* 注意:仅在空闲时重挂,不会打断正在进行的扫码。
*/
export function startScanSelfHeal(intervalMs) {
if (selfHealTimer) {
return
}
const period = Number(intervalMs) > 0 ? Number(intervalMs) : SELF_HEAL_INTERVAL_MS
selfHealStartedAt = Date.now()
selfHealTimer = setInterval(() => {
// 从未收到过按键时以心跳启动时刻为基准,否则"一直收不到"的情况永远不会触发重挂
const idleMs = Date.now() - (lastAnyKeyAt || selfHealStartedAt)
diagSetGates({
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType || 'none',
idleSec: Math.round(idleMs / 1000),
})
if (receiver && idleMs > LISTENER_REARM_IDLE_MS && !rearmedForIdle) {
rearmedForIdle = true
removePlusListener()
removeDomListener()
ensurePlusListener()
ensureDomListener()
diagHeal('listener-rearmed-idle', { idleMs, hint: '长时间无按键,强制重挂监听' })
}
diagHeartbeat()
}, period)
}
/** 停止自愈心跳(页面 onHide/deactivated 调用) */
export function stopScanSelfHeal() {
if (selfHealTimer) {
clearInterval(selfHealTimer)
selfHealTimer = null
}
diagPersistNow()
}

View File

@ -169,7 +169,10 @@ import {
unregisterScanReceiver,
setScanPaused,
resetScanBuffer,
startScanSelfHeal,
stopScanSelfHeal,
} from '@/core/scan'
import { diagBegin, diagNote, diagPersistNow } from '@/core/scan-diag'
const qrBaseUrl = 'https://ye4s.wms.gztbyc.com/grcode/build?text='
const qrFallbackBaseUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=280x280&data='
@ -282,20 +285,27 @@ export default {
this.clearHiddenRefocusTimer()
this.clearAutoEnterPackTimer()
this.scanBadgeSubmitting = false
stopScanSelfHeal()
diagPersistNow()
},
onReady() {
this.pageActive = true
diagBegin('login')
diagNote('lifecycle', { hook: 'onReady' })
this.hasStoredWorkbench = !!uni.getStorageSync('workbench_token')
this.setupScanCaptureMode()
this.registerScanCapture()
startScanSelfHeal()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(260)
this.checkAppUpdate()
},
onShow() {
this.pageActive = true
diagNote('lifecycle', { hook: 'onShow' })
this.setupScanCaptureMode()
this.registerScanCapture()
startScanSelfHeal()
this.suppressSoftKeyboardBurst()
this.scheduleScanInputFocus(320)
this.resumeWorkbenchFlow()
@ -303,6 +313,7 @@ export default {
},
onHide() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onHide' })
this.stopScanLongPolling()
this.stopWorkbenchLongPolling()
this.abortScanRequest()
@ -318,6 +329,7 @@ export default {
this.clearAutoEnterPackTimer()
this.scanHiddenFocused = false
this.scanInputFocus = false
stopScanSelfHeal()
},
beforeUnmount() {
this.pageActive = false
@ -338,6 +350,8 @@ export default {
this.scanBadgeSubmitting = false
this.scanHiddenFocused = false
this.scanInputFocus = false
stopScanSelfHeal()
diagPersistNow()
},
methods: {
isPageActive() {

View File

@ -6,7 +6,7 @@
<view class="mode-title">
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-name">{{ workbenchInfo.name }}</text>
<text v-if="workbenchInfo && workbenchInfo.name" class="mode-title-divider"></text>
<text class="mode-title-label">打包模式</text>
<text class="mode-title-label" @click="handleDiagTitleTap">打包模式</text>
</view>
</view>
<view class="topbar-actions">
@ -314,6 +314,9 @@
</view>
</view>
</view>
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
</view>
</template>
@ -328,6 +331,18 @@ import {
packOrder,
finishPack,
} from '@/api/index'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import {
diagBegin,
diagDrop,
diagFlush,
diagHeal,
diagHeartbeat,
diagKey,
diagNote,
diagPersistNow,
diagSetGates,
} from '@/core/scan-diag'
// 扫码枪识别参数(广播扫描:扫码枪为键盘 HID 设备,按键事件全局广播)
// 无回车结束符时:停止输入超过该毫秒数视为一次完整扫码,自动提交
@ -359,6 +374,10 @@ const ANDROID_PUNCT_MAP = {
const MEMBER_STORAGE_KEY = 'workbenchMember'
// 扫描记录本地缓存 key(最多 50 条,出入栈:最新在前、超限丢最旧)
const SCAN_RECORDS_STORAGE_KEY = 'packScanRecords'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型(自愈「锁错就永久静默」)
const SCAN_IDLE_LOCK_RESET_MS = 1200
// 长时间(默认 10 分钟)无任何按键到达时强制重挂监听(防桥接回调静默失效)
const SCAN_LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 无新打包任务自动退出:超过该时长(毫秒)自动登出所有成员并结束最后打包任务
const IDLE_AUTO_LOGOUT_MS = 30 * 60 * 1000
// 语音播报:HTTP 语音接口(参考 WMS_PDA voice.js,不依赖平板系统中文语音包)
@ -367,6 +386,7 @@ const VOICE_API_PATH = 'http://tbdata.gztbyc.com'
export default {
name: 'PackagingPage',
components: { ScanDiagPanel },
data() {
return {
workbenchInfo: null,
@ -425,6 +445,13 @@ export default {
scanInputIdleTimer: null,
lastSubmittedScan: { code: '', at: 0 },
lastScannedCode: '',
// ---- 长时间运行可追踪/自愈 ----
lastScanKeyArrivedAt: 0, // 最近一次按键到达(任何门控之前)
scanRearmedForIdle: false, // 本次空闲是否已重挂过监听(收到按键后复位)
scanWatchdogStartedAt: 0, // 看门狗启动时刻(从未收到按键时的空闲基线)
diagPanelVisible: false,
diagTitleTapAt: 0,
diagTitleTapCount: 0,
// ---- 绑定操作员(工作台成员)----
operatorDialogVisible: false,
badgeHandling: false,
@ -590,6 +617,8 @@ export default {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onLoad')
// #endif
diagBegin('packaging')
diagNote('lifecycle', { hook: 'onLoad' })
// 简单守卫:无 token 时回到登录页
if (!uni.getStorageSync('token')) {
uni.reLaunch({
@ -613,6 +642,7 @@ export default {
// #ifdef APP-PLUS
plus.android.importClass('android.util.Log').i('WMSPage', 'onShow')
// #endif
diagNote('lifecycle', { hook: 'onShow' })
try {
this.pageActive = true
this.lockLandscape()
@ -640,6 +670,9 @@ export default {
this.removeGlobalKeyboardListener()
this.clearScanTimers()
this.clearIdleAutoLogoutTimer()
diagNote('lifecycle', { hook: 'onHide' })
diagSetGates({ pageActive: false })
diagPersistNow()
},
methods: {
// 强制锁定横屏 + 全屏重排:
@ -1827,7 +1860,9 @@ export default {
* 回车且有内容时立即提交;无回车结束符则静默防抖自动提交。
*/
handleGlobalKeydown(event) {
this.markScanKeyArrived('dom')
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'dom' })
return
}
const key = event.key || ''
@ -1891,7 +1926,10 @@ export default {
return
}
if (this.isLikelyScannerCode(code, durationMs, true)) {
diagFlush({ trigger: 'enter', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs, trigger: 'enter' })
}
},
touchScanInput() {
@ -1957,15 +1995,30 @@ export default {
},
// 看门狗:即使 onShow 异常未触发也能自愈恢复扫码。
// App/H5 页面隐藏或后台时收不到按键,所以 pageActive=true 不会误处理。
// 长时间运行自愈:
// 1) 空闲超过 10 分钟无任何按键 → 强制重挂 plus/DOM 监听(防桥接回调静默失效);
// 2) 每次心跳刷新门控快照 + 触发 60s 健康心跳,事后可定位「哪一分钟开始收不到按键」。
startScanWatchdog() {
if (this.scanWatchdogTimer) {
return
}
this.scanWatchdogStartedAt = Date.now()
this.scanWatchdogTimer = setInterval(() => {
this.pageActive = true
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
this.ensureScanInputFocus()
this.maybeRearmScanListenersWhenIdle()
diagSetGates({
pageActive: this.pageActive !== false,
plusListener: !!(this.plusKeyListener || this.plusKeyUpListener),
domListener: !!this.globalKeyListener,
eventTypeLock: this._plusKeyEventType || 'none',
idleSec: this.lastScanKeyArrivedAt
? Math.round((Date.now() - this.lastScanKeyArrivedAt) / 1000)
: 0,
})
diagHeartbeat()
}, 2000)
},
stopScanWatchdog() {
@ -1974,6 +2027,52 @@ export default {
this.scanWatchdogTimer = null
}
},
/** 记录「按键到达 JS」(任何门控之前调用),返回距上次按键的空闲时长 */
markScanKeyArrived(source) {
const now = Date.now()
const gap = this.lastScanKeyArrivedAt ? now - this.lastScanKeyArrivedAt : 0
this.lastScanKeyArrivedAt = now
this.scanRearmedForIdle = false
diagKey(source)
return gap
},
/**
* 空闲(默认 10 分钟无任何按键)时强制重挂监听:
* 只在空闲时执行,不会打断正在进行的扫码;
* 用于兜住「监听器还在、但桥接回调不再投递按键」这类长时间运行才出现的静默失效。
*/
maybeRearmScanListenersWhenIdle() {
if (this.scanRearmedForIdle) {
return
}
// 从未收到过按键时以看门狗启动时刻为基准,否则"一直收不到"永远不会触发重挂
const baseline = this.lastScanKeyArrivedAt || this.scanWatchdogStartedAt || Date.now()
const idleMs = Date.now() - baseline
if (idleMs < SCAN_LISTENER_REARM_IDLE_MS) {
return
}
this.scanRearmedForIdle = true
this.removePlusKeyboardListener()
this.removeGlobalKeyboardListener()
this.attachPlusKeyboardListener()
this.attachGlobalKeyboardListener()
diagHeal('listener-rearmed-idle', { idleMs, hint: '长时间无按键,强制重挂监听' })
console.log('[packaging][scan] 已重挂扫码监听(空闲)', idleMs)
},
/** 诊断面板隐藏入口:3 秒内连点标题 5 次(操作员不会误触) */
handleDiagTitleTap() {
const now = Date.now()
if (now - this.diagTitleTapAt > 3000) {
this.diagTitleTapCount = 0
}
this.diagTitleTapAt = now
this.diagTitleTapCount += 1
if (this.diagTitleTapCount >= 5) {
this.diagTitleTapCount = 0
this.diagPanelVisible = true
diagNote('diag-panel-opened')
}
},
isRealDevice() {
// #ifdef APP-PLUS
return true
@ -2040,7 +2139,10 @@ export default {
return
}
if (this.isLikelyScannerCode(code, durationMs, false)) {
diagFlush({ trigger: 'timer', source: 'dom', length: code.length, durationMs })
this.submitScanCode(code, 'dom')
} else {
diagDrop('dom-not-scanner-code', { length: code.length, durationMs })
}
},
attachGlobalKeyboardListener() {
@ -2170,7 +2272,16 @@ export default {
},
// 统一处理 plus.key 按键(keydown / keyup)
handlePlusKeyEvent(event, type) {
// 先记录「按键到达 JS」这一事实(任何门控之前),用于区分「按键根本没到」与「到了被门控丢掉」
const gap = this.markScanKeyArrived('plus')
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (this._plusKeyEventType && gap > SCAN_IDLE_LOCK_RESET_MS) {
const locked = this._plusKeyEventType
this._plusKeyEventType = null
diagHeal('event-type-lock-idle-reset', { locked, gapMs: gap })
}
if (!this.isPageActive()) {
diagDrop('page-inactive', { source: 'plus' })
return
}
const keyCode = Number((event && event.keyCode) || 0)
@ -2194,6 +2305,7 @@ export default {
this._plusShiftPrev = this._plusShiftDown
const isEnter = this.isPlusEnterKey(keyCode, text)
if (!text && !isEnter) {
diagDrop('unmapped-keycode', { keyCode, type })
return
}
@ -2202,6 +2314,7 @@ export default {
this._plusKeyEventType = type
}
if (this._plusKeyEventType !== type) {
diagDrop('event-type-locked', { keyCode, type, locked: this._plusKeyEventType })
return
}
@ -2242,9 +2355,13 @@ export default {
},
flushPlusKeyBuffer(trigger = 'timer') {
if (!this.isPageActive()) {
diagDrop('page-inactive-flush', { source: 'plus', trigger })
return
}
const code = (this.plusKeyBuffer || '').trim()
const durationMs = this.plusKeyStartedAt
? Math.max(0, (this.plusKeyLastAt || Date.now()) - this.plusKeyStartedAt)
: 0
this.plusKeyBuffer = ''
this.plusKeyStartedAt = 0
this.plusKeyLastAt = 0
@ -2252,6 +2369,7 @@ export default {
if (!code) {
return
}
diagFlush({ trigger, source: 'plus', length: code.length, durationMs })
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code)
this.submitScanCode(code, 'plus')
},
@ -2490,6 +2608,7 @@ export default {
},
submitScanCode(code, source) {
if (!this.isPageActive()) {
diagDrop('page-inactive-submit', { source })
return
}
const trimmed = this.dedupeRepeatedScan((code || '').trim())
@ -2502,9 +2621,11 @@ export default {
this.lastSubmittedScan.code === trimmed &&
now - this.lastSubmittedScan.at < 600
) {
diagDrop('dedupe-same-code', { source, length: trimmed.length })
return
}
this.lastSubmittedScan = { code: trimmed, at: now }
diagNote('submit-scan', { source, length: trimmed.length })
console.log('[packaging][scan] submitScanCode source =', source, 'code =', trimmed)
// 操作员弹窗打开时:弹窗已无输入框,关闭弹窗后扫码内容走主流程
if (this.operatorDialogVisible) {

View File

@ -7,7 +7,7 @@
<view class="rp-left">
<view class="rp-card">
<view class="rp-card-title-row">
<text class="rp-card-title">拆包工作台</text>
<text class="rp-card-title" @click="handleDiagTitleTap">拆包工作台</text>
<view class="rp-card-title-actions">
<button class="rp-btn rp-btn--mini rp-btn--plain" @click="openCameraSettings">摄像头设置</button>
</view>
@ -408,6 +408,9 @@
@confirm="handleHiddenScanConfirm"
@blur="handleHiddenScanBlur"
/>
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
</view>
</template>
@ -438,7 +441,9 @@ import {
cameraServerDetail,
getLiveStreamUrl,
} from '@/api/camera'
import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength } from '@/core/scan'
import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength, startScanSelfHeal, stopScanSelfHeal } from '@/core/scan'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import { diagBegin, diagDrop, diagNote, diagPersistNow } from '@/core/scan-diag'
// ==================== 扫码指令定义(与散单 Web 端 scan-commands.ts 一致) ====================
// 制式 Code 128,内容为简单单词,识别时 trim + 忽略大小写,与商品条码(纯数字)零冲突
@ -485,6 +490,7 @@ export default {
name: 'ReturnsPage',
components: {
TopNav,
ScanDiagPanel,
},
props: {
// 在布局壳内渲染时为 true,隐藏内嵌顶栏;独立访问时不传,显示顶栏
@ -572,6 +578,10 @@ export default {
// 扫码捕获状态
pageActive: false,
modalBusy: false,
// 诊断面板(隐藏入口:3 秒内连点标题 5 次)
diagPanelVisible: false,
diagTitleTapAt: 0,
diagTitleTapCount: 0,
scanHiddenFocused: false,
scanInputFocus: false,
scanHiddenValue: '',
@ -722,8 +732,11 @@ export default {
},
onShow() {
this.pageActive = true
diagBegin('returns')
diagNote('lifecycle', { hook: 'onShow' })
this.registerScanCapture()
this.resumePreviewIfNeeded()
startScanSelfHeal()
// APP:保持隐藏 input 聚焦(WebView 不聚焦不派发按键);H5 全局 DOM 监听无需焦点
// #ifdef APP-PLUS
this.requestScanFocus()
@ -731,31 +744,41 @@ export default {
},
onHide() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onHide' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
},
onUnload() {
this.pageActive = false
diagNote('lifecycle', { hook: 'onUnload' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
diagPersistNow()
},
// keep-alive 内嵌模式(外壳菜单切换):页面级 onShow/onHide 不会触发,
// 扫码捕获必须挂在 keep-alive 的 activated/deactivated 上(与订单复核页一致)
activated() {
this.pageActive = true
diagBegin('returns')
diagNote('lifecycle', { hook: 'activated' })
this.registerScanCapture()
this.resumePreviewIfNeeded()
startScanSelfHeal()
// #ifdef APP-PLUS
this.requestScanFocus()
// #endif
},
deactivated() {
this.pageActive = false
diagNote('lifecycle', { hook: 'deactivated' })
this.unregisterScanCapture()
this.clearScanTimers()
this.stopPreviewStream()
stopScanSelfHeal()
},
methods: {
// ==================== 通用 ====================
@ -849,11 +872,29 @@ export default {
return this.pageActive
},
/** 诊断面板隐藏入口:3 秒内连点标题 5 次(操作员不会误触) */
handleDiagTitleTap() {
const now = Date.now()
if (now - this.diagTitleTapAt > 3000) {
this.diagTitleTapCount = 0
}
this.diagTitleTapAt = now
this.diagTitleTapCount += 1
if (this.diagTitleTapCount >= 5) {
this.diagTitleTapCount = 0
this.diagPanelVisible = true
diagNote('diag-panel-opened')
}
},
registerScanCapture() {
setScanMinLength(SCAN_MIN_LENGTH)
registerScanReceiver({
onScanCode: (code, meta) => {
if (!this.isPageActive()) return
if (!this.isPageActive()) {
diagDrop('page-inactive-receiver', { source: 'receiver' })
return
}
this.handleScanCode(code, meta)
},
onScanDebug: (...args) => {