| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- /**
- * 运行链路领域接口(票 05 只交 REST 侧的分区读取;消费方是票 15/16)。
- *
- * ADR 0005 的 `runtimeApi`:WebSocket 是运行链路,前端消费的是**版本化领域事件**,
- * 不把 `/ws/deviceStatus` 的裸 JSON 当依赖。本文件先交 REST 侧能落地的部分
- * (新鲜度、设备状态增量帧 → 领域事件的**转换**),连接与重连归票 15。
- *
- * 增量帧的字段名有个坑(调研 §1 已核实):WS 线上帧的状态键是 `data.status`,
- * 而后端 DTO 命名为 `monitoringState`。转换层两个键都认,避免接错一边就静默丢状态。
- */
- import { toFreshness } from '../domain/freshness.js'
- import { fetchSection } from './domainRequest.js'
- import { SECTION_STATE, section } from '../domain/sectionState.js'
- /**
- * WS 消息类型(后端 `DeviceStatusWebSocketHandler` / `DeviceStatusRedisListener`)。
- *
- * 线上形状(2026-09-28 按 ADR 0005 修订后的后端协议核实):
- * · 连接后**直接** `cockpitSubscribe`(`scope` 只认 `"all"`),回 `cockpitSubscribed`
- * (只带 `scope` 与 `serverUpdatedAt`,**不带初始状态数组** —— REST 才是初始快照);
- * 免鉴权:**不再要求也不发送 `authenticate` 帧**(那是管理端工单推送的机制);
- * · 增量帧 `cockpitDeviceStatusDelta`:`deviceCode`/`device_code`/`monitoringPointCode`
- * 与 `data.{status,statusTime,serverUpdatedAt,reason}` **平级在顶层**(见
- * `DeviceStatusRedisListener.cockpitDeltaMessage`)。`monitoringPointCode`
- * 未关联设备时为 `null`(显式给,不静默丢)。
- *
- * `AUTHENTICATE`/`AUTHENTICATED` 常量保留:后端协议里它们仍服务管理端工单推送,
- * 驾驶舱消费方(runtimeSocket)已不再使用,留作字典完整性与旧走查兼容。
- */
- export const WS_MESSAGE = {
- SUBSCRIBE: 'cockpitSubscribe',
- SUBSCRIBED: 'cockpitSubscribed',
- DELTA: 'cockpitDeviceStatusDelta',
- ORDER_DELTA: 'cockpitWorkOrderStateDelta',
- AUTHENTICATE: 'authenticate',
- AUTHENTICATED: 'authenticated',
- PONG: 'pong',
- ERROR: 'error',
- }
- /**
- * 设备状态增量帧 → 领域事件。
- *
- * 只做字段归一,不做取舍:是否采纳(旧消息要丢弃)由运行时服务按 `serverUpdatedAt` 判。
- * `monitoringPointCode` 是**点位状态联动的唯一依据**(CONTEXT.md:前端不重算点位状态,
- * 所以只有后端在帧里指名了点位,才允许改写那个点位的状态;没给就只更新设备维度)。
- * @param {object} frame WS 线上帧
- * @returns {object|null} 认不出的帧回 null(调用方据此忽略,不猜)
- */
- export function toDeviceStatusEvent(frame) {
- const raw = frame && typeof frame === 'object' ? frame : null
- if (!raw || raw.type !== WS_MESSAGE.DELTA) return null
- const payload = raw.data && typeof raw.data === 'object' ? raw.data : {}
- const deviceCode = raw.deviceCode || raw.device_code || payload.deviceCode || ''
- if (!deviceCode) return null
- return {
- deviceCode,
- // 后端在顶层给点位码(票 25 的 BT-1);两个位置都认,避免接错一边就静默丢联动。
- monitoringPointCode: raw.monitoringPointCode || payload.monitoringPointCode || '',
- // 线上帧用 status,DTO 用 monitoringState:两个都认。
- status: payload.status || payload.monitoringState || '',
- statusTime: payload.statusTime || '',
- serverUpdatedAt: payload.serverUpdatedAt || raw.serverUpdatedAt || '',
- reason: payload.reason || '',
- // 增量帧不带坐标与行业(只能靠 deviceCode 回联 REST 快照)——运行时服务据此设计合并。
- sampledAt: payload.sampledAt || '',
- eventId: typeof raw.eventId === 'string' ? raw.eventId : null,
- }
- }
- /** 工单扫描增量独立解析;不借设备状态帧推断工单或伪造操作时间。 */
- export function toWorkOrderDelta(frame) {
- if (!frame || frame.type !== WS_MESSAGE.ORDER_DELTA) return null
- if (typeof frame.serverUpdatedAt !== 'string' || !Number.isFinite(Date.parse(frame.serverUpdatedAt))) return null
- const rows = frame.data && frame.data.items
- if (!Array.isArray(rows)) return null
- const items = rows.filter((row) => row && typeof row.workOrderCode === 'string' && row.workOrderCode.trim())
- .map((row) => ({
- code: row.workOrderCode.trim(),
- deviceCode: typeof row.deviceCode === 'string' ? row.deviceCode : '',
- stateCode: Number.isInteger(row.stateCode) ? row.stateCode : null,
- stateName: typeof row.stateName === 'string' ? row.stateName : '',
- }))
- if (!items.length) return null
- return {
- items,
- serverUpdatedAt: frame.serverUpdatedAt,
- scanIntervalMs: Number.isFinite(frame.scanIntervalMs) && frame.scanIntervalMs > 0 ? frame.scanIntervalMs : null,
- }
- }
- /**
- * 鉴权回帧 → 领域事件。**历史接口**:驾驶舱免鉴权后不再消费该帧
- * (`authenticated` 只在管理端工单推送链路出现);保留供旧调用方/走查兼容。
- */
- export function toAuthenticatedEvent(frame) {
- const raw = frame && typeof frame === 'object' ? frame : null
- if (!raw || raw.type !== WS_MESSAGE.AUTHENTICATED) return null
- return {
- ok: raw.success === true,
- // 失败时后端给的中文原因(如「token 无效或已过期」);成功时为空串。
- reason: raw.msg || '',
- }
- }
- /** 订阅确认帧 → 领域事件。 */
- export function toSubscribedEvent(frame) {
- const raw = frame && typeof frame === 'object' ? frame : null
- if (!raw || raw.type !== WS_MESSAGE.SUBSCRIBED) return null
- return { scope: raw.scope || '', serverUpdatedAt: raw.serverUpdatedAt || '' }
- }
- /**
- * 设备新鲜度分区(票 16 的统一新鲜度模型)。
- * @param {string} deviceCode 设备编码
- * @param {object} [options] `{ calibrationPeriodSeconds, config, fetchImpl }`
- */
- export async function fetchFreshnessSection(deviceCode, options = {}) {
- if (!deviceCode) {
- return section(SECTION_STATE.FAILED, { reason: '缺少设备编码' })
- }
- const result = await fetchSection(`/equipments/${encodeURIComponent(deviceCode)}/freshness`, {
- params: { calibrationPeriodSeconds: options.calibrationPeriodSeconds },
- toData: toFreshness,
- config: options.config,
- fetchImpl: options.fetchImpl,
- })
- if (result.state !== SECTION_STATE.SUCCESS) return result
- const freshness = result.data || {}
- // 后端四态 → 分区状态:EXPIRED/STALE 归「过期但保留旧值」,EMPTY 归「确实没有」。
- if (freshness.freshness === 'EMPTY') {
- return section(SECTION_STATE.EMPTY, { mode: result.mode, data: freshness, freshness: 'EMPTY' })
- }
- if (freshness.freshness === 'EXPIRED' || freshness.freshness === 'STALE') {
- return section(SECTION_STATE.STALE, {
- mode: result.mode,
- reason: freshness.staleReason || '',
- data: freshness,
- freshness: freshness.freshness,
- retained: freshness.retained === true,
- })
- }
- return section(SECTION_STATE.SUCCESS, { mode: result.mode, data: freshness, freshness: freshness.freshness || 'CURRENT' })
- }
|