From 2b5081061e365d045813ddca8b7543c48376cf7d Mon Sep 17 00:00:00 2001 From: zhougf Date: Mon, 1 Jun 2026 21:48:29 +0800 Subject: [PATCH] Add factory dashboard SignalR integration --- apps/factory-dashboard/package.json | 1 + .../src/api/dashboardSignalR.ts | 344 ++++++++++++++++++ .../src/components/CncCard.tsx | 2 +- .../src/components/FocusDevicePanel.tsx | 95 ++++- .../src/components/StatusSummary.tsx | 20 +- .../src/domain/deviceTypes.ts | 14 + .../src/mock/factoryDevices.ts | 7 + .../src/pages/DashboardPage.tsx | 100 ++++- .../src/styles/factory-dashboard.css | 30 +- doc/factory-dashboard-wms-progress.md | 261 +++++++++++++ packages/charts/src/optionFactories.ts | 4 + pnpm-lock.yaml | 187 ++++++++++ 12 files changed, 1018 insertions(+), 47 deletions(-) create mode 100644 apps/factory-dashboard/src/api/dashboardSignalR.ts create mode 100644 doc/factory-dashboard-wms-progress.md diff --git a/apps/factory-dashboard/package.json b/apps/factory-dashboard/package.json index 56a2466..7429c05 100644 --- a/apps/factory-dashboard/package.json +++ b/apps/factory-dashboard/package.json @@ -14,6 +14,7 @@ "@dev-screen-starter/debug": "workspace:*", "@dev-screen-starter/screen-core": "workspace:*", "@dev-screen-starter/visual-kit": "workspace:*", + "@microsoft/signalr": "^10.0.0", "@vitejs/plugin-react": "^5.0.4", "echarts": "^6.0.0", "react": "^19.1.1", diff --git a/apps/factory-dashboard/src/api/dashboardSignalR.ts b/apps/factory-dashboard/src/api/dashboardSignalR.ts new file mode 100644 index 0000000..5130bd2 --- /dev/null +++ b/apps/factory-dashboard/src/api/dashboardSignalR.ts @@ -0,0 +1,344 @@ +import * as signalR from '@microsoft/signalr' +import type { AlarmRow, CncDevice, DeviceTrendData, FactoryDevice, PowerDevice, WeeklyStats } from '../domain/deviceTypes' + +type DashboardDailyProductionDto = { + dates?: string[] + Dates?: string[] + produce?: number[] + Produce?: number[] + runtime?: number[] + Runtime?: number[] +} + +type DashboardDeviceDto = { + deviceId?: string + DeviceId?: string + deviceName?: string + DeviceName?: string + deviceType?: string + DeviceType?: string + status?: string + Status?: string + alarmSummary?: string + AlarmSummary?: string + realtime?: Record + Realtime?: Record + dailyProduction?: DashboardDailyProductionDto + DailyProduction?: DashboardDailyProductionDto + trendPoints?: DashboardTrendPointDto[] + TrendPoints?: DashboardTrendPointDto[] +} + +type DashboardAlarmDto = { + deviceId?: string + DeviceId?: string + alarmMessage?: string + AlarmMessage?: string + lastSeenTime?: string + LastSeenTime?: string + startTime?: string + StartTime?: string +} + +type DashboardSnapshotDto = { + devices?: DashboardDeviceDto[] + Devices?: DashboardDeviceDto[] + alarms?: DashboardAlarmDto[] + Alarms?: DashboardAlarmDto[] +} + +type DashboardTrendPointDto = { + metricName?: string + MetricName?: string + bucketTime?: string + BucketTime?: string + avgValue?: number + AvgValue?: number +} + +type DashboardSignalRHandlers = { + onConnectionState: (state: string) => void + onSnapshot: (devices: DashboardDeviceDto[], alarms: AlarmRow[]) => void + onDeviceUpdated: (device: DashboardDeviceDto) => void + onAlarmUpdated: (deviceId: string, alarms: AlarmRow[]) => void + onTrendUpdated: (deviceId: string, points: DashboardTrendPointDto[]) => void +} + +export function connectDashboardSignalR(url: string, handlers: DashboardSignalRHandlers) { + const connection = new signalR.HubConnectionBuilder() + .withUrl(url) + .withAutomaticReconnect() + .build() + + connection.onreconnecting(() => handlers.onConnectionState('重连中')) + connection.onreconnected(() => handlers.onConnectionState('已连接')) + connection.onclose(() => handlers.onConnectionState('已断开')) + + connection.on('device.updated', (device: DashboardDeviceDto) => { + handlers.onDeviceUpdated(device) + }) + + connection.on('alarm.updated', (payload: { deviceId?: string; DeviceId?: string; alarms?: DashboardAlarmDto[]; Alarms?: DashboardAlarmDto[] }) => { + const deviceId = payload.deviceId ?? payload.DeviceId ?? '' + handlers.onAlarmUpdated(deviceId, mapAlarms(payload.alarms ?? payload.Alarms ?? [])) + }) + + connection.on('trend.updated', (payload: { deviceId?: string; DeviceId?: string; points?: DashboardTrendPointDto[]; Points?: DashboardTrendPointDto[] }) => { + const deviceId = payload.deviceId ?? payload.DeviceId ?? '' + handlers.onTrendUpdated(deviceId, payload.points ?? payload.Points ?? []) + }) + + connection.start() + .then(async () => { + handlers.onConnectionState('已连接') + const snapshot = await connection.invoke('GetSnapshot') + handlers.onSnapshot(snapshot.devices ?? snapshot.Devices ?? [], mapAlarms(snapshot.alarms ?? snapshot.Alarms ?? [])) + }) + .catch((error) => { + handlers.onConnectionState(`连接失败: ${error instanceof Error ? error.message : String(error)}`) + }) + + return () => { + void connection.stop() + } +} + +export function applyDashboardDeviceUpdate(devices: FactoryDevice[], dto: DashboardDeviceDto): FactoryDevice[] { + const deviceId = dto.deviceId ?? dto.DeviceId ?? '' + const deviceType = String(dto.deviceType ?? dto.DeviceType ?? '').toLowerCase() + const status = String(dto.status ?? dto.Status ?? '') + const realtime = (dto.realtime ?? dto.Realtime ?? {}) as Record + const dailyProduction = dto.dailyProduction ?? dto.DailyProduction + const trendPoints = dto.trendPoints ?? dto.TrendPoints ?? [] + const index = devices.findIndex((device) => isSameDevice(device, deviceId, deviceType)) + const current = index >= 0 ? devices[index] : createDeviceFromDto(deviceId, deviceType) + if (!current) return devices + + const next = updateDevice(current, deviceId, deviceType, status, realtime, dailyProduction) + const nextWithTrend = trendPoints.length ? applyTrendToDevice(next, trendPoints) : next + if (index < 0) return [...devices, nextWithTrend] + return devices.map((device, i) => (i === index ? nextWithTrend : device)) +} + +export function applyDashboardTrendUpdate(devices: FactoryDevice[], deviceId: string, points: DashboardTrendPointDto[]): FactoryDevice[] { + if (!deviceId || points.length === 0) return devices + + return devices.map((device) => { + if (!isSameDevice(device, deviceId, device.type)) return device + + return applyTrendToDevice(device, points) + }) +} + +function applyTrendToDevice(device: FactoryDevice, points: DashboardTrendPointDto[]): FactoryDevice { + const trend = buildTrendData(device.type, points) + return trend ? { ...device, trend } : device +} + +function updateDevice(device: FactoryDevice, deviceId: string, deviceType: string, status: string, realtime: Record, dailyProduction?: DashboardDailyProductionDto): FactoryDevice { + if (device.type === 'cnc' || deviceType === 'cnc') { + const cncDevice = (device.type === 'cnc' ? device : createDeviceFromDto(deviceId, 'cnc')) as CncDevice + return { + ...cncDevice, + online: true, + weeklyStats: mapDailyProduction(dailyProduction) ?? cncDevice.weeklyStats, + machineData: { + ...(cncDevice.machineData ?? {}), + alarm: readStringArray(realtime.alarmMessages), + alarmStatus: status === 'alarm' ? 1 : 0, + runtime: minutesToFanucTime(readNumber(realtime.runtimeMinutes)), + cuttime: minutesToFanucTime(readNumber(realtime.cuttimeMinutes)), + cycletime: minutesToFanucTime(readNumber(realtime.cycletimeMinutes)), + currentProduceCount: readNumber(realtime.currentProduceCount), + todayProduce: readNumber(realtime.todayProduce), + programCurrent: { + name: readString(realtime.programName) ?? '无程序', + number: readNumber(realtime.programNumber) + }, + setFeedRate: readNumber(realtime.setFeedRate), + setSpindleSpeed: readNumber(realtime.setSpindleSpeed), + spindleSpeedAndFeedRate: { + speed: readNumber(realtime.spindleSpeed), + feedRate: readNumber(realtime.feedRate) + }, + statusInfo: { + Alarm: status === 'alarm' ? 1 : 0, + Emergency: 0, + Motion: status === 'running' ? 1 : 0, + MSTB: status === 'running' ? 1 : 0, + RunStatus: readString(realtime.runStatus) ?? (status === 'running' ? '3' : '0'), + WorkMode: readString(realtime.workMode) ?? '1' + }, + sysInfo: { + axes: readNumber(realtime.axes), + cncType: readString(realtime.cncType), + mtType: 'Machining center' + }, + timestamp: readString(realtime.payloadTime) ?? new Date().toISOString() + } + } + } + + if (device.type === 'power' || deviceType === 'power') { + const powerDevice = (device.type === 'power' ? device : createDeviceFromDto(deviceId, 'power')) as PowerDevice + return { + ...powerDevice, + online: true, + machineData: { + timestamp: readString(realtime.payloadTime) ?? new Date().toISOString(), + slave1: { + current1: formatAmp(realtime.currentA), + current2: formatAmp(realtime.currentB), + current3: formatAmp(realtime.currentC) + } + } + } + } + + return device +} + +function mapDailyProduction(dailyProduction?: DashboardDailyProductionDto): WeeklyStats | null { + if (!dailyProduction) return null + + const dates = dailyProduction.dates ?? dailyProduction.Dates ?? [] + const produce = toNumberArray(dailyProduction.produce ?? dailyProduction.Produce) + const runtime = toNumberArray(dailyProduction.runtime ?? dailyProduction.Runtime) + if (dates.length === 0 || produce.length === 0) return null + + return { + dates: dates.map((date) => String(date)), + produce, + cuttime: runtime + } +} + +function buildTrendData(deviceType: FactoryDevice['type'], points: DashboardTrendPointDto[]): DeviceTrendData | null { + const rows = points + .map((point) => ({ + metricName: String(point.metricName ?? point.MetricName ?? ''), + bucketTime: String(point.bucketTime ?? point.BucketTime ?? ''), + value: readNumber(point.avgValue ?? point.AvgValue) + })) + .filter((point) => point.bucketTime && point.metricName && point.value != null) + + if (rows.length === 0) return null + + const labels = Array.from(new Set(rows.map((point) => point.bucketTime))).sort() + const valueOf = (metricName: string) => labels.map((time) => rows.find((point) => point.bucketTime === time && point.metricName === metricName)?.value ?? 0) + + if (deviceType === 'power') { + return { + labels: labels.map(formatTrendLabel), + power: valueOf('estimatedPower'), + currentA: valueOf('currentA'), + currentB: valueOf('currentB'), + currentC: valueOf('currentC') + } + } + + if (deviceType === 'cnc') { + return { + labels: labels.map(formatTrendLabel), + produce: valueOf('cncProduceCount'), + runtime: valueOf('runtimeMinutes') + } + } + + return null +} + +function createDeviceFromDto(deviceId: string, deviceType: string): FactoryDevice | null { + if (deviceType === 'cnc') { + return { + id: deviceId, + name: deviceId || 'CNC-UNKNOWN', + type: 'cnc', + online: true, + machineData: null, + weeklyStats: null + } + } + if (deviceType === 'power') { + return { + id: deviceId, + name: powerName(deviceId), + type: 'power', + online: true, + machineData: null, + powerHistory: [] + } + } + return null +} + +function isSameDevice(device: FactoryDevice, deviceId: string, deviceType: string) { + if (device.id === deviceId || device.name === deviceId) return true + if (deviceType === 'cnc' && device.name === deviceId) return true + if (deviceType === 'power') { + if (deviceId.endsWith('001') && device.name.includes('#1')) return true + if (deviceId.endsWith('002') && device.name.includes('#2')) return true + } + return false +} + +function mapAlarms(alarms: DashboardAlarmDto[]): AlarmRow[] { + return alarms.map((alarm) => { + const time = alarm.lastSeenTime ?? alarm.LastSeenTime ?? alarm.startTime ?? alarm.StartTime ?? '' + return { + time: formatTime(time), + device: alarm.deviceId ?? alarm.DeviceId ?? '--', + message: alarm.alarmMessage ?? alarm.AlarmMessage ?? '设备告警' + } + }) +} + +function readString(value: unknown) { + return value == null ? undefined : String(value) +} + +function readNumber(value: unknown) { + const number = Number(value) + return Number.isFinite(number) ? number : undefined +} + +function toNumberArray(value: unknown) { + return Array.isArray(value) ? value.map((item) => Number(item)).map((item) => (Number.isFinite(item) ? item : 0)) : [] +} + +function readStringArray(value: unknown) { + return Array.isArray(value) ? value.map((item) => String(item)) : [] +} + +function minutesToFanucTime(minutes?: number) { + if (!Number.isFinite(minutes)) return undefined + const totalSeconds = Math.max(0, Math.round((minutes ?? 0) * 60)) + const hours = Math.floor(totalSeconds / 3600) + const mins = Math.floor((totalSeconds % 3600) / 60) + const secs = totalSeconds % 60 + return `${hours} H ${mins} M ${secs} S` +} + +function formatAmp(value: unknown) { + const number = readNumber(value) + return number == null ? 'invalid' : `${number.toFixed(1)}A` +} + +function formatTime(value: string) { + if (!value) return '--' + const date = new Date(value) + if (Number.isNaN(date.getTime())) return value.slice(11, 16) || value + return date.toTimeString().slice(0, 5) +} + +function formatTrendLabel(value: string) { + const date = new Date(value) + if (Number.isNaN(date.getTime())) return value.slice(11, 16) || value + return date.toTimeString().slice(0, 5) +} + +function powerName(deviceId: string) { + if (deviceId.endsWith('001')) return '配电柜 #1' + if (deviceId.endsWith('002')) return '配电柜 #2' + return deviceId || '配电柜' +} diff --git a/apps/factory-dashboard/src/components/CncCard.tsx b/apps/factory-dashboard/src/components/CncCard.tsx index 39cc070..8a94157 100644 --- a/apps/factory-dashboard/src/components/CncCard.tsx +++ b/apps/factory-dashboard/src/components/CncCard.tsx @@ -4,7 +4,7 @@ import type { CncDevice } from '../domain/deviceTypes' export function CncCard({ device, onOpen }: { device: CncDevice; onOpen?: () => void }) { const status = getDeviceStatus(device) const machineData = device.machineData - const todayProduce = Number(device.weeklyStats?.produce?.[6] || 0) + const todayProduce = Number(machineData?.todayProduce ?? device.weeklyStats?.produce?.[6] ?? 0) return (