Add factory dashboard mock screen

This commit is contained in:
Mac mini git server 2026-05-31 02:20:12 +08:00
parent d7bfde754b
commit 1331d10e31
21 changed files with 2044 additions and 0 deletions

View File

@ -0,0 +1,3 @@
VITE_API_BASE_URL=http://localhost:3000
VITE_WS_URL=ws://localhost:3000/ws/screen
VITE_ENABLE_STAGE_DEBUG=true

View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>工厂设备智能监控平台</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,28 @@
{
"name": "@dev-screen-starter/factory-dashboard",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@dev-screen-starter/charts": "workspace:*",
"@dev-screen-starter/data": "workspace:*",
"@dev-screen-starter/debug": "workspace:*",
"@dev-screen-starter/screen-core": "workspace:*",
"@dev-screen-starter/visual-kit": "workspace:*",
"@vitejs/plugin-react": "^5.0.4",
"echarts": "^6.0.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"vite": "^7.1.7"
},
"devDependencies": {
"@types/react": "^19.1.16",
"@types/react-dom": "^19.1.9",
"typescript": "^5.9.2"
}
}

View File

@ -0,0 +1,5 @@
import { DashboardPage } from './pages/DashboardPage'
export function ProjectScreen() {
return <DashboardPage />
}

View File

@ -0,0 +1,23 @@
import { MarqueeList } from '@dev-screen-starter/visual-kit'
import type { AlarmRow } from '../domain/deviceTypes'
export function AlarmPanel({ alarms }: { alarms: AlarmRow[] }) {
return (
<div className="alarm-panel">
<div className="panel-title">报警信息</div>
{alarms.length ? <span className="alarm-count">{alarms.length} 条报警</span> : <div className="no-alarm">全部设备运行正常</div>}
{alarms.length ? (
<MarqueeList
rows={alarms}
renderRow={(alarm) => (
<div className="alarm-row">
<span>{alarm.time}</span>
<strong>{alarm.device}</strong>
<small>{alarm.message}</small>
</div>
)}
/>
) : null}
</div>
)
}

View File

@ -0,0 +1,42 @@
import { formatFanucTimeShort, getCncWorkModeText, getDeviceStatus, STATUS_COLORS } from '../domain/deviceStatus'
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)
return (
<button className={`device-card cnc-card status-${status.key}`} onClick={onOpen} type="button">
<div className="device-card-head">
<div>
<strong>{device.name}</strong>
<span>{machineData?.sysInfo?.cncType ?? 'CNC'}</span>
</div>
<span className="device-status" style={{ color: STATUS_COLORS[status.key] }}>
<i className={`status-dot ${status.key}`} />
{status.label}
</span>
</div>
{!device.online ? (
<div className="offline-copy">{device.offlineReason ?? '设备离线'}</div>
) : (
<>
<div className="cnc-produce">
<span>累计总产量</span>
<strong>{Number(machineData?.currentProduceCount || 0).toLocaleString()}<small>件</small></strong>
</div>
<div className="cnc-line">
<span>今日 {todayProduce.toLocaleString()} 件</span>
<span>{getCncWorkModeText(machineData?.statusInfo?.WorkMode)}</span>
</div>
<div className="cnc-line muted">
<span>运行</span>
<span>{formatFanucTimeShort(machineData?.runtime)}</span>
</div>
</>
)}
</button>
)
}

View File

@ -0,0 +1,74 @@
import { useMemo, useState } from 'react'
import { getDeviceStatus, STATUS_COLORS } from '../domain/deviceStatus'
import type { DeviceStatusKey, FactoryDevice } from '../domain/deviceTypes'
type DeviceListPanelProps = {
devices: FactoryDevice[]
selectedId: string
onSelect: (deviceId: string) => void
}
type StatusFilter = 'all' | Extract<DeviceStatusKey, 'running' | 'alarm' | 'offline'>
export function DeviceListPanel({ devices, selectedId, onSelect }: DeviceListPanelProps) {
const [keyword, setKeyword] = useState('')
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
const filtered = useMemo(() => {
const normalized = keyword.trim().toLowerCase()
return devices.filter((device) => {
const status = getDeviceStatus(device)
const matchKeyword = !normalized || `${device.name} ${device.id}`.toLowerCase().includes(normalized)
const matchStatus = statusFilter === 'all' || status.key === statusFilter
return matchKeyword && matchStatus
})
}, [devices, keyword, statusFilter])
return (
<div className="device-list-panel">
<div className="panel-title">设备选择</div>
<input
className="device-search"
onChange={(event) => setKeyword(event.target.value)}
placeholder="搜索设备编号"
value={keyword}
/>
<div className="status-filter">
<FilterButton active={statusFilter === 'all'} label="全部" onClick={() => setStatusFilter('all')} />
<FilterButton active={statusFilter === 'running'} label="运行" onClick={() => setStatusFilter('running')} />
<FilterButton active={statusFilter === 'alarm'} label="报警" onClick={() => setStatusFilter('alarm')} />
<FilterButton active={statusFilter === 'offline'} label="离线" onClick={() => setStatusFilter('offline')} />
</div>
<div className="device-list">
{filtered.map((device) => {
const status = getDeviceStatus(device)
return (
<button
className={`device-list-item ${device.id === selectedId ? 'selected' : ''}`}
key={device.id}
onClick={() => onSelect(device.id)}
type="button"
>
<span className="list-status-dot" style={{ background: STATUS_COLORS[status.key] }} />
<strong>{device.name}</strong>
<small>{status.label}</small>
</button>
)
})}
</div>
</div>
)
}
function FilterButton({ active, label, onClick }: { active: boolean; label: string; onClick: () => void }) {
return (
<button className={active ? 'active' : ''} onClick={onClick} type="button">
{label}
</button>
)
}

View File

@ -0,0 +1,161 @@
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 type { FactoryDevice } from '../domain/deviceTypes'
import { getLast7DaysChartInfo } from '../utils/weekLabels'
export function FocusDevicePanel({ device }: { device: FactoryDevice }) {
const status = getDeviceStatus(device)
return (
<section className={`focus-panel status-${status.key}`}>
<header className="focus-header">
<div>
<span>焦点设备</span>
<strong>{device.name}</strong>
</div>
<div className="focus-state" style={{ borderColor: STATUS_COLORS[status.key], color: STATUS_COLORS[status.key] }}>
<i style={{ background: STATUS_COLORS[status.key] }} />
{status.label}
</div>
</header>
<div className="focus-main">
<FocusRealtime device={device} />
<FocusTrend device={device} />
</div>
</section>
)
}
function FocusRealtime({ device }: { device: FactoryDevice }) {
if (device.type === 'laser') {
const nc = device.machineData?.CutSystemState?.NcState
const ds = device.machineData?.CutSystemState?.DeviceState
const progress = nc?.CutPercent ?? 0
return (
<div className="focus-realtime">
<div className="focus-hero">
<WaterLevel label="切割进度" value={progress} tone={progress > 0 ? 'green' : 'blue'} />
<div className="focus-task">
<span>当前图纸</span>
<strong>{nc?.TaskName ?? '无当前图纸'}</strong>
<small>{getLaserSysStateText(nc?.SysState)}</small>
</div>
</div>
<div className="focus-metric-grid">
<FocusMetric label="穿孔次数" value={(device.machineData?.pierceCount ?? 0).toLocaleString()} unit="次" />
<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" />
</div>
</div>
)
}
if (device.type === 'cnc') {
const md = device.machineData
return (
<div className="focus-realtime">
<div className="focus-hero">
<FlipNumber label="今日产量" value={Number(device.weeklyStats?.produce?.[6] || 0).toLocaleString()} unit="件" tone="green" />
<div className="focus-task">
<span>当前程序</span>
<strong>{md?.programCurrent?.name ?? '无程序'}</strong>
<small>运行 {formatFanucTimeShort(md?.runtime)}</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={String(md?.spindleSpeedAndFeedRate?.speed ?? 0)} unit="RPM" />
</div>
</div>
)
}
const phases = [
{ label: 'A相电流', value: device.machineData?.slave1?.current1 ?? '--' },
{ label: 'B相电流', value: device.machineData?.slave1?.current2 ?? '--' },
{ label: 'C相电流', value: device.machineData?.slave1?.current3 ?? '--' }
]
return (
<div className="focus-realtime">
<div className="focus-hero">
<FlipNumber label="估算功率" value={estimatePower(device).toFixed(1)} unit="kVA" tone="amber" />
<div className="focus-task">
<span>实时三相电流</span>
<strong>{device.name}</strong>
<small>{device.machineData?.timestamp ?? '等待数据'}</small>
</div>
</div>
<div className="focus-metric-grid">
{phases.map((phase) => (
<FocusMetric key={phase.label} label={phase.label} value={phase.value} warn={Number.parseFloat(phase.value) > 16} />
))}
</div>
</div>
)
}
function FocusTrend({ device }: { device: FactoryDevice }) {
const labels = device.weeklyStats?.dates ?? getLast7DaysChartInfo().labels
const title = device.type === 'power' ? '最近7天电流趋势' : '最近7天产量与运行趋势'
const option = device.type === 'power'
? createLineOption({
categories: labels,
values: device.powerHistory ?? [],
name: '视在功率',
color: '#d8a13e'
})
: createDualAxisOption({
categories: labels,
leftName: device.type === 'laser' ? '穿孔' : '产量',
rightName: '运行时长',
bar: {
name: device.type === 'laser' ? '穿孔' : '产量',
values: device.weeklyStats?.produce ?? [],
color: '#63a4ff'
},
line: {
name: device.type === 'laser' ? '激光时长' : '运行时长',
values: device.weeklyStats?.cuttime ?? [],
color: '#d8a13e'
}
})
return (
<div className="focus-trend">
<ChartPanel
title={title}
option={option}
extra={<TrendBadge label="今日" value={labels[labels.length - 1] ?? '--'} size="sm" />}
/>
</div>
)
}
function FocusMetric({ label, value, unit, warn = false }: { label: string; value: string; unit?: string; warn?: boolean }) {
return (
<div className={`focus-metric ${warn ? 'warn' : ''}`}>
<span>{label}</span>
<strong>{value}{unit ? <small>{unit}</small> : null}</strong>
</div>
)
}
function estimatePower(device: Extract<FactoryDevice, { type: 'power' }>) {
const currents = [
device.machineData?.slave1?.current1,
device.machineData?.slave1?.current2,
device.machineData?.slave1?.current3
].map((value) => Number.parseFloat(String(value ?? '').replace(/A$/i, '')))
if (!currents.every(Number.isFinite)) return 0
const avg = currents.reduce((sum, value) => sum + value, 0) / currents.length
return (Math.sqrt(3) * 380 * avg) / 1000
}

View File

@ -0,0 +1,32 @@
import { useEffect, useState } from 'react'
function readClock() {
const now = new Date()
return {
date: now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' }),
time: now.toLocaleTimeString('zh-CN', { hour12: false })
}
}
export function HeaderBar() {
const [clock, setClock] = useState(readClock)
useEffect(() => {
const timer = window.setInterval(() => setClock(readClock()), 1000)
return () => window.clearInterval(timer)
}, [])
return (
<header className="factory-header">
<div className="header-line" />
<div className="header-time">
<span>{clock.date}</span>
<strong>{clock.time}</strong>
</div>
<div className="header-title">
<span>工厂设备智能监控平台</span>
</div>
<div className="header-sub">设备实时状态 · React starter edition</div>
</header>
)
}

View File

@ -0,0 +1,58 @@
import { getDeviceStatus, STATUS_COLORS } from '../domain/deviceStatus'
import type { LaserDevice } from '../domain/deviceTypes'
export function LaserCard({ device, onOpen }: { device: LaserDevice; onOpen?: () => void }) {
const status = getDeviceStatus(device)
const nc = device.machineData?.CutSystemState?.NcState
return (
<button className={`device-card laser-card status-${status.key}`} onClick={onOpen} type="button">
<div className="device-card-head">
<div>
<strong>{device.name}</strong>
{device.appName ? <span>{device.appName}</span> : null}
</div>
<StatusBadge color={STATUS_COLORS[status.key]} label={status.label} status={status.key} />
</div>
<div className="laser-stats">
<Stat label="穿孔" value={(device.machineData?.pierceCount ?? 0).toLocaleString()} unit="次" />
<Stat label="切割" value={((device.machineData?.cutLength ?? 0) / 1000).toFixed(1)} unit="m" />
<Stat label="开机率" value={device.machineData?.startRate ?? '--'} />
<Stat label="切割率" value={device.machineData?.cutRate ?? '--'} />
</div>
<div className="device-card-foot">
<span>{nc?.TaskName ?? '无当前图纸'}</span>
{nc?.SysState === 8 ? <Progress value={nc.CutPercent ?? 0} /> : <small>报警 {nc?.AlarmCount ?? 0} 个</small>}
</div>
</button>
)
}
function Stat({ label, value, unit }: { label: string; value: string; unit?: string }) {
return (
<div>
<span>{label}</span>
<strong>{value}{unit ? <small>{unit}</small> : null}</strong>
</div>
)
}
function Progress({ value }: { value: number }) {
return (
<div className="progress-line">
<i style={{ width: `${Math.max(0, Math.min(100, value))}%` }} />
<span>{value.toFixed(1)}%</span>
</div>
)
}
function StatusBadge({ color, label, status }: { color: string; label: string; status: string }) {
return (
<span className="device-status" style={{ color }}>
<i className={`status-dot ${status}`} />
{label}
</span>
)
}

View File

@ -0,0 +1,31 @@
import { getDeviceStatus, STATUS_COLORS } from '../domain/deviceStatus'
import type { PowerDevice } from '../domain/deviceTypes'
export function PowerCard({ device, onOpen }: { device: PowerDevice; onOpen?: () => void }) {
const status = getDeviceStatus(device)
const phases = [
{ label: 'A相', value: device.machineData?.slave1?.current1 ?? '--' },
{ label: 'B相', value: device.machineData?.slave1?.current2 ?? '--' },
{ label: 'C相', value: device.machineData?.slave1?.current3 ?? '--' }
]
return (
<button className={`device-card power-card status-${status.key}`} onClick={onOpen} type="button">
<div className="device-card-head">
<strong>{device.name}</strong>
<span className="device-status" style={{ color: STATUS_COLORS[status.key] }}>
<i className={`status-dot ${status.key}`} />
{status.label}
</span>
</div>
<div className="phase-grid">
{phases.map((phase) => (
<div key={phase.label}>
<span>{phase.label}</span>
<strong className={Number.parseFloat(phase.value) > 16 ? 'warn' : ''}>{phase.value}</strong>
</div>
))}
</div>
</button>
)
}

View File

@ -0,0 +1,77 @@
import { FlipNumber, WaterLevel } from '@dev-screen-starter/visual-kit'
import { getDeviceStatus } from '../domain/deviceStatus'
import type { CncDevice, FactoryDevice } from '../domain/deviceTypes'
type StatusSummaryProps = {
devices: FactoryDevice[]
weeklyLabels: string[]
weeklyProduce: number[]
todayIdx: number
}
export function StatusSummary({ devices, weeklyLabels, weeklyProduce, todayIdx }: StatusSummaryProps) {
const counts = devices.reduce(
(result, device) => {
const status = getDeviceStatus(device)
if (status.key === 'running' || status.key === 'normal') result.running += 1
else if (status.key === 'alarm') result.alarm += 1
else if (status.key === 'offline') result.offline += 1
else result.idle += 1
return result
},
{ running: 0, idle: 0, alarm: 0, offline: 0 }
)
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)
return (
<div className="status-summary">
<div className="panel-title">设备总览</div>
<div className="status-count-grid">
<StatusCount label="运行中" value={counts.running} tone="running" />
<StatusCount label="待机" value={counts.idle} tone="idle" />
<StatusCount label="报警" value={counts.alarm} tone="alarm" />
<StatusCount label="离线" value={counts.offline} tone="offline" />
</div>
<div className="water-pair">
<WaterLevel label="设备可用率" value={availability} tone="green" />
<WaterLevel label="运行率" value={running} tone="blue" />
</div>
<div className="summary-total">
<FlipNumber label="CNC 总产量" value={cncTotal.toLocaleString()} tone="blue" size="sm" />
<div className="today-produce">今日产量 <strong>{todayProduce.toLocaleString()}</strong> 件</div>
</div>
<div className="panel-title compact">近7日产能趋势</div>
<div className="mini-bars">
{weeklyProduce.map((value, index) => (
<div className="mini-bar" key={`${weeklyLabels[index]}-${index}`}>
<span>{value > 1000 ? `${Math.round(value / 100) / 10}k` : value}</span>
<div>
<i className={index === todayIdx ? 'today' : ''} style={{ height: `${Math.max(8, (value / maxProduce) * 90)}%` }} />
</div>
<small>{weeklyLabels[index]}</small>
</div>
))}
</div>
</div>
)
}
function StatusCount({ label, value, tone }: { label: string; value: number; tone: string }) {
return (
<div className={`status-count ${tone}`}>
<strong>{value}</strong>
<span>{label}</span>
</div>
)
}

View File

@ -0,0 +1,96 @@
import type { CncMachineData, DeviceStatus, FactoryDevice, LaserMachineData, PowerMachineData } from './deviceTypes'
const CNC_WORK_MODES: Record<string, string> = {
'0': 'MDI',
'1': 'AUTO',
'2': 'ERR',
'3': 'EDIT',
'4': 'HANDLE',
'5': 'JOG',
'6': 'T-JOG',
'7': 'T-HNDL',
'8': 'INC',
'9': 'REF',
'10': 'REMOTE'
}
const LASER_SYS_STATES: Record<number, string> = {
0: '待机',
1: '模拟',
2: '点动',
3: '回零',
7: '走边框',
8: '加工状态',
9: '暂停',
13: '定位',
21: '单点寻边',
22: '绝对寻边'
}
export const STATUS_COLORS: Record<string, string> = {
running: '#56d08a',
idle: '#d8a13e',
alarm: '#ec646c',
offline: '#66788e',
normal: '#56d08a'
}
export function getCncWorkModeText(mode?: string | number) {
return CNC_WORK_MODES[String(mode ?? '')] || `MODE ${mode ?? '-'}`
}
export function getLaserSysStateText(state?: string | number) {
const n = Number(state)
if (Number.isFinite(n) && LASER_SYS_STATES[n]) {
return LASER_SYS_STATES[n]
}
return `状态 ${state ?? '-'}`
}
export function getCncStatus(machineData?: CncMachineData | null): DeviceStatus {
const statusInfo = machineData?.statusInfo
if (!statusInfo) return { key: 'offline', label: '离线' }
if ((machineData?.alarmStatus ?? 0) > 0 || (statusInfo.Alarm ?? 0) > 0 || (statusInfo.Emergency ?? 0) > 0) {
return { key: 'alarm', label: '报警' }
}
if (statusInfo.RunStatus === '3' && statusInfo.Motion === 1) return { key: 'running', label: '运行中' }
if (statusInfo.RunStatus === '2' || statusInfo.MSTB === 1) return { key: 'running', label: '运行中' }
return { key: 'idle', label: '待机' }
}
export function getLaserStatus(machineData?: LaserMachineData | null): DeviceStatus {
const nc = machineData?.CutSystemState?.NcState
if (!nc) return { key: 'offline', label: '离线' }
const sys = Number(nc.SysState)
if (sys === 8) return { key: 'running', label: getLaserSysStateText(nc.SysState) }
return { key: 'idle', label: getLaserSysStateText(nc.SysState) }
}
export function getPowerStatus(machineData?: PowerMachineData | null): DeviceStatus {
if (!machineData) return { key: 'offline', label: '离线' }
const values = [machineData.slave1?.current1, machineData.slave1?.current2, machineData.slave1?.current3]
if (values.some((value) => value === 'invalid')) return { key: 'alarm', label: '异常' }
return { key: 'normal', label: '正常' }
}
export function getDeviceStatus(device: FactoryDevice): DeviceStatus {
if (!device.online) return { key: 'offline', label: '离线' }
if (device.type === 'cnc') return getCncStatus(device.machineData)
if (device.type === 'laser') return getLaserStatus(device.machineData)
return getPowerStatus(device.machineData)
}
export function parseFanucTime(time?: string) {
if (!time) return { hours: 0, minutes: 0, seconds: 0, totalMinutes: 0 }
const match = time.match(/(\d+)\s*H\s*(\d+)\s*M\s*(\d+)\s*S/)
if (!match) return { hours: 0, minutes: 0, seconds: 0, totalMinutes: 0 }
const hours = Number(match[1])
const minutes = Number(match[2])
const seconds = Number(match[3])
return { hours, minutes, seconds, totalMinutes: hours * 60 + minutes }
}
export function formatFanucTimeShort(time?: string) {
const parsed = parseFanucTime(time)
return `${parsed.hours}H ${parsed.minutes}M`
}

View File

@ -0,0 +1,120 @@
export type DeviceType = 'laser' | 'cnc' | 'power'
export type DeviceStatusKey = 'running' | 'idle' | 'alarm' | 'offline' | 'normal'
export type WeeklyStats = {
dates: string[]
produce: number[]
cuttime?: number[]
}
export type DeviceStatus = {
key: DeviceStatusKey
label: string
}
export type BaseFactoryDevice = {
id: string
name: string
type: DeviceType
online: boolean
offlineReason?: string
weeklyStats?: WeeklyStats | null
}
export type LaserMachineData = {
startRate?: string
cutRate?: string
pierceCount?: number
cutLength?: number
moveLength?: number
workTime?: number
laserTime?: number
timestamp?: string
CutSystemState?: {
NcState?: {
SysState?: number
AlarmCount?: number
AlarmMsg?: string
TaskName?: string
CutPercent?: number
LaserPower?: number
WorkSpeed?: number
FeedRate?: number
}
DeviceState?: {
GasPressure?: number
GasType?: string | number
IsLaserOn?: boolean
IsGasOn?: boolean
}
}
}
export type CncMachineData = {
alarm?: string[]
alarmStatus?: number
boottime?: string
runtime?: string
cuttime?: string
cycletime?: string
currentProduceCount?: number
programCurrent?: {
name?: string
number?: number
}
setFeedRate?: number
setSpindleSpeed?: number
spindleSpeedAndFeedRate?: {
speed?: number
feedRate?: number
}
statusInfo?: {
Alarm?: number
Emergency?: number
Motion?: number
MSTB?: number
RunStatus?: string
WorkMode?: string
}
sysInfo?: {
axes?: number
cncType?: string
mtType?: string
}
timestamp?: string
}
export type PowerMachineData = {
timestamp?: string
slave1?: {
current1?: string
current2?: string
current3?: string
}
}
export type LaserDevice = BaseFactoryDevice & {
type: 'laser'
appName?: string
ip?: string
machineData: LaserMachineData | null
}
export type CncDevice = BaseFactoryDevice & {
type: 'cnc'
machineData: CncMachineData | null
}
export type PowerDevice = BaseFactoryDevice & {
type: 'power'
machineData: PowerMachineData | null
powerHistory?: number[]
}
export type FactoryDevice = LaserDevice | CncDevice | PowerDevice
export type AlarmRow = {
time: string
device: string
message: string
}

View File

@ -0,0 +1,6 @@
import { createRoot } from 'react-dom/client'
import { ProjectScreen } from './ProjectScreen'
import '@dev-screen-starter/visual-kit/styles.css'
import './styles/factory-dashboard.css'
createRoot(document.getElementById('root')!).render(<ProjectScreen />)

View File

@ -0,0 +1,146 @@
import type { AlarmRow, FactoryDevice } from '../domain/deviceTypes'
import { getLast7DaysChartInfo } from '../utils/weekLabels'
const { labels } = getLast7DaysChartInfo()
export const factoryDevices: FactoryDevice[] = [
{
id: 'laser:192.168.1.101:HypCut',
name: '激光 #1',
type: 'laser',
online: true,
appName: 'HypCut',
ip: '192.168.1.101',
machineData: {
startRate: '83.4%',
cutRate: '42.1%',
pierceCount: 3728,
cutLength: 537221.81,
moveLength: 7271764.2,
timestamp: '2026-04-06 22:15:00',
CutSystemState: {
NcState: {
SysState: 8,
AlarmCount: 0,
AlarmMsg: '',
TaskName: '20180814001.lxds',
CutPercent: 62.5,
LaserPower: 3000,
WorkSpeed: 500,
FeedRate: 100
},
DeviceState: {
GasPressure: 4.5,
GasType: 'Oxygen',
IsLaserOn: true,
IsGasOn: true
}
}
},
weeklyStats: {
dates: labels,
produce: [3500, 3600, 3728, 3800, 3650, 3890, 4020],
cuttime: [0.4, 0.45, 0.48, 0.5, 0.47, 0.55, 0.58]
}
},
{
id: 'laser:192.168.1.102:TubePro',
name: '激光 #2',
type: 'laser',
online: true,
appName: 'TubePro',
ip: '192.168.1.102',
machineData: {
startRate: '76.2%',
cutRate: '35.8%',
pierceCount: 4120,
cutLength: 680000.2,
timestamp: '2026-04-06 22:15:00',
CutSystemState: {
NcState: {
SysState: 0,
AlarmCount: 1,
AlarmMsg: '气压不足',
TaskName: '20201010002.lxds',
CutPercent: 0,
LaserPower: 2000
},
DeviceState: {
GasPressure: 0.8,
GasType: 'Nitrogen',
IsLaserOn: false,
IsGasOn: false
}
}
},
weeklyStats: {
dates: labels,
produce: [4100, 4200, 4000, 4300, 4150, 4220, 4380],
cuttime: [0.55, 0.6, 0.5, 0.65, 0.52, 0.58, 0.62]
}
},
...Array.from({ length: 13 }, (_, index) => {
const id = index + 1
const running = [0, 4, 7].includes(index)
const offline = [8, 10].includes(index)
return {
id: `B-${String(id).padStart(3, '0')}`,
name: `CNC-${String(id).padStart(3, '0')}`,
type: 'cnc' as const,
online: !offline,
offlineReason: offline ? '等待 MQTT 首条数据' : undefined,
machineData: offline
? null
: {
alarm: index === 5 ? ['主轴冷却液不足'] : [],
alarmStatus: index === 5 ? 1 : 0,
boottime: `${5400 + index * 320} H 40 M 0 S`,
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`,
currentProduceCount: 400 + index * 870,
programCurrent: { name: `O${2168 + index}`, number: 2168 + index },
setFeedRate: 100,
setSpindleSpeed: 100,
spindleSpeedAndFeedRate: { feedRate: running ? 500 : 0, speed: running ? 1200 : 0 },
statusInfo: {
Alarm: index === 5 ? 1 : 0,
Emergency: 0,
Motion: running ? 1 : 0,
MSTB: running ? 1 : 0,
RunStatus: running ? '3' : '0',
WorkMode: running ? '1' : '5'
},
sysInfo: { axes: index > 7 ? 4 : 3, cncType: index > 3 ? 'Series 0i-MF' : 'Series 0i-MD', mtType: 'Machining center' },
timestamp: '2026-04-06 22:15:00'
},
weeklyStats: {
dates: labels,
produce: [80 + index * 8, 92 + index * 9, 76 + index * 10, 110 + index * 7, 128 + index * 8, 118 + index * 9, 136 + index * 10],
cuttime: [7, 7.5, 8, 7.8, 8, 8.4, 8.9]
}
}
}),
{
id: 'C-001',
name: '配电柜 #1',
type: 'power',
online: true,
machineData: { timestamp: '2026-04-06 22:15:00', slave1: { current1: '12.4A', current2: '13.1A', current3: '12.8A' } },
powerHistory: [8.2, 8.5, 8.4, 8.9, 9.2, 9.1, 8.8]
},
{
id: 'C-002',
name: '配电柜 #2',
type: 'power',
online: true,
machineData: { timestamp: '2026-04-06 22:15:00', slave1: { current1: '16.8A', current2: '15.4A', current3: '16.1A' } },
powerHistory: [10.2, 10.5, 10.9, 11.4, 11.8, 11.6, 11.2]
}
]
export const factoryAlarms: AlarmRow[] = [
{ time: '18:20', device: '激光 #2', message: '气压不足' },
{ time: '18:12', device: 'CNC-006', message: '主轴冷却液不足' },
{ time: '17:48', device: '配电柜 #2', message: 'B 相电流偏高' }
]

View File

@ -0,0 +1,65 @@
import { ScreenStage, type ScaleMode } from '@dev-screen-starter/screen-core'
import { useMemo, useState } from 'react'
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 { factoryAlarms, factoryDevices } from '../mock/factoryDevices'
import { getLast7DaysChartInfo } from '../utils/weekLabels'
const scaleModes: ScaleMode[] = ['fit', 'fill', 'stretch', 'none']
function readScaleMode(): ScaleMode {
if (typeof window === 'undefined') {
return 'fit'
}
const value = new URLSearchParams(window.location.search).get('scaleMode')
return scaleModes.includes(value as ScaleMode) ? (value as ScaleMode) : 'fit'
}
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 selectedDevice = useMemo(
() => factoryDevices.find((device) => device.id === selectedDeviceId) ?? defaultFocus,
[defaultFocus, selectedDeviceId]
)
const { labels, todayIdx } = getLast7DaysChartInfo()
const weeklyProduce = labels.map((_, index) =>
factoryDevices.reduce((sum, device) => sum + Number(device.weeklyStats?.produce?.[index] || 0), 0)
)
return (
<ScreenStage background="#020c20" scaleMode={scaleMode} debug>
<div className="factory-dashboard">
<HeaderBar />
<main className="factory-main">
<aside className="side-panel left-panel">
<DeviceListPanel devices={factoryDevices} selectedId={selectedDevice.id} onSelect={setSelectedDeviceId} />
</aside>
<section className="center-panel">
<FocusDevicePanel device={selectedDevice} />
</section>
<aside className="side-panel right-panel">
<StatusSummary devices={factoryDevices} weeklyLabels={labels} weeklyProduce={weeklyProduce} todayIdx={todayIdx} />
<AlarmPanel alarms={factoryAlarms} />
</aside>
</main>
<footer className="factory-footer">
<span className="conn-dot pulse" />
实时链路:mock 数据
<span>超时阈值:60s</span>
<span>历史数据:mock 同步</span>
<span>scaleMode={scaleMode}</span>
</footer>
</div>
</ScreenStage>
)
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
export function getLast7DaysChartInfo() {
const today = new Date()
const labels: string[] = []
for (let index = 6; index >= 0; index -= 1) {
const date = new Date(today)
date.setDate(today.getDate() - index)
labels.push(`${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`)
}
return { labels, todayIdx: 6 }
}

View File

@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx",
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}

View File

@ -0,0 +1,6 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [react()]
})