Add factory dashboard SignalR integration
This commit is contained in:
1 parent
1331d10e31
commit
2b5081061e
12 files changed
+1018
-47
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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<string, unknown>
|
||||
Realtime?: Record<string, unknown>
|
||||
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<DashboardSnapshotDto>('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<string, unknown>
|
||||
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<string, unknown>, 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 || '配电柜'
|
||||
}
|
||||
@@ -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 (
|
||||
<button className={`device-card cnc-card status-${status.key}`} onClick={onOpen} type="button">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ChartPanel, createDualAxisOption, createLineOption } from '@dev-screen-starter/charts'
|
||||
import { FlipNumber, TrendBadge, WaterLevel } from '@dev-screen-starter/visual-kit'
|
||||
import { formatFanucTimeShort, getDeviceStatus, getLaserSysStateText, STATUS_COLORS } from '../domain/deviceStatus'
|
||||
import { formatFanucTimeShort, getCncWorkModeText, getDeviceStatus, getLaserSysStateText, STATUS_COLORS } from '../domain/deviceStatus'
|
||||
import type { FactoryDevice } from '../domain/deviceTypes'
|
||||
import { getLast7DaysChartInfo } from '../utils/weekLabels'
|
||||
|
||||
@@ -41,7 +41,7 @@ function FocusRealtime({ device }: { device: FactoryDevice }) {
|
||||
<div className="focus-task">
|
||||
<span>当前图纸</span>
|
||||
<strong>{nc?.TaskName ?? '无当前图纸'}</strong>
|
||||
<small>{getLaserSysStateText(nc?.SysState)}</small>
|
||||
<small>{getLaserSysStateText(nc?.SysState)} · {device.machineData?.timestamp ?? '等待数据'}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="focus-metric-grid">
|
||||
@@ -49,6 +49,8 @@ function FocusRealtime({ device }: { device: FactoryDevice }) {
|
||||
<FocusMetric label="切割长度" value={((device.machineData?.cutLength ?? 0) / 1000).toFixed(1)} unit="m" />
|
||||
<FocusMetric label="激光功率" value={String(nc?.LaserPower ?? 0)} unit="W" />
|
||||
<FocusMetric label="气压" value={String(ds?.GasPressure ?? 0)} unit="Bar" />
|
||||
<FocusMetric label="工作速度" value={String(nc?.WorkSpeed ?? 0)} unit="mm/min" />
|
||||
<FocusMetric label="开光/开气" value={`${ds?.IsLaserOn ? '开光' : '未开光'} · ${ds?.IsGasOn ? '开气' : '未开气'}`} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -56,22 +58,25 @@ function FocusRealtime({ device }: { device: FactoryDevice }) {
|
||||
|
||||
if (device.type === 'cnc') {
|
||||
const md = device.machineData
|
||||
const todayProduce = Number(md?.todayProduce ?? device.weeklyStats?.produce?.[6] ?? 0)
|
||||
|
||||
return (
|
||||
<div className="focus-realtime">
|
||||
<div className="focus-hero">
|
||||
<FlipNumber label="今日产量" value={Number(device.weeklyStats?.produce?.[6] || 0).toLocaleString()} unit="件" tone="green" />
|
||||
<FlipNumber label="今日产量" value={todayProduce.toLocaleString()} unit="件" tone="green" />
|
||||
<div className="focus-task">
|
||||
<span>当前程序</span>
|
||||
<strong>{md?.programCurrent?.name ?? '无程序'}</strong>
|
||||
<small>运行 {formatFanucTimeShort(md?.runtime)}</small>
|
||||
<small>运行 {formatFanucTimeShort(md?.runtime)} · {md?.timestamp ?? '等待数据'}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="focus-metric-grid">
|
||||
<FocusMetric label="累计产量" value={Number(md?.currentProduceCount || 0).toLocaleString()} unit="件" />
|
||||
<FocusMetric label="主轴倍率" value={String(md?.setSpindleSpeed ?? 0)} unit="%" />
|
||||
<FocusMetric label="进给倍率" value={String(md?.setFeedRate ?? 0)} unit="%" />
|
||||
<FocusMetric label="循环时间" value={formatFanucTimeShort(md?.cycletime)} />
|
||||
<FocusMetric label="切削时间" value={formatFanucTimeShort(md?.cuttime)} />
|
||||
<FocusMetric label="实际转速" value={String(md?.spindleSpeedAndFeedRate?.speed ?? 0)} unit="RPM" />
|
||||
<FocusMetric label="进给速度" value={String(md?.spindleSpeedAndFeedRate?.feedRate ?? 0)} unit="mm/min" />
|
||||
<FocusMetric label="工作模式" value={getCncWorkModeText(md?.statusInfo?.WorkMode)} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -103,14 +108,19 @@ function FocusRealtime({ device }: { device: FactoryDevice }) {
|
||||
}
|
||||
|
||||
function FocusTrend({ device }: { device: FactoryDevice }) {
|
||||
const labels = device.weeklyStats?.dates ?? getLast7DaysChartInfo().labels
|
||||
const title = device.type === 'power' ? '最近7天电流趋势' : '最近7天产量与运行趋势'
|
||||
const powerTrend = device.type === 'power' ? buildPowerTrendDisplay(device) : null
|
||||
const hasRealtimeTrend = device.type === 'power' && Boolean(powerTrend?.labels.length)
|
||||
const labels = hasRealtimeTrend ? powerTrend?.labels ?? [] : device.weeklyStats?.dates ?? getLast7DaysChartInfo().labels
|
||||
const title = hasRealtimeTrend
|
||||
? device.type === 'power' ? '最近1小时三相电流趋势' : '实时产量与运行趋势'
|
||||
: device.type === 'power' ? '最近7天电流趋势' : '最近7天产量与运行趋势'
|
||||
const dailyProduce = getDailyProduce(device)
|
||||
const option = device.type === 'power'
|
||||
? createLineOption({
|
||||
categories: labels,
|
||||
values: device.powerHistory ?? [],
|
||||
name: '视在功率',
|
||||
color: '#d8a13e'
|
||||
series: hasRealtimeTrend
|
||||
? powerTrend?.series ?? []
|
||||
: [{ name: '视在功率', values: device.powerHistory ?? [], color: '#d8a13e' }]
|
||||
})
|
||||
: createDualAxisOption({
|
||||
categories: labels,
|
||||
@@ -118,7 +128,7 @@ function FocusTrend({ device }: { device: FactoryDevice }) {
|
||||
rightName: '运行时长',
|
||||
bar: {
|
||||
name: device.type === 'laser' ? '穿孔' : '产量',
|
||||
values: device.weeklyStats?.produce ?? [],
|
||||
values: dailyProduce,
|
||||
color: '#63a4ff'
|
||||
},
|
||||
line: {
|
||||
@@ -139,6 +149,67 @@ function FocusTrend({ device }: { device: FactoryDevice }) {
|
||||
)
|
||||
}
|
||||
|
||||
function buildPowerTrendDisplay(device: Extract<FactoryDevice, { type: 'power' }>) {
|
||||
const latestLabel = formatTrendTime(device.machineData?.timestamp) ?? '当前'
|
||||
const labels = appendLatestLabel(device.trend?.labels ?? [], latestLabel)
|
||||
const currentA = appendLatestTrendValue(device.trend?.currentA ?? [], parseAmp(device.machineData?.slave1?.current1), labels.length)
|
||||
const currentB = appendLatestTrendValue(device.trend?.currentB ?? [], parseAmp(device.machineData?.slave1?.current2), labels.length)
|
||||
const currentC = appendLatestTrendValue(device.trend?.currentC ?? [], parseAmp(device.machineData?.slave1?.current3), labels.length)
|
||||
|
||||
return {
|
||||
labels,
|
||||
series: [
|
||||
{ name: 'A相', values: currentA, color: '#63a4ff', step: 'end' as const },
|
||||
{ name: 'B相', values: currentB, color: '#56d08a', step: 'end' as const },
|
||||
{ name: 'C相', values: currentC, color: '#d8a13e', step: 'end' as const }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function appendLatestLabel(labels: string[], latestLabel: string) {
|
||||
if (labels.length === 0) return [latestLabel]
|
||||
if (labels[labels.length - 1] === latestLabel) return labels
|
||||
|
||||
return [...labels, latestLabel]
|
||||
}
|
||||
|
||||
function appendLatestTrendValue(values: number[], latest: number | undefined, targetLength: number) {
|
||||
const fallback = Number.isFinite(latest) ? latest ?? 0 : values[values.length - 1] ?? 0
|
||||
const next = [...values]
|
||||
|
||||
while (next.length < Math.max(targetLength - 1, 0)) {
|
||||
next.push(next[next.length - 1] ?? fallback)
|
||||
}
|
||||
|
||||
if (next.length === targetLength) {
|
||||
next[next.length - 1] = fallback
|
||||
return next
|
||||
}
|
||||
|
||||
return [...next, fallback]
|
||||
}
|
||||
|
||||
function getDailyProduce(device: FactoryDevice) {
|
||||
const values = [...(device.weeklyStats?.produce ?? [])]
|
||||
if (device.type === 'cnc' && device.machineData?.todayProduce != null) {
|
||||
const lastIndex = Math.max(values.length - 1, 0)
|
||||
values[lastIndex] = device.machineData.todayProduce
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
function parseAmp(value?: string) {
|
||||
const number = Number.parseFloat(String(value ?? '').replace(/A$/i, ''))
|
||||
return Number.isFinite(number) ? number : undefined
|
||||
}
|
||||
|
||||
function formatTrendTime(value?: string) {
|
||||
if (!value) return undefined
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return value.slice(11, 16) || value
|
||||
return date.toTimeString().slice(0, 5)
|
||||
}
|
||||
|
||||
function FocusMetric({ label, value, unit, warn = false }: { label: string; value: string; unit?: string; warn?: boolean }) {
|
||||
return (
|
||||
<div className={`focus-metric ${warn ? 'warn' : ''}`}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FlipNumber, WaterLevel } from '@dev-screen-starter/visual-kit'
|
||||
import { getDeviceStatus } from '../domain/deviceStatus'
|
||||
import type { CncDevice, FactoryDevice } from '../domain/deviceTypes'
|
||||
import type { FactoryDevice } from '../domain/deviceTypes'
|
||||
|
||||
type StatusSummaryProps = {
|
||||
devices: FactoryDevice[]
|
||||
@@ -24,11 +24,17 @@ export function StatusSummary({ devices, weeklyLabels, weeklyProduce, todayIdx }
|
||||
const availability = devices.length ? Math.round(((devices.length - counts.offline) / devices.length) * 100) : 0
|
||||
const running = devices.length ? Math.round((counts.running / devices.length) * 100) : 0
|
||||
const maxProduce = Math.max(...weeklyProduce, 1)
|
||||
const cncDevices = devices.filter((device): device is CncDevice => device.type === 'cnc' && device.online)
|
||||
const cncTotal = cncDevices
|
||||
.reduce((sum, device) => sum + Number(device.machineData?.currentProduceCount || 0), 0)
|
||||
const todayProduce = cncDevices
|
||||
.reduce((sum, device) => sum + Number(device.weeklyStats?.produce?.[todayIdx] || 0), 0)
|
||||
const productionDevices = devices.filter((device) => (device.type === 'cnc' || device.type === 'laser') && device.online)
|
||||
const cncTotal = productionDevices.reduce((sum, device) => {
|
||||
if (device.type === 'cnc') return sum + Number(device.machineData?.currentProduceCount || 0)
|
||||
if (device.type === 'laser') return sum + Number(device.machineData?.pierceCount || 0)
|
||||
return sum
|
||||
}, 0)
|
||||
const todayProduce = productionDevices
|
||||
.reduce((sum, device) => {
|
||||
if (device.type === 'cnc') return sum + Number(device.machineData?.todayProduce ?? device.weeklyStats?.produce?.[todayIdx] ?? 0)
|
||||
return sum + Number(device.weeklyStats?.produce?.[todayIdx] ?? 0)
|
||||
}, 0)
|
||||
|
||||
return (
|
||||
<div className="status-summary">
|
||||
@@ -47,7 +53,7 @@ export function StatusSummary({ devices, weeklyLabels, weeklyProduce, todayIdx }
|
||||
</div>
|
||||
|
||||
<div className="summary-total">
|
||||
<FlipNumber label="CNC 总产量" value={cncTotal.toLocaleString()} tone="blue" size="sm" />
|
||||
<FlipNumber label="总产能" value={cncTotal.toLocaleString()} tone="blue" size="sm" />
|
||||
<div className="today-produce">今日产量 <strong>{todayProduce.toLocaleString()}</strong> 件</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -12,6 +12,16 @@ export type DeviceStatus = {
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DeviceTrendData = {
|
||||
labels: string[]
|
||||
produce?: number[]
|
||||
runtime?: number[]
|
||||
power?: number[]
|
||||
currentA?: number[]
|
||||
currentB?: number[]
|
||||
currentC?: number[]
|
||||
}
|
||||
|
||||
export type BaseFactoryDevice = {
|
||||
id: string
|
||||
name: string
|
||||
@@ -19,6 +29,7 @@ export type BaseFactoryDevice = {
|
||||
online: boolean
|
||||
offlineReason?: string
|
||||
weeklyStats?: WeeklyStats | null
|
||||
trend?: DeviceTrendData
|
||||
}
|
||||
|
||||
export type LaserMachineData = {
|
||||
@@ -57,7 +68,10 @@ export type CncMachineData = {
|
||||
runtime?: string
|
||||
cuttime?: string
|
||||
cycletime?: string
|
||||
currentForegroundDir?: string
|
||||
currentProduceCount?: number
|
||||
todayProduce?: number
|
||||
cutterNumber?: number
|
||||
programCurrent?: {
|
||||
name?: string
|
||||
number?: number
|
||||
|
||||
@@ -17,6 +17,8 @@ export const factoryDevices: FactoryDevice[] = [
|
||||
pierceCount: 3728,
|
||||
cutLength: 537221.81,
|
||||
moveLength: 7271764.2,
|
||||
workTime: 6.8,
|
||||
laserTime: 4.6,
|
||||
timestamp: '2026-04-06 22:15:00',
|
||||
CutSystemState: {
|
||||
NcState: {
|
||||
@@ -55,6 +57,9 @@ export const factoryDevices: FactoryDevice[] = [
|
||||
cutRate: '35.8%',
|
||||
pierceCount: 4120,
|
||||
cutLength: 680000.2,
|
||||
moveLength: 720820.6,
|
||||
workTime: 4.2,
|
||||
laserTime: 2.9,
|
||||
timestamp: '2026-04-06 22:15:00',
|
||||
CutSystemState: {
|
||||
NcState: {
|
||||
@@ -98,7 +103,9 @@ export const factoryDevices: FactoryDevice[] = [
|
||||
runtime: `${320 + index * 18} H 13 M 25 S`,
|
||||
cuttime: `${2029 + index * 96} H 22 M 15 S`,
|
||||
cycletime: `0 H ${String(12 + index).padStart(2, '0')} M 30 S`,
|
||||
currentForegroundDir: '//CNC_MEM/USER/PATH1/',
|
||||
currentProduceCount: 400 + index * 870,
|
||||
cutterNumber: 4 + (index % 20),
|
||||
programCurrent: { name: `O${2168 + index}`, number: 2168 + index },
|
||||
setFeedRate: 100,
|
||||
setSpindleSpeed: 100,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { ScreenStage, type ScaleMode } from '@dev-screen-starter/screen-core'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { applyDashboardDeviceUpdate, applyDashboardTrendUpdate, connectDashboardSignalR } from '../api/dashboardSignalR'
|
||||
import { AlarmPanel } from '../components/AlarmPanel'
|
||||
import { DeviceListPanel } from '../components/DeviceListPanel'
|
||||
import { FocusDevicePanel } from '../components/FocusDevicePanel'
|
||||
import { HeaderBar } from '../components/HeaderBar'
|
||||
import { StatusSummary } from '../components/StatusSummary'
|
||||
import type { AlarmRow, FactoryDevice } from '../domain/deviceTypes'
|
||||
import { factoryAlarms, factoryDevices } from '../mock/factoryDevices'
|
||||
import { getLast7DaysChartInfo } from '../utils/weekLabels'
|
||||
|
||||
@@ -19,19 +21,66 @@ function readScaleMode(): ScaleMode {
|
||||
return scaleModes.includes(value as ScaleMode) ? (value as ScaleMode) : 'fit'
|
||||
}
|
||||
|
||||
function readDataMode() {
|
||||
if (typeof window === 'undefined') return 'mock'
|
||||
return new URLSearchParams(window.location.search).get('dataMode') ?? import.meta.env.VITE_DATA_MODE ?? 'mock'
|
||||
}
|
||||
|
||||
function readSignalRUrl() {
|
||||
if (typeof window === 'undefined') return 'http://127.0.0.1:5000/dashboardHub'
|
||||
return new URLSearchParams(window.location.search).get('signalRUrl') ?? import.meta.env.VITE_DASHBOARD_SIGNALR_URL ?? 'http://127.0.0.1:5000/dashboardHub'
|
||||
}
|
||||
|
||||
export function DashboardPage() {
|
||||
const scaleMode = readScaleMode()
|
||||
const defaultFocus = factoryDevices.find((device) => device.online && device.type === 'cnc') ?? factoryDevices[0]
|
||||
const [selectedDeviceId, setSelectedDeviceId] = useState(defaultFocus.id)
|
||||
const dataMode = readDataMode()
|
||||
const signalRUrl = readSignalRUrl()
|
||||
const isSignalRMode = dataMode === 'signalr'
|
||||
const [devices, setDevices] = useState(() => (isSignalRMode ? [] : factoryDevices))
|
||||
const [alarms, setAlarms] = useState(() => (isSignalRMode ? [] : factoryAlarms))
|
||||
const [connectionState, setConnectionState] = useState(dataMode === 'signalr' ? '连接中' : 'mock 数据')
|
||||
const defaultFocus = devices.find((device) => device.online && device.type === 'cnc') ?? devices[0]
|
||||
const [selectedDeviceId, setSelectedDeviceId] = useState(defaultFocus?.id ?? '')
|
||||
const selectedDevice = useMemo(
|
||||
() => factoryDevices.find((device) => device.id === selectedDeviceId) ?? defaultFocus,
|
||||
[defaultFocus, selectedDeviceId]
|
||||
() => devices.find((device) => device.id === selectedDeviceId) ?? devices.find((device) => device.name === selectedDeviceId) ?? defaultFocus,
|
||||
[defaultFocus, devices, selectedDeviceId]
|
||||
)
|
||||
const { labels, todayIdx } = getLast7DaysChartInfo()
|
||||
const weeklyProduce = labels.map((_, index) =>
|
||||
factoryDevices.reduce((sum, device) => sum + Number(device.weeklyStats?.produce?.[index] || 0), 0)
|
||||
devices.reduce((sum, device) => sum + Number(device.weeklyStats?.produce?.[index] || 0), 0)
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSignalRMode) {
|
||||
setDevices(factoryDevices)
|
||||
setAlarms(factoryAlarms)
|
||||
setConnectionState('mock 数据')
|
||||
return
|
||||
}
|
||||
|
||||
return connectDashboardSignalR(signalRUrl, {
|
||||
onConnectionState: setConnectionState,
|
||||
onSnapshot: (snapshotDevices, snapshotAlarms) => {
|
||||
setDevices(snapshotDevices.reduce((next, device) => applyDashboardDeviceUpdate(next, device), [] as FactoryDevice[]))
|
||||
setAlarms(snapshotAlarms)
|
||||
},
|
||||
onDeviceUpdated: (device) => {
|
||||
setDevices((current) => applyDashboardDeviceUpdate(current, device))
|
||||
},
|
||||
onAlarmUpdated: (deviceId, nextAlarms) => {
|
||||
setAlarms((current) => mergeDeviceAlarms(current, deviceId, nextAlarms))
|
||||
},
|
||||
onTrendUpdated: (deviceId, points) => {
|
||||
setDevices((current) => applyDashboardTrendUpdate(current, deviceId, points))
|
||||
}
|
||||
})
|
||||
}, [isSignalRMode, signalRUrl])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDevice || !defaultFocus) return
|
||||
setSelectedDeviceId(defaultFocus.id)
|
||||
}, [defaultFocus, selectedDevice])
|
||||
|
||||
return (
|
||||
<ScreenStage background="#020c20" scaleMode={scaleMode} debug>
|
||||
<div className="factory-dashboard">
|
||||
@@ -39,27 +88,54 @@ export function DashboardPage() {
|
||||
|
||||
<main className="factory-main">
|
||||
<aside className="side-panel left-panel">
|
||||
<DeviceListPanel devices={factoryDevices} selectedId={selectedDevice.id} onSelect={setSelectedDeviceId} />
|
||||
<DeviceListPanel devices={devices} selectedId={selectedDevice?.id ?? ''} onSelect={setSelectedDeviceId} />
|
||||
</aside>
|
||||
|
||||
<section className="center-panel">
|
||||
<FocusDevicePanel device={selectedDevice} />
|
||||
{selectedDevice ? <FocusDevicePanel device={selectedDevice} /> : <EmptyFocusPanel connectionState={connectionState} />}
|
||||
</section>
|
||||
|
||||
<aside className="side-panel right-panel">
|
||||
<StatusSummary devices={factoryDevices} weeklyLabels={labels} weeklyProduce={weeklyProduce} todayIdx={todayIdx} />
|
||||
<AlarmPanel alarms={factoryAlarms} />
|
||||
<StatusSummary devices={devices} weeklyLabels={labels} weeklyProduce={weeklyProduce} todayIdx={todayIdx} />
|
||||
<AlarmPanel alarms={alarms} />
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<footer className="factory-footer">
|
||||
<span className="conn-dot pulse" />
|
||||
实时链路:mock 数据
|
||||
实时链路:{dataMode === 'signalr' ? `SignalR ${connectionState}` : connectionState}
|
||||
<span>超时阈值:60s</span>
|
||||
<span>历史数据:mock 同步</span>
|
||||
<span>历史数据:{dataMode === 'signalr' ? '后端推送' : 'mock 同步'}</span>
|
||||
<span>scaleMode={scaleMode}</span>
|
||||
</footer>
|
||||
</div>
|
||||
</ScreenStage>
|
||||
)
|
||||
}
|
||||
|
||||
function mergeDeviceAlarms(current: AlarmRow[], deviceId: string, nextAlarms: AlarmRow[]) {
|
||||
if (!deviceId) return nextAlarms
|
||||
return [...current.filter((alarm) => alarm.device !== deviceId), ...nextAlarms]
|
||||
}
|
||||
|
||||
function EmptyFocusPanel({ connectionState }: { connectionState: string }) {
|
||||
return (
|
||||
<section className="focus-panel status-offline">
|
||||
<header className="focus-header">
|
||||
<div>
|
||||
<span>焦点设备</span>
|
||||
<strong>等待设备数据</strong>
|
||||
</div>
|
||||
</header>
|
||||
<div className="focus-main">
|
||||
<div className="focus-realtime">
|
||||
<div className="focus-task empty">
|
||||
<span>实时链路</span>
|
||||
<strong>{connectionState}</strong>
|
||||
<small>未收到后端设备快照或实时推送</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -622,14 +622,14 @@ button {
|
||||
display: grid;
|
||||
flex: 1;
|
||||
gap: 14px;
|
||||
grid-template-rows: minmax(0, 320px) minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 300px) minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.focus-realtime {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
grid-template-columns: 430px 1fr;
|
||||
grid-template-columns: 410px 1fr;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
@@ -639,7 +639,7 @@ button {
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
grid-template-columns: 190px 1fr;
|
||||
grid-template-columns: 168px 1fr;
|
||||
min-height: 0;
|
||||
padding: 14px;
|
||||
}
|
||||
@@ -656,8 +656,8 @@ button {
|
||||
}
|
||||
|
||||
.focus-hero .vk-water-level-tank {
|
||||
height: 112px;
|
||||
width: 112px;
|
||||
height: 104px;
|
||||
width: 104px;
|
||||
}
|
||||
|
||||
.focus-task {
|
||||
@@ -674,7 +674,7 @@ button {
|
||||
|
||||
.focus-task strong {
|
||||
color: #f0f7ff;
|
||||
font-size: 26px;
|
||||
font-size: 24px;
|
||||
margin: 10px 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -683,14 +683,14 @@ button {
|
||||
|
||||
.focus-task small {
|
||||
color: #04b9ff;
|
||||
font-size: 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.focus-metric-grid {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.focus-metric {
|
||||
@@ -701,7 +701,7 @@ button {
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
padding: 12px 16px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.focus-metric.warn {
|
||||
@@ -710,13 +710,13 @@ button {
|
||||
|
||||
.focus-metric span {
|
||||
color: #8eb8d8;
|
||||
font-size: 14px;
|
||||
margin-bottom: 10px;
|
||||
font-size: 13px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.focus-metric strong {
|
||||
color: #f0f7ff;
|
||||
font-size: 28px;
|
||||
font-size: 24px;
|
||||
line-height: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -729,8 +729,8 @@ button {
|
||||
|
||||
.focus-metric small {
|
||||
color: #8eb8d8;
|
||||
font-size: 16px;
|
||||
margin-left: 6px;
|
||||
font-size: 13px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.focus-trend {
|
||||
|
||||
Reference in new issue
Block a user