add a
This commit is contained in:
parent
bc93fb4d61
commit
89fe9988fc
13
.env.example
13
.env.example
@ -18,7 +18,18 @@ VITE_MQTT_WS_URL=ws://127.0.0.1:9001/mqtt
|
||||
# 额外订阅通配(可选,与上面设备列表配合;消息仍需能匹配到已配置设备)
|
||||
# VITE_MQTT_EXTRA_SUBSCRIBE=topic/device/+/data
|
||||
|
||||
VITE_MQTT_OFFLINE_MS=30000
|
||||
VITE_MQTT_OFFLINE_MS=60000
|
||||
# VITE_MQTT_DEBUG=true
|
||||
# VITE_MQTT_USERNAME=
|
||||
# VITE_MQTT_PASSWORD=
|
||||
|
||||
# ---------- 柏楚激光魔盒(A 类 HTTP 采集,与 MQTT 并行;设 URL 后自动轮询)----------
|
||||
# 示例:http://192.168.1.188:8080
|
||||
VITE_LASER_BOX_URL=http://192.168.1.188:8080
|
||||
# 若魔盒开启鉴权,填写 token / secret(签名:MD5("timestamp="+ts+"&token="+token+"&secret="+secret))
|
||||
# VITE_LASER_BOX_TOKEN=
|
||||
# VITE_LASER_BOX_SECRET=
|
||||
# VITE_LASER_BOX_POLL_MS=30000
|
||||
# VITE_LASER_BOX_TIMEOUT_MS=20000
|
||||
# 生产/预览环境需要看控制台请求日志时打开(dev 默认会打)
|
||||
# VITE_LASER_BOX_DEBUG=true
|
||||
|
||||
BIN
dist (2).zip
Normal file
BIN
dist (2).zip
Normal file
Binary file not shown.
36
package-lock.json
generated
36
package-lock.json
generated
@ -11,6 +11,7 @@
|
||||
"@kjgl77/datav-vue3": "^1.7.4",
|
||||
"axios": "^1.13.6",
|
||||
"echarts": "^6.0.0",
|
||||
"md5": "^2.3.0",
|
||||
"mqtt": "^5.15.1",
|
||||
"vue": "^3.5.25",
|
||||
"vue-echarts": "^8.0.1",
|
||||
@ -1312,6 +1313,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/charenc": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
|
||||
"integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
@ -1359,6 +1369,15 @@
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/crypt": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
|
||||
"integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
|
||||
@ -1764,6 +1783,12 @@
|
||||
"node": ">= 12"
|
||||
}
|
||||
},
|
||||
"node_modules/is-buffer": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
|
||||
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-sdsl": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz",
|
||||
@ -1798,6 +1823,17 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/md5": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",
|
||||
"integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"charenc": "0.0.2",
|
||||
"crypt": "0.0.2",
|
||||
"is-buffer": "~1.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz",
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
"@kjgl77/datav-vue3": "^1.7.4",
|
||||
"axios": "^1.13.6",
|
||||
"echarts": "^6.0.0",
|
||||
"md5": "^2.3.0",
|
||||
"mqtt": "^5.15.1",
|
||||
"vue": "^3.5.25",
|
||||
"vue-echarts": "^8.0.1",
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
import { startMqttDeviceRealtime, stopMqttDeviceRealtime } from './services/mqttDeviceStore.js'
|
||||
import { startLaserBoxSync, stopLaserBoxSync } from './services/laserBoxSync.js'
|
||||
|
||||
const DESIGN_W = 1920
|
||||
const DESIGN_H = 1080
|
||||
@ -24,11 +25,13 @@ onMounted(() => {
|
||||
applyScale()
|
||||
window.addEventListener('resize', applyScale)
|
||||
startMqttDeviceRealtime()
|
||||
startLaserBoxSync()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', applyScale)
|
||||
stopMqttDeviceRealtime()
|
||||
stopLaserBoxSync()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@ -47,10 +47,10 @@
|
||||
<dv-digital-flop class="digital-flop" :config="flopConfig" />
|
||||
</div>
|
||||
|
||||
<!-- 本周趋势 -->
|
||||
<!-- 横轴为「近 7 日(含今天)」,由 Dashboard 传入 getLast7DaysChartInfo().labels -->
|
||||
<div class="panel-title mt12">
|
||||
<dv-decoration-3 class="deco" />
|
||||
<span>本周产能趋势</span>
|
||||
<span>近7日产能趋势</span>
|
||||
<dv-decoration-3 class="deco flip" />
|
||||
</div>
|
||||
<div class="bar-chart" v-if="weeklyProduce.length">
|
||||
|
||||
104
src/services/laserBoxClient.js
Normal file
104
src/services/laserBoxClient.js
Normal file
@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 柏楚激光魔盒 HTTP 客户端(见仓库 `设备信息示例(包含ABC类).md` · A 类)
|
||||
*
|
||||
* - **鉴权**:若配置 `VITE_LASER_BOX_TOKEN` + `VITE_LASER_BOX_SECRET`,请求头带
|
||||
* `token`、`timestamp`、`sign`,其中 `sign = MD5("timestamp="+ts+"&token="+token+"&secret="+secret)`。
|
||||
* - **日统计** `statistic/daily/*`:`startDate` / `endDate` 为 `yyyy-MM-dd`(闭区间),
|
||||
* 与前端 `getLast7DaysStatContext` 的 `startYmd` / `endYmd` 一致。
|
||||
* - **报警** `alarm/v2`:`startDate` / `endDate` 为 `yyyy-MM-dd HH:mm:ss`。
|
||||
* - **控制台日志**:`npm run dev` 下会打印每次 GET;生产构建可加 `VITE_LASER_BOX_DEBUG=true`。
|
||||
*/
|
||||
import axios from 'axios'
|
||||
import md5 from 'md5'
|
||||
|
||||
/**
|
||||
* 是否在控制台打印 A 类魔盒 HTTP 请求。
|
||||
* - 开发模式 `npm run dev` 下默认开启;
|
||||
* - 生产预览可设 `VITE_LASER_BOX_DEBUG=true`。
|
||||
*/
|
||||
export function isLaserBoxHttpLog() {
|
||||
if (import.meta.env.DEV) return true
|
||||
return String(import.meta.env.VITE_LASER_BOX_DEBUG || '').toLowerCase() === 'true'
|
||||
}
|
||||
|
||||
function buildAuthHeaders() {
|
||||
const token = (import.meta.env.VITE_LASER_BOX_TOKEN ?? '').trim()
|
||||
const secret = (import.meta.env.VITE_LASER_BOX_SECRET ?? '').trim()
|
||||
if (!token || !secret) return {}
|
||||
const timestamp = Date.now()
|
||||
const sign = md5(`timestamp=${timestamp}&token=${token}&secret=${secret}`)
|
||||
return {
|
||||
token,
|
||||
timestamp: String(timestamp),
|
||||
sign
|
||||
}
|
||||
}
|
||||
|
||||
async function getJson(baseUrl, path, params = {}) {
|
||||
const url = `${String(baseUrl).replace(/\/+$/, '')}${path}`
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.log('[LaserBox] GET', path, params && Object.keys(params).length ? params : '')
|
||||
}
|
||||
let data
|
||||
try {
|
||||
const res = await axios.get(url, {
|
||||
params,
|
||||
headers: { ...buildAuthHeaders() },
|
||||
timeout: Number(import.meta.env.VITE_LASER_BOX_TIMEOUT_MS || 20000)
|
||||
})
|
||||
data = res.data
|
||||
} catch (e) {
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.warn('[LaserBox] 请求失败', path, e?.response?.status, e?.message || e)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
if (data && typeof data.status === 'number' && data.status !== 0) {
|
||||
if (isLaserBoxHttpLog()) console.warn('[LaserBox] 业务 status≠0', path, data)
|
||||
throw new Error(data.msg || `魔盒接口错误 status=${data.status}`)
|
||||
}
|
||||
return data?.data
|
||||
}
|
||||
|
||||
/** 机床列表 → 一般为数组;兼容 { list: [] } */
|
||||
export async function fetchMachineList(baseUrl) {
|
||||
const raw = await getJson(baseUrl, '/api/datacenter/list')
|
||||
if (Array.isArray(raw)) return raw
|
||||
if (Array.isArray(raw?.list)) return raw.list
|
||||
if (Array.isArray(raw?.data)) return raw.data
|
||||
return []
|
||||
}
|
||||
|
||||
export async function fetchCutSystemState(baseUrl, ip, appName) {
|
||||
return getJson(baseUrl, '/api/monitor/cutSystemState', { ip, appName })
|
||||
}
|
||||
|
||||
/** 报警(含历史) */
|
||||
export async function fetchAlarms(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/machine/alarm/v2', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
export async function fetchSummary(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/summary', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
/** 日切割长度 + 空移长度等;`startDate`/`endDate`:`yyyy-MM-dd` */
|
||||
export async function fetchDailyLength(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/daily/length', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
export async function fetchDailyPierce(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/daily/pierceCount', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
export async function fetchDailyLaser(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/daily/laser', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
export async function fetchDailyGas(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/daily/gasTime', { ip, appName, startDate, endDate })
|
||||
}
|
||||
|
||||
export async function fetchDailyRunTime(baseUrl, ip, appName, startDate, endDate) {
|
||||
return getJson(baseUrl, '/api/statistic/daily/runTime', { ip, appName, startDate, endDate })
|
||||
}
|
||||
251
src/services/laserBoxSync.js
Normal file
251
src/services/laserBoxSync.js
Normal file
@ -0,0 +1,251 @@
|
||||
/**
|
||||
* A 类(激光)魔盒轮询同步:设备列表 → 按机床 ip + 切割软件 appName 拉状态 / 报警 / 统计。
|
||||
*
|
||||
* - **仅 HTTP**:与 MQTT 无关;看板在 `VITE_LASER_BOX_URL` 已配置时应只展示本模块 `devices`。
|
||||
* - **近 7 日**:日统计与柱图对齐「今天往前 7 天(含今天)」,见 `getLast7DaysStatContext`。
|
||||
*/
|
||||
import { reactive } from 'vue'
|
||||
import {
|
||||
fetchMachineList,
|
||||
fetchCutSystemState,
|
||||
fetchAlarms,
|
||||
fetchSummary,
|
||||
fetchDailyLength,
|
||||
fetchDailyPierce,
|
||||
fetchDailyLaser,
|
||||
fetchDailyGas,
|
||||
fetchDailyRunTime,
|
||||
isLaserBoxHttpLog
|
||||
} from './laserBoxClient.js'
|
||||
import { getLast7DaysStatContext } from '../utils/weekLabels.js'
|
||||
|
||||
export const laserBoxRuntime = reactive({
|
||||
devices: [],
|
||||
lastSyncAt: '',
|
||||
error: null,
|
||||
syncing: false,
|
||||
enabled: false
|
||||
})
|
||||
|
||||
let timer = null
|
||||
|
||||
export function laserRouteId(ip, appName) {
|
||||
return `laser:${ip}:${appName}`
|
||||
}
|
||||
|
||||
function pickCuttingAppName(appInfos) {
|
||||
if (!Array.isArray(appInfos) || appInfos.length === 0) return ''
|
||||
const skip = (n) => /datacenter/i.test(String(n || ''))
|
||||
const preferred = appInfos.find((a) => !skip(a?.appName))
|
||||
return preferred?.appName || appInfos[0]?.appName || ''
|
||||
}
|
||||
|
||||
/** 将魔盒 CutState 粗映射到 NcState.SysState,供 getLaserStatus / 详情页展示 */
|
||||
function mapCutStateToSysState(cutState) {
|
||||
const s = String(cutState ?? '').toLowerCase()
|
||||
if (s.includes('pause') || s.includes('暂停')) return 9
|
||||
if (s.includes('run') || s.includes('加工') || s.includes('切割')) return 8
|
||||
return 0
|
||||
}
|
||||
|
||||
function buildCutSystemState(cut, alarmList) {
|
||||
const rawNc = cut?.NcState ?? cut?.ncState
|
||||
const rawDev = cut?.DeviceState ?? cut?.deviceState
|
||||
const nc = typeof rawNc === 'object' && rawNc ? { ...rawNc } : {}
|
||||
const ds = typeof rawDev === 'object' && rawDev ? { ...rawDev } : {}
|
||||
if (cut && nc.SysState == null && cut.CutState != null) nc.SysState = mapCutStateToSysState(cut.CutState)
|
||||
|
||||
const list = Array.isArray(alarmList) ? alarmList : []
|
||||
const unresolved = list.filter((a) => !(a?.ClearTime || a?.clearTime) && a?.IsCleared !== true && a?.isCleared !== true)
|
||||
const useAlarms = unresolved.length ? unresolved : list
|
||||
if ((nc.AlarmCount == null || Number(nc.AlarmCount) === 0) && useAlarms.length) nc.AlarmCount = useAlarms.length
|
||||
const msgs = useAlarms
|
||||
.slice(0, 5)
|
||||
.map((a) => a?.AlarmDesc || a?.alarmDesc || a?.message || a?.msg || '')
|
||||
.filter(Boolean)
|
||||
if (msgs.length) nc.AlarmMsg = msgs.join(';')
|
||||
|
||||
return { NcState: nc, DeviceState: ds }
|
||||
}
|
||||
|
||||
function buildWeeklyBars(statInts, rowsByStatInt, key) {
|
||||
return statInts.map((si) => {
|
||||
const row = rowsByStatInt.get(si)
|
||||
const v = row?.[key]
|
||||
return typeof v === 'number' && !Number.isNaN(v) ? v : 0
|
||||
})
|
||||
}
|
||||
|
||||
function indexDailyRows(rows, keyStatDate = 'statDate') {
|
||||
const m = new Map()
|
||||
if (!Array.isArray(rows)) return m
|
||||
for (const r of rows) {
|
||||
const k = r?.[keyStatDate]
|
||||
if (k != null) m.set(Number(k), r)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
async function fetchOneMachine(baseUrl, ip, appName) {
|
||||
const win = getLast7DaysStatContext()
|
||||
const alarmStart = `${win.startYmd} 00:00:00`
|
||||
const alarmEnd = `${win.endYmd} 23:59:59`
|
||||
|
||||
const [
|
||||
cutRes,
|
||||
alarmRes,
|
||||
summaryRes,
|
||||
lenRes,
|
||||
pierceRes,
|
||||
laserRes,
|
||||
gasRes,
|
||||
runRes
|
||||
] = await Promise.allSettled([
|
||||
fetchCutSystemState(baseUrl, ip, appName),
|
||||
fetchAlarms(baseUrl, ip, appName, alarmStart, alarmEnd),
|
||||
fetchSummary(baseUrl, ip, appName, win.summaryStart, win.summaryEnd),
|
||||
fetchDailyLength(baseUrl, ip, appName, win.startYmd, win.endYmd),
|
||||
fetchDailyPierce(baseUrl, ip, appName, win.startYmd, win.endYmd),
|
||||
fetchDailyLaser(baseUrl, ip, appName, win.startYmd, win.endYmd),
|
||||
fetchDailyGas(baseUrl, ip, appName, win.startYmd, win.endYmd),
|
||||
fetchDailyRunTime(baseUrl, ip, appName, win.startYmd, win.endYmd)
|
||||
])
|
||||
|
||||
const cut = cutRes.status === 'fulfilled' ? cutRes.value : null
|
||||
const alarmsRaw = alarmRes.status === 'fulfilled' ? alarmRes.value : []
|
||||
const summary = summaryRes.status === 'fulfilled' ? summaryRes.value : null
|
||||
|
||||
const lenRows = lenRes.status === 'fulfilled' ? lenRes.value : []
|
||||
const pierceRows = pierceRes.status === 'fulfilled' ? pierceRes.value : []
|
||||
const laserRows = laserRes.status === 'fulfilled' ? laserRes.value : []
|
||||
const gasRows = gasRes.status === 'fulfilled' ? gasRes.value : []
|
||||
const runRows = runRes.status === 'fulfilled' ? runRes.value : []
|
||||
|
||||
const statInts = win.statInts
|
||||
const lenM = indexDailyRows(lenRows)
|
||||
const pierceM = indexDailyRows(pierceRows)
|
||||
const laserM = indexDailyRows(laserRows)
|
||||
const gasM = indexDailyRows(gasRows)
|
||||
const runM = indexDailyRows(runRows)
|
||||
|
||||
const cutLength = buildWeeklyBars(statInts, lenM, 'cutLength')
|
||||
const moveLength = buildWeeklyBars(statInts, lenM, 'moveLength')
|
||||
const pierceDaily = buildWeeklyBars(statInts, pierceM, 'pierceCount')
|
||||
const laserTimeDaily = buildWeeklyBars(statInts, laserM, 'laserTime')
|
||||
const gasTimeDaily = buildWeeklyBars(statInts, gasM, 'gasTime')
|
||||
const runTimeDaily = buildWeeklyBars(statInts, runM, 'runTime')
|
||||
|
||||
const cutTimeHours = laserTimeDaily.map((s) => Math.round((s / 3600) * 10) / 10)
|
||||
|
||||
const alarmList = Array.isArray(alarmsRaw) ? alarmsRaw : []
|
||||
const { labels } = win
|
||||
const cutSystemState = buildCutSystemState(cut || {}, alarmList)
|
||||
|
||||
const id = laserRouteId(ip, appName)
|
||||
const ts = new Date().toLocaleString('zh-CN', { hour12: false })
|
||||
const machineData = {
|
||||
...(summary && typeof summary === 'object' ? summary : {}),
|
||||
timestamp: ts,
|
||||
CutSystemState: cutSystemState,
|
||||
CutState: cut?.CutState,
|
||||
CutStateDesc: cut?.CutStateDesc
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name: `${ip}`,
|
||||
type: 'laser',
|
||||
online: cutRes.status === 'fulfilled',
|
||||
appName,
|
||||
ip,
|
||||
machineData,
|
||||
weeklyStats: {
|
||||
dates: labels,
|
||||
produce: pierceDaily,
|
||||
cuttime: cutTimeHours,
|
||||
cutLength,
|
||||
moveLength,
|
||||
pierceDaily,
|
||||
laserTimeDaily,
|
||||
gasTimeDaily,
|
||||
runTimeDaily
|
||||
},
|
||||
_laser: { ip, appName, alarms: alarmList }
|
||||
}
|
||||
}
|
||||
|
||||
async function syncOnce(baseUrl) {
|
||||
laserBoxRuntime.syncing = true
|
||||
laserBoxRuntime.error = null
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.info('[LaserBox] 开始同步', baseUrl)
|
||||
}
|
||||
try {
|
||||
const list = await fetchMachineList(baseUrl)
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.info('[LaserBox] 机床列表', list.length, '条')
|
||||
}
|
||||
const tasks = []
|
||||
for (const row of list) {
|
||||
const ip = row?.serverIP || row?.serverIp || row?.ip
|
||||
if (!ip) continue
|
||||
const appName = pickCuttingAppName(row?.appInfos)
|
||||
if (!appName) continue
|
||||
tasks.push(fetchOneMachine(baseUrl, ip, appName))
|
||||
}
|
||||
const settled = await Promise.allSettled(tasks)
|
||||
const devices = []
|
||||
for (const r of settled) {
|
||||
if (r.status === 'fulfilled' && r.value) devices.push(r.value)
|
||||
}
|
||||
laserBoxRuntime.devices = devices
|
||||
laserBoxRuntime.lastSyncAt = new Date().toLocaleString()
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.info('[LaserBox] 同步完成', devices.length, '台', laserBoxRuntime.lastSyncAt)
|
||||
}
|
||||
} catch (e) {
|
||||
laserBoxRuntime.error = e?.message || String(e)
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.warn('[LaserBox] 同步异常', laserBoxRuntime.error)
|
||||
}
|
||||
} finally {
|
||||
laserBoxRuntime.syncing = false
|
||||
}
|
||||
}
|
||||
|
||||
export function startLaserBoxSync() {
|
||||
const baseUrl = (import.meta.env.VITE_LASER_BOX_URL ?? '').trim()
|
||||
if (!baseUrl) {
|
||||
laserBoxRuntime.enabled = false
|
||||
if (import.meta.env.DEV) {
|
||||
console.info(
|
||||
'[LaserBox] 未设置 VITE_LASER_BOX_URL,不会请求 A 类接口。在项目根目录 .env 增加一行,例如:VITE_LASER_BOX_URL=http://192.168.1.188:8080'
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
laserBoxRuntime.enabled = true
|
||||
const interval = Math.max(5000, Number(import.meta.env.VITE_LASER_BOX_POLL_MS || 30000))
|
||||
if (timer) clearInterval(timer)
|
||||
if (isLaserBoxHttpLog()) {
|
||||
console.info('[LaserBox] 轮询已启动', baseUrl, `间隔 ${interval}ms`)
|
||||
}
|
||||
syncOnce(baseUrl)
|
||||
timer = setInterval(() => syncOnce(baseUrl), interval)
|
||||
}
|
||||
|
||||
export function stopLaserBoxSync() {
|
||||
if (timer) clearInterval(timer)
|
||||
timer = null
|
||||
laserBoxRuntime.enabled = false
|
||||
}
|
||||
|
||||
export function findLaserDeviceByRouteParam(routeParam) {
|
||||
const p = String(routeParam || '')
|
||||
if (!p) return null
|
||||
let decoded = p
|
||||
try {
|
||||
decoded = decodeURIComponent(p)
|
||||
} catch { /* ignore */ }
|
||||
return laserBoxRuntime.devices.find((d) => d.id === p || d.id === decoded) || null
|
||||
}
|
||||
@ -7,6 +7,7 @@
|
||||
* - VITE_MQTT_TOPICS 中直接写完整路径(含 /)则原样订阅,如 topic/device/rbiot-c01-001/data
|
||||
* - 类型/展示名:从路径中识别 rbiot-a|b|c 段(避免末段为 data 时误判)
|
||||
* - 与 MQTTX 一致:同时订阅「有/无」前导 /
|
||||
* - A 类若以魔盒 HTTP 采集为主,可不在 VITE_MQTT_TOPICS 中配置 rbiot-a;配置 VITE_LASER_BOX_URL 后看板不再用 MQTT 激光。
|
||||
*/
|
||||
import { reactive } from 'vue'
|
||||
import mqtt from 'mqtt'
|
||||
|
||||
@ -1,3 +1,12 @@
|
||||
/**
|
||||
* 日期区间工具(看板 / 魔盒日统计)
|
||||
*
|
||||
* - **自然周** `getWeeklyInfo` / `getWeekStatContext`:周一 00:00 至周日,横轴「本周」;
|
||||
* 若 MQTT 上游仍按自然周传 `weeklyStats.produce`,索引 0 表示周一。
|
||||
* - **滚动近 7 日** `getLast7DaysStatContext` / `getLast7DaysChartInfo`:从「今天往前共 7 天」
|
||||
* (含今天),横轴从左到右为从旧到新;与魔盒 `statistic/daily` 的 `statDate`(yyyymmdd)对齐。
|
||||
*/
|
||||
|
||||
/** 生成本周日期标签(周一至周日),用于趋势图横轴 */
|
||||
export function getWeeklyInfo() {
|
||||
const today = new Date()
|
||||
@ -12,3 +21,87 @@ export function getWeeklyInfo() {
|
||||
}
|
||||
return { labels, todayIdx }
|
||||
}
|
||||
|
||||
function pad2(n) {
|
||||
return String(n).padStart(2, '0')
|
||||
}
|
||||
|
||||
/** yyyy-MM-dd */
|
||||
export function formatYmd(d) {
|
||||
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
|
||||
}
|
||||
|
||||
/** yyyy-MM-dd HH:mm:ss */
|
||||
export function formatYmdHms(d) {
|
||||
return `${formatYmd(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 本周一~周日与魔盒 statistic/daily 的 statDate(整数 yyyymmdd)对齐。
|
||||
* 仅当业务仍按「自然周」拉日统计时使用;A 类魔盒采集请改用 `getLast7DaysStatContext`。
|
||||
*/
|
||||
export function getWeekStatContext() {
|
||||
const today = new Date()
|
||||
const todayIdx = (today.getDay() + 6) % 7
|
||||
const monday = new Date(today)
|
||||
monday.setDate(today.getDate() - todayIdx)
|
||||
monday.setHours(0, 0, 0, 0)
|
||||
const sunday = new Date(monday)
|
||||
sunday.setDate(monday.getDate() + 6)
|
||||
const statInts = []
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const d = new Date(monday)
|
||||
d.setDate(monday.getDate() + i)
|
||||
statInts.push(d.getFullYear() * 10000 + (d.getMonth() + 1) * 100 + d.getDate())
|
||||
}
|
||||
return {
|
||||
monday,
|
||||
sunday,
|
||||
startYmd: formatYmd(monday),
|
||||
endYmd: formatYmd(sunday),
|
||||
statInts,
|
||||
summaryStart: `${formatYmd(monday)} 00:00:00`,
|
||||
summaryEnd: formatYmdHms(new Date())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 最近 7 天(含今天):`startYmd` = 今天−6 天,`endYmd` = 今天。
|
||||
* `statInts` / `labels` 下标 0…6 对应从旧到新,最后一格为「今天」。
|
||||
*
|
||||
* @param {Date} [now] 参考时刻,默认 `new Date()`;取日期部分以本地时区为准。
|
||||
*/
|
||||
export function getLast7DaysStatContext(now = new Date()) {
|
||||
const end = new Date(now)
|
||||
end.setHours(0, 0, 0, 0)
|
||||
const start = new Date(end)
|
||||
start.setDate(end.getDate() - 6)
|
||||
|
||||
const statInts = []
|
||||
const labels = []
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const d = new Date(start)
|
||||
d.setDate(start.getDate() + i)
|
||||
statInts.push(d.getFullYear() * 10000 + (d.getMonth() + 1) * 100 + d.getDate())
|
||||
labels.push(`${pad2(d.getMonth() + 1)}/${pad2(d.getDate())}`)
|
||||
}
|
||||
|
||||
return {
|
||||
startYmd: formatYmd(start),
|
||||
/** 窗口结束日(今天) */
|
||||
endYmd: formatYmd(end),
|
||||
statInts,
|
||||
labels,
|
||||
/** 魔盒 summary:自首日 00:00:00 到当前时刻 */
|
||||
summaryStart: `${formatYmd(start)} 00:00:00`,
|
||||
summaryEnd: formatYmdHms(now),
|
||||
/** 柱状图高亮「今天」列(固定最后一根) */
|
||||
todayChartIdx: 6
|
||||
}
|
||||
}
|
||||
|
||||
/** 看板左侧近 7 日柱图:`labels` + `todayIdx`(与 `getLast7DaysStatContext` 一致) */
|
||||
export function getLast7DaysChartInfo(now = new Date()) {
|
||||
const ctx = getLast7DaysStatContext(now)
|
||||
return { labels: ctx.labels, todayIdx: ctx.todayChartIdx }
|
||||
}
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
<!-- ===== 左侧面板 ===== -->
|
||||
<div class="left-panel panel-box">
|
||||
<StatusSummary
|
||||
:devices="mqtt.devices"
|
||||
:devices="overviewDevices"
|
||||
:weeklyLabels="weeklyLabels"
|
||||
:weeklyProduce="weeklyProduceTotal"
|
||||
:todayIdx="todayIdx"
|
||||
@ -68,6 +68,11 @@
|
||||
| 最近消息:{{ mqtt.lastMessageTopic }} @ {{ mqtt.lastMessageAt }}
|
||||
</template>
|
||||
<span v-if="mqtt.error" class="mqtt-err"> | {{ mqtt.error }}</span>
|
||||
<template v-if="laser.enabled">
|
||||
| 激光魔盒:{{ laser.syncing ? '同步中' : '已同步' }}
|
||||
<template v-if="laser.lastSyncAt"> @ {{ laser.lastSyncAt }}</template>
|
||||
<span v-if="laser.error" class="mqtt-err"> | {{ laser.error }}</span>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="mqtt.lastRouteHint" class="mqtt-hint">{{ mqtt.lastRouteHint }}</div>
|
||||
</div>
|
||||
@ -83,23 +88,42 @@ import PowerCard from '../components/PowerCard.vue'
|
||||
import StatusSummary from '../components/StatusSummary.vue'
|
||||
import AlarmPanel from '../components/AlarmPanel.vue'
|
||||
import { mqttRuntime } from '../services/mqttDeviceStore.js'
|
||||
import { getWeeklyInfo } from '../utils/weekLabels.js'
|
||||
import { laserBoxRuntime } from '../services/laserBoxSync.js'
|
||||
import { getLast7DaysChartInfo } from '../utils/weekLabels.js'
|
||||
import { getDeviceStatus } from '../composables/useDeviceStatus.js'
|
||||
|
||||
const router = useRouter()
|
||||
const mqtt = mqttRuntime
|
||||
const laser = laserBoxRuntime
|
||||
|
||||
// 按类型过滤
|
||||
const laserDevices = computed(() => mqttRuntime.devices.filter(d => d.type === 'laser'))
|
||||
/**
|
||||
* A 类数据源:已配置魔盒 URL 时**只**用 HTTP 列表(即使暂时为空也不回退 MQTT)。
|
||||
* 未配置魔盒时才展示 MQTT 中的 `type === 'laser'`。
|
||||
*/
|
||||
const laserListForUi = computed(() => {
|
||||
if (laser.enabled) return laser.devices
|
||||
return mqttRuntime.devices.filter((d) => d.type === 'laser')
|
||||
})
|
||||
|
||||
const overviewDevices = computed(() => [
|
||||
...laserListForUi.value,
|
||||
...mqttRuntime.devices.filter((d) => d.type !== 'laser')
|
||||
])
|
||||
|
||||
const laserDevices = computed(() => laserListForUi.value)
|
||||
const cncDevices = computed(() => mqttRuntime.devices.filter(d => d.type === 'cnc'))
|
||||
const powerDevices = computed(() => mqttRuntime.devices.filter(d => d.type === 'power'))
|
||||
|
||||
// 周报表
|
||||
const { labels: weeklyLabels, todayIdx } = getWeeklyInfo()
|
||||
// 左侧柱图横轴:近 7 日(含今天);最后一根高亮为今天(todayIdx === 6)
|
||||
const { labels: weeklyLabels, todayIdx } = getLast7DaysChartInfo()
|
||||
|
||||
/**
|
||||
* 各设备 `weeklyStats.produce` 按索引 0…6 与上面对齐。
|
||||
* 注意:B/C 若 MQTT 上游仍按「自然周」传 7 个数,与近 7 日日历可能错位,宜在采集端改为按日或滚动窗口。
|
||||
*/
|
||||
const weeklyProduceTotal = computed(() => {
|
||||
const totals = [0, 0, 0, 0, 0, 0, 0]
|
||||
mqttRuntime.devices.forEach(d => {
|
||||
overviewDevices.value.forEach((d) => {
|
||||
if (d.weeklyStats?.produce) {
|
||||
d.weeklyStats.produce.forEach((v, i) => {
|
||||
if (i <= todayIdx) totals[i] += v
|
||||
@ -113,7 +137,7 @@ const weeklyProduceTotal = computed(() => {
|
||||
const alarms = computed(() => {
|
||||
const arr = []
|
||||
const now = new Date()
|
||||
mqttRuntime.devices.forEach(d => {
|
||||
overviewDevices.value.forEach(d => {
|
||||
if (!d.online || !d.machineData) return
|
||||
const status = getDeviceStatus(d)
|
||||
if (status.key !== 'alarm') return
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<div class="offline-page" v-if="!allDevices.length">
|
||||
<div class="offline-box">
|
||||
<div class="offline-title">未配置设备</div>
|
||||
<div class="offline-reason">请配置 VITE_MQTT_TOPICS(逗号分隔);可选 VITE_MQTT_TOPIC_PREFIX 拼接路径,或直接写完整 topic(如 topic/xx/rbiot-c01-001)</div>
|
||||
<div class="offline-reason">请配置 VITE_MQTT_TOPICS(逗号分隔),或配置 VITE_LASER_BOX_URL 从魔盒拉取 A 类设备;可选 VITE_MQTT_TOPIC_PREFIX 拼接路径,或直接写完整 topic(如 topic/xx/rbiot-c01-001)</div>
|
||||
</div>
|
||||
</div>
|
||||
<template v-else>
|
||||
@ -13,7 +13,7 @@
|
||||
<button class="back-btn" @click="goBack">← 返回全景看板</button>
|
||||
<select v-model="selectedId" @change="switchDevice" class="device-select">
|
||||
<option v-for="d in allDevices" :key="d.id" :value="d.id">
|
||||
{{ d.mqttTopic }} · {{ d.name }} ({{ typeLabel(d.type) }})
|
||||
{{ deviceSelectLabel(d) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
@ -197,32 +197,52 @@ import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import * as echarts from 'echarts'
|
||||
import { mqttRuntime, findDeviceByRouteParam } from '../services/mqttDeviceStore.js'
|
||||
import { laserBoxRuntime, findLaserDeviceByRouteParam } from '../services/laserBoxSync.js'
|
||||
import { getLast7DaysChartInfo } from '../utils/weekLabels.js'
|
||||
import { getCncWorkModeText, getLaserSysStateText } from '../composables/useDeviceStatus.js'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const allDevices = computed(() => mqttRuntime.devices)
|
||||
function findDeviceByAny(routeParamId) {
|
||||
return findLaserDeviceByRouteParam(routeParamId) || findDeviceByRouteParam(routeParamId)
|
||||
}
|
||||
|
||||
/** 与看板一致:魔盒已启用则 A 类仅 HTTP,不回退 MQTT */
|
||||
const laserListForDetail = computed(() => {
|
||||
if (laserBoxRuntime.enabled) return laserBoxRuntime.devices
|
||||
return mqttRuntime.devices.filter((d) => d.type === 'laser')
|
||||
})
|
||||
|
||||
const allDevices = computed(() => [
|
||||
...laserListForDetail.value,
|
||||
...mqttRuntime.devices.filter((d) => d.type !== 'laser')
|
||||
])
|
||||
|
||||
const selectedId = ref(String(route.params.id || ''))
|
||||
const device = computed(() => findDeviceByRouteParam(selectedId.value) || findDeviceByRouteParam(route.params.id))
|
||||
const device = computed(() => findDeviceByAny(selectedId.value) || findDeviceByAny(route.params.id))
|
||||
|
||||
watch(
|
||||
() => route.params.id,
|
||||
(id) => {
|
||||
const sid = id ? String(id) : ''
|
||||
if (sid && findDeviceByRouteParam(sid)) selectedId.value = sid
|
||||
if (sid && findDeviceByAny(sid)) selectedId.value = sid
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
() => mqttRuntime.devices.map(d => d.id).join(','),
|
||||
() => [
|
||||
laserBoxRuntime.enabled,
|
||||
laserBoxRuntime.devices.map((d) => d.id).join(','),
|
||||
mqttRuntime.devices.map((d) => d.id).join(',')
|
||||
],
|
||||
() => {
|
||||
const list = mqttRuntime.devices
|
||||
const list = allDevices.value
|
||||
if (!list.length) return
|
||||
if (!selectedId.value || !findDeviceByRouteParam(selectedId.value)) {
|
||||
if (!selectedId.value || !findDeviceByAny(selectedId.value)) {
|
||||
const rid = route.params?.id ? String(route.params.id) : ''
|
||||
selectedId.value = (rid && findDeviceByRouteParam(rid)) ? rid : list[0].id
|
||||
selectedId.value = rid && findDeviceByAny(rid) ? rid : list[0].id
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
@ -267,6 +287,11 @@ function typeLabel(t) {
|
||||
return { laser: '激光', cnc: 'CNC', power: '电力' }[t] || t
|
||||
}
|
||||
|
||||
function deviceSelectLabel(d) {
|
||||
const topic = d.mqttTopic || (d.ip ? `魔盒 ${d.ip}` : '—')
|
||||
return `${topic} · ${d.name} (${typeLabel(d.type)})`
|
||||
}
|
||||
|
||||
function goBack() { router.push({ name: 'Dashboard' }) }
|
||||
function switchDevice() { router.replace({ name: 'DeviceDetail', params: { id: selectedId.value } }) }
|
||||
|
||||
@ -284,7 +309,7 @@ function formatSec(sec) {
|
||||
return `${h}H ${m}M`
|
||||
}
|
||||
|
||||
// ====== ECharts(CNC / 激光周趋势)======
|
||||
// ====== ECharts(CNC / 激光;横轴优先 weeklyStats.dates,否则与看板一致的近 7 日标签)======
|
||||
const chartRef = ref(null)
|
||||
let chartInstance = null
|
||||
|
||||
@ -355,7 +380,7 @@ function updateChart() {
|
||||
},
|
||||
grid: { left: '3%', right: '4%', bottom: '3%', top: '40px', containLabel: true },
|
||||
xAxis: {
|
||||
type: 'category', data: stats.dates || ['周一','周二','周三','周四','周五','周六','周日'],
|
||||
type: 'category', data: stats.dates || getLast7DaysChartInfo().labels,
|
||||
axisLabel: { color: '#6a8a9a' }, axisLine: { lineStyle: { color: '#1a3a6a' } }
|
||||
},
|
||||
yAxis: [
|
||||
@ -403,6 +428,21 @@ watch(
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
() => [
|
||||
device.value?.type,
|
||||
device.value?.machineData?.timestamp,
|
||||
device.value?.weeklyStats?.produce?.join(','),
|
||||
device.value?.weeklyStats?.cuttime?.join(',')
|
||||
],
|
||||
() => {
|
||||
if (!device.value || device.value.type === 'power') return
|
||||
nextTick(() => {
|
||||
if (chartInstance) updateChart()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', onChartResize)
|
||||
nextTick(() => {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user