import { config, dashboardEndpoints } from '../config'; import { getDemoData } from '../mock'; import type { DashboardData, ProductionOverview, ProductionProgress, WarehouseOverview, } from '../types'; export type DataMode = 'sse' | 'polling' | 'demo' | 'init'; type ChangeListener = (data: DashboardData | null) => void; type ModeListener = (mode: DataMode) => void; type ErrorListener = (message: string) => void; /** * 看板数据源。 * * 双通道设计: * 1. HTTP 快照轮询(兜底保真)——每 pollIntervalMs 拉一次 /dashboard/snapshot, * 保证真实数据一到位、或演示期间业务起量后能自动切回,不依赖事件推送。 * 2. SSE 长连接(实时增强)——业务事件发生时即时刷新,可用时顶部标“实时推送”。 * * 关于演示数据:看板是纯展示系统,MES 业务库在投产前为空,直连会让大屏显示全 0, * 比展示演示数据更糟。因此真实数据为空(无工单且无产量)时自动降级演示数据并在界面标注, * 演示期间轮询不停止,真实数据一到位即自动切回。 */ export class DashboardDataService { private baseUrl = config.mesBaseUrl; private token = config.internalToken; private forceDemo = config.forceDemo; private controller: AbortController | null = null; private timer: ReturnType | null = null; private pollingInFlight = false; private changeListeners = new Set(); private modeListeners = new Set(); private errorListeners = new Set(); mode: DataMode = 'init'; private running = false; onChange(cb: ChangeListener): () => void { this.changeListeners.add(cb); return () => this.changeListeners.delete(cb); } onModeChange(cb: ModeListener): () => void { this.modeListeners.add(cb); return () => this.modeListeners.delete(cb); } onError(cb: ErrorListener): () => void { this.errorListeners.add(cb); return () => this.errorListeners.delete(cb); } private emit(data: DashboardData | null) { this.changeListeners.forEach((l) => l(data)); } private setMode(m: DataMode) { if (this.mode === m) return; this.mode = m; this.modeListeners.forEach((l) => l(m)); } private emitError(msg: string) { this.errorListeners.forEach((l) => l(msg)); } /** 启动数据流(幂等) */ start() { if (this.running) return; this.running = true; if (this.forceDemo) { this.useDemo('已启用强制演示模式'); return; } void this.pollOnce(); this.startPolling(); void this.openSse(); } stop() { this.running = false; this.closeStream(); this.stopPolling(); this.changeListeners.clear(); this.modeListeners.clear(); this.errorListeners.clear(); } /** 手动重试:重走一次完整数据流 */ retry() { if (!this.running) this.running = true; if (this.forceDemo) { this.useDemo('已启用强制演示模式'); return; } this.closeStream(); this.stopPolling(); void this.pollOnce(); this.startPolling(); void this.openSse(); } /** 降级到演示数据(轮询不停止,真实数据到位后自动切回) */ private useDemo(reason: string) { this.setMode('demo'); this.emit(getDemoData()); this.emitError(reason); } // ---------- HTTP 快照轮询(兜底保真) ---------- private startPolling() { this.stopPolling(); this.timer = setInterval(() => void this.pollOnce(), config.pollIntervalMs); } private stopPolling() { if (this.timer) { clearInterval(this.timer); this.timer = null; } } private async pollOnce() { if (!this.running || this.pollingInFlight) return; this.pollingInFlight = true; try { const res = await fetch(`${this.baseUrl}${dashboardEndpoints.snapshot}`, { headers: { 'X-API-TOKEN': this.token }, }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const raw = unwrapPayload(await res.json()) as Partial; this.accept(raw, 'polling'); } catch (err) { if (!this.running) return; // 已处于演示模式且后端仍不可达时,不再重复弹错/重发演示数据 if (this.mode !== 'demo') { this.useDemo( `MES 不可用,已切换演示数据(${err instanceof Error ? err.message : '网络异常'})`, ); } } finally { this.pollingInFlight = false; } } // ---------- SSE(实时增强) ---------- private async openSse() { this.closeStream(); const url = `${this.baseUrl}${dashboardEndpoints.stream}`; const controller = new AbortController(); this.controller = controller; try { const res = await fetch(url, { headers: { 'X-API-TOKEN': this.token }, signal: controller.signal, }); if (!res.ok || !res.body) throw new Error(`SSE 连接失败:HTTP ${res.status}`); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; for (;;) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const blocks = buffer.split('\n\n'); buffer = blocks.pop() ?? ''; for (const block of blocks) { const lines = block.split('\n'); const dataLine = lines.find((l) => l.startsWith('data:')); if (!dataLine) continue; const payload = dataLine.replace(/^data:\s*/, '').trim(); if (!payload) continue; // 事件驱动:业务数据落库后后端广播 dashboard.updated(空载荷), // 收到即拉一次最新快照,实时性优于轮询周期。 const evtLine = lines.find((l) => l.startsWith('event:')); if (evtLine && evtLine.includes('dashboard.updated')) { void this.pollOnce(); continue; } try { const parsed = unwrapPayload(JSON.parse(payload)) as Partial; // 忽略 hello / 心跳等无数据载荷(无 production 且无 updatedAt) if (!parsed || typeof parsed !== 'object' || (!parsed.production && !parsed.updatedAt)) { continue; } this.accept(parsed, 'sse'); } catch { // 单条事件解析失败不影响后续推送 } } } if (this.running && this.mode === 'sse') this.setMode('polling'); } catch (err) { if (!this.running) return; if (err instanceof Error && err.name === 'AbortError') return; // SSE 不可用时依赖轮询通道;仍在 init 则先降级演示,等待轮询恢复 if (this.mode === 'init') this.useDemo('实时通道不可用,已切换演示数据'); else if (this.mode === 'sse') this.setMode('polling'); } } private closeStream() { this.controller?.abort(); this.controller = null; } /** 接收一次数据:补全字段后判定是否为空,空则演示;有真数据则按来源标记通道 */ private accept(raw: Partial, source: 'sse' | 'polling') { const data = normalize(raw); if (isEmpty(data)) { if (this.mode !== 'demo') this.useDemo('MES 暂无业务数据,已切换演示数据'); return; } if (this.mode !== source) this.setMode(source); this.emit(data); } } /** 真实业务数据是否为空:无工单且无产量即视为尚未投产 */ function isEmpty(d: DashboardData): boolean { return !d.progress?.orderNo && (d.production?.outputToday ?? 0) === 0; } /** 后端响应统一为 {code,message,data},取 data 层;SSE 心跳推的是裸对象,两种都兼容 */ function unwrapPayload(j: unknown): unknown { if (j && typeof j === 'object' && !Array.isArray(j)) { const o = j as { code?: unknown; data?: unknown }; if (o.code !== undefined && 'data' in o) return o.data; } return j; } /** * 字段补全:后端可能只返回部分字段,缺失一律补零值, * 避免前端到处判空,也避免 undefined 传进图表。 */ function normalize(raw: Partial): DashboardData { const p: ProductionOverview = raw.production ?? ({} as ProductionOverview); const w: WarehouseOverview = raw.warehouse ?? ({} as WarehouseOverview); const pr: ProductionProgress = raw.progress ?? ({} as ProductionProgress); return { production: { outputToday: p.outputToday ?? 0, targetToday: p.targetToday ?? 0, passCount: p.passCount ?? 0, torqueCount: p.torqueCount ?? 0, inLine: p.inLine ?? 0, deviceOnline: p.deviceOnline ?? 0, deviceTotal: p.deviceTotal ?? 0, stationSummary: { running: p.stationSummary?.running ?? 0, idle: p.stationSummary?.idle ?? 0, offline: p.stationSummary?.offline ?? 0, alarm: p.stationSummary?.alarm ?? 0, }, }, warehouse: { totalStock: w.totalStock ?? 0, materialTypes: w.materialTypes ?? 0, inboundToday: w.inboundToday ?? 0, outboundToday: w.outboundToday ?? 0, movements: w.movements ?? [], }, equipment: raw.equipment ?? [], progress: { orderNo: pr.orderNo ?? '', contractNo: pr.contractNo ?? '', productName: pr.productName ?? '', owner: pr.owner ?? '', planStart: pr.planStart ?? '', planEnd: pr.planEnd ?? '', remainDays: pr.remainDays ?? 0, totalQty: pr.totalQty ?? 0, doneQty: pr.doneQty ?? 0, progress: pr.progress ?? 0, processDone: pr.processDone ?? 0, processTotal: pr.processTotal ?? 0, currentProcess: pr.currentProcess ?? '', status: pr.status ?? '', traceStepCount: pr.traceStepCount ?? 0, traceable: pr.traceable ?? false, steps: pr.steps ?? [], }, traces: raw.traces ?? [], trends: raw.trends ?? { production: [] }, isDemo: false, }; }