feat: add typed data and views with scoped device power
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "zhao-steward-ui",
|
||||
"private": true,
|
||||
"version": "0.1.55",
|
||||
"version": "0.1.56",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<script setup>
|
||||
import {computed, ref, watch} from 'vue'
|
||||
import {dataViewModel, runDataViewOperation} from '../composables/data-view.mjs'
|
||||
|
||||
const props = defineProps({
|
||||
dataType: {type: Object, default: null}, viewType: {type: Object, default: null}, dataInstance: {type: Object, default: null},
|
||||
capabilities: {type: Object, default: null}, operation: Function, now: {type: Number, default: undefined},
|
||||
})
|
||||
const pending = ref(false), error = ref('')
|
||||
let generation = 0
|
||||
watch(() => [props.dataType?.id, props.viewType?.id, props.dataInstance?.id].join('|'), () => {generation++; pending.value = false; error.value = ''}, {flush: 'sync'})
|
||||
const options = computed(() => ({dataType: props.dataType, viewType: props.viewType, dataInstance: props.dataInstance,
|
||||
capabilities: props.capabilities ? {...props.capabilities, pending: pending.value || props.capabilities.pending === true} : null,
|
||||
operation: props.operation, now: props.now ?? Date.now() / 1000}))
|
||||
const model = computed(() => dataViewModel({...options.value, hasOperation: typeof props.operation === 'function'}))
|
||||
async function perform(id) {
|
||||
if (pending.value || !model.value.actions.some(action => action.id === id && action.enabled)) return
|
||||
const inputs = options.value, version = generation
|
||||
pending.value = true; error.value = ''
|
||||
// The injected callback owns confirmation, authorization, and delivery; this view only passes a typed operation.
|
||||
try {await runDataViewOperation(inputs, id)} catch (reason) {if (version === generation) error.value = reason?.message || '操作未完成'}
|
||||
finally {if (version === generation) pending.value = false}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="data-view" :aria-busy="pending">
|
||||
<p v-if="!model.compatible" class="small text-secondary mb-0" role="status">{{ model.error }}</p>
|
||||
<template v-else>
|
||||
<dl v-if="model.rows.length" class="data-view-values mb-0" :class="{'data-view-power': model.renderer === 'power'}">
|
||||
<div v-for="row in model.rows" :key="row.key">
|
||||
<dt><code v-if="row.runtime" class="me-1">{{ row.key }}</code>{{ row.label }}</dt>
|
||||
<dd :class="{'text-secondary': row.unknown}">{{ row.value }}<span v-if="row.unit && !row.unknown"> {{ row.unit }}</span></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else class="small text-secondary mb-0">此数据类型没有可展示字段。</p>
|
||||
<div v-if="model.actions.length" class="d-flex flex-wrap gap-2 mt-3">
|
||||
<button v-for="action in model.actions" :key="action.id" type="button" class="btn btn-sm btn-outline-primary" :disabled="!action.enabled || pending" @click="perform(action.id)">{{ action.label }}</button>
|
||||
</div>
|
||||
<p v-if="error" class="small text-danger mt-2 mb-0" role="alert">{{ error }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.data-view-values {display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: .75rem}
|
||||
.data-view-values dt {font-size: .8125rem; font-weight: 500; color: var(--bs-secondary-color)}
|
||||
.data-view-values dd {margin: .2rem 0 0; overflow-wrap: anywhere}
|
||||
.data-view-power dd {font-weight: 600}
|
||||
.data-view-values code {color: inherit}
|
||||
</style>
|
||||
@@ -9,6 +9,9 @@ import AppIcon from "./AppIcon.vue";
|
||||
import NetworkStatus from "./NetworkStatus.vue";
|
||||
import DisplayManager from './DisplayManager.vue';
|
||||
import DeviceTransfer from './DeviceTransfer.vue';
|
||||
import DevicePowerPanel from './DevicePowerPanel.vue';
|
||||
import DeviceTypeLibrary from './DeviceTypeLibrary.vue';
|
||||
const powerManaged = (d) => d.source === 'device' && d.powerManaged === true;
|
||||
const channels = (d) =>
|
||||
(snapshot.value.state.cameras || []).filter((c) =>
|
||||
d.source === "camera"
|
||||
@@ -28,6 +31,7 @@ const monitored = (d) =>
|
||||
</script>
|
||||
<template>
|
||||
<div id="asset-list">
|
||||
<DeviceTypeLibrary :active="snapshot.page === 'objects'" />
|
||||
<section
|
||||
v-for="group in deviceView.groups"
|
||||
:key="group.key"
|
||||
@@ -43,7 +47,12 @@ const monitored = (d) =>
|
||||
:key="d.source + d.id"
|
||||
class="card device-card"
|
||||
>
|
||||
<div class="card-body">
|
||||
<div v-if="powerManaged(d)" class="card-body">
|
||||
<h3><button class="device-title" @click="bridge().enterDevice(d.source, d.id, 'device')">{{ d.name }}</button></h3>
|
||||
<p class="device-location">{{ bridge().location?.(d.siteId) || '区域待填写' }}<template v-if="d.point"> · {{ d.point }}</template></p>
|
||||
<DevicePowerPanel :device="d" :active="snapshot.page === 'objects' && deviceView.mode === 'cards'" />
|
||||
</div>
|
||||
<div v-else class="card-body">
|
||||
<div class="device-card-heading">
|
||||
<div class="device-symbol">
|
||||
<AppIcon
|
||||
@@ -123,7 +132,7 @@ const monitored = (d) =>
|
||||
<DisplayManager v-if="d.source==='device' && /电视|显示|大屏/.test(d.deviceType)" :device="d"/>
|
||||
<DeviceTransfer :device="d"/>
|
||||
</div>
|
||||
<div class="card-footer device-card-actions">
|
||||
<div v-if="!powerManaged(d)" class="card-footer device-card-actions">
|
||||
<button
|
||||
class="btn btn-sm btn-outline-secondary"
|
||||
@click="bridge().enterDevice(d.source, d.id, 'device')"
|
||||
|
||||
@@ -1,7 +1,25 @@
|
||||
<script setup>
|
||||
import {snapshot} from '../composables/bridge.js'
|
||||
import {snapshot, bridge} from '../composables/bridge.js'
|
||||
import NetworkStatus from './NetworkStatus.vue'
|
||||
import DisplayManager from './DisplayManager.vue'
|
||||
import DeviceTransfer from './DeviceTransfer.vue'
|
||||
import DevicePowerPanel from './DevicePowerPanel.vue'
|
||||
import DeviceTypeBinding from './DeviceTypeBinding.vue'
|
||||
</script>
|
||||
<template><section v-if="snapshot.admin&&snapshot.device&&snapshot.page==='device'" class="panel"><h3>网络状态与管理入口</h3><DisplayManager v-if="snapshot.device.source==='device' && /电视|显示|大屏/.test(snapshot.device.deviceType)" :device="snapshot.device"/><NetworkStatus v-else :device="snapshot.device"/><DeviceTransfer :device="snapshot.device"/></section></template>
|
||||
<template>
|
||||
<template v-if="snapshot.loggedIn && snapshot.device && snapshot.page === 'device'">
|
||||
<section v-if="snapshot.device.source === 'device' && snapshot.device.powerManaged === true" class="panel">
|
||||
<h3>{{ snapshot.device.name }}</h3>
|
||||
<p class="device-location">{{ bridge().location?.(snapshot.device.siteId) || '区域待填写' }}<template v-if="snapshot.device.point"> · {{ snapshot.device.point }}</template></p>
|
||||
<DevicePowerPanel :device="snapshot.device" show-grants />
|
||||
<DeviceTransfer :device="snapshot.device" />
|
||||
</section>
|
||||
<section v-else-if="snapshot.admin" class="panel">
|
||||
<h3>网络状态与管理入口</h3>
|
||||
<DisplayManager v-if="snapshot.device.source === 'device' && /电视|显示|大屏/.test(snapshot.device.deviceType)" :device="snapshot.device" />
|
||||
<NetworkStatus v-else :device="snapshot.device" />
|
||||
<DeviceTransfer :device="snapshot.device" />
|
||||
</section>
|
||||
<DeviceTypeBinding v-if="snapshot.device.source === 'device'" :device="snapshot.device" />
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup>
|
||||
import {computed, onBeforeUnmount, ref, shallowRef, watch} from 'vue'
|
||||
import {bridge, snapshot} from '../composables/bridge.js'
|
||||
import {createDevicePowerSession, grantRows, powerView} from '../composables/device-power.mjs'
|
||||
|
||||
const props = defineProps({device: {type: Object, required: true}, active: {type: Boolean, default: true}, showGrants: Boolean})
|
||||
const result = shallowRef({power: null, pending: false, canManage: false, candidates: [], grants: [], error: '', message: '', observedAt: Date.now() / 1000})
|
||||
const grantsOpen = ref(false), draft = ref([]), dirty = ref(false)
|
||||
const session = createDevicePowerSession({request: (...args) => bridge().api(...args), onChange: value => {result.value = value}})
|
||||
const context = computed(() => ({
|
||||
deviceId: props.device.source === 'device' && props.device.powerManaged === true ? props.device.id : '',
|
||||
familyId: snapshot.value.state.familyId, session: snapshot.value.session, userId: snapshot.value.user?.id,
|
||||
authMarker: [snapshot.value.user?.personId, snapshot.value.user?.role, snapshot.value.admin].join('|'),
|
||||
loggedIn: snapshot.value.loggedIn, active: props.active,
|
||||
}))
|
||||
const contextKey = computed(() => JSON.stringify(context.value))
|
||||
watch(contextKey, () => {grantsOpen.value = false; dirty.value = false; draft.value = []; session.setContext(context.value)}, {immediate: true, flush: 'sync'})
|
||||
watch(() => result.value, value => {
|
||||
if (!value.canManage) {grantsOpen.value = false; dirty.value = false; draft.value = []}
|
||||
else if (!dirty.value) draft.value = grantRows(value)
|
||||
})
|
||||
onBeforeUnmount(() => session.dispose())
|
||||
const view = computed(() => powerView(result.value.power, {now: result.value.observedAt, pending: result.value.pending}))
|
||||
const stateLabel = computed(() => ({online: '在线', offline: '离线 · 网络不可达', unknown: '未知'}[view.value.state]))
|
||||
const statusLabel = value => ({queued: '等待执行', sent: '已发送', delivered: '已送达', scheduled: '已安排关机', succeeded: '已完成', success: '已完成', failed: '失败', blocked: '未执行', timed_out: '超时', timeout: '超时', cancelled: '已取消'}[value] || value || '已记录')
|
||||
const formatTime = value => Number.isFinite(value) && value > 0 ? new Date(value * 1000).toLocaleString('zh-CN') : '尚未记录'
|
||||
function shutdown() {
|
||||
if (!view.value.canShutdown) return
|
||||
if (window.confirm(`确定正常关闭“${props.device.name}”?请先保存工作。系统将正常关机,未保存的工作可能阻止关机。`)) session.command(2, true)
|
||||
}
|
||||
function changeView(row) {if (!row.view) row.control = false; dirty.value = true}
|
||||
async function saveGrants() {if (await session.saveGrants(draft.value)) {dirty.value = false; draft.value = grantRows(result.value)}}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="device-power-panel" :aria-busy="result.pending">
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mb-3" role="status" aria-live="polite">
|
||||
<span class="badge" :class="view.state === 'online' ? 'text-bg-success' : view.state === 'offline' ? 'text-bg-secondary' : 'text-bg-warning'">RUN · {{ stateLabel }}</span>
|
||||
<span v-if="result.pending" class="small text-secondary">正在更新…</span>
|
||||
<span v-else-if="view.state === 'unknown'" class="small text-secondary">状态未确认,暂不可操作</span>
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<button type="button" class="btn btn-primary btn-sm" :disabled="!view.canStart" @click="session.command(1)">开机</button>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm" :disabled="!view.canShutdown" @click="shutdown">关机</button>
|
||||
</div>
|
||||
<div class="small text-secondary power-history">
|
||||
<div>最近检查:{{ formatTime(result.power?.checkedAt) }}</div>
|
||||
<template v-if="result.power?.last">
|
||||
<div>最近操作:{{ formatTime(result.power.last.at) }}</div>
|
||||
<div class="power-result">{{ result.power.last.op === 1 ? '开机' : '关机' }} · {{ statusLabel(result.power.last.status) }}<template v-if="result.power.last.result"> · {{ result.power.last.result }}</template></div>
|
||||
</template>
|
||||
<div v-else>最近结果:尚无操作记录</div>
|
||||
</div>
|
||||
<div v-if="result.error" class="mt-2" role="alert">
|
||||
<p class="small text-danger mb-1">{{ result.error }}</p>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" :disabled="result.pending" @click="session.refresh">重新读取状态</button>
|
||||
</div>
|
||||
<details v-if="showGrants && result.canManage" :open="grantsOpen" class="power-grants border-top mt-3 pt-3" @toggle="grantsOpen = $event.target.open">
|
||||
<summary>手机查看与控制授权</summary>
|
||||
<p class="small text-secondary mt-2">选择已配对的成员。查看设备与开关机权限分别授权,控制权限同时需要查看权限。</p>
|
||||
<fieldset :disabled="result.pending">
|
||||
<div v-for="row in draft" :key="row.personId" class="power-grant-row py-2 border-bottom">
|
||||
<span>{{ row.name }}</span>
|
||||
<label class="form-check mb-0"><input v-model="row.view" type="checkbox" class="form-check-input" @change="changeView(row)">查看</label>
|
||||
<label class="form-check mb-0"><input v-model="row.control" type="checkbox" class="form-check-input" :disabled="!row.view" @change="dirty = true">控制</label>
|
||||
</div>
|
||||
<p v-if="!draft.length" class="small text-secondary">暂无可授权成员,请先完成手机配对。</p>
|
||||
<button type="button" class="btn btn-sm btn-outline-primary mt-3" :disabled="!dirty" @click="saveGrants">保存设备权限</button>
|
||||
</fieldset>
|
||||
<p v-if="result.message" class="small text-success mt-2 mb-0" role="status">{{ result.message }}</p>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.power-history {line-height: 1.7}
|
||||
.power-result {overflow-wrap: anywhere}
|
||||
.power-grants summary {cursor: pointer; font-weight: 600}
|
||||
.power-grant-row {display: flex; align-items: center; flex-wrap: wrap; gap: .75rem}
|
||||
.power-grant-row > span {flex: 1 1 8rem; overflow-wrap: anywhere}
|
||||
.power-grant-row label {flex: 0 0 auto}
|
||||
</style>
|
||||
@@ -0,0 +1,109 @@
|
||||
<script setup>
|
||||
import {computed, onBeforeUnmount, onMounted, ref, shallowRef, watch} from 'vue'
|
||||
import {bridge, snapshot} from '../composables/bridge.js'
|
||||
import {createDataTypeSession, createDeviceTypeSession, createDeviceViewSession, createViewTypeSession, compatibleViewTypes, initialProperties, propertyRows} from '../composables/device-types.mjs'
|
||||
import DataView from './DataView.vue'
|
||||
|
||||
const props = defineProps({device: {type: Object, required: true}, active: {type: Boolean, default: true}})
|
||||
const listing = shallowRef({types: [], blocks: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const views = shallowRef({items: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const dataTypes = shallowRef({types: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const viewTypes = shallowRef({types: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const editing = ref(false), selectedId = ref(''), values = ref({}), bound = ref(null), notice = ref('')
|
||||
const viewDraft = ref(null)
|
||||
const observedAt = ref(Date.now() / 1000)
|
||||
let clockTimer
|
||||
onMounted(() => {clockTimer = setInterval(() => {observedAt.value = Date.now() / 1000}, 1000)})
|
||||
const request = (...args) => bridge().api(...args)
|
||||
const typeSession = createDeviceTypeSession({request, onChange: state => {listing.value = state}})
|
||||
const dataSession = createDataTypeSession({request, onChange: state => {dataTypes.value = state}})
|
||||
const viewTypeSession = createViewTypeSession({request, onChange: state => {viewTypes.value = state}})
|
||||
const viewSession = createDeviceViewSession({request, onChange: state => {views.value = state}})
|
||||
const context = computed(() => ({deviceId: props.device.id, familyId: snapshot.value.state.familyId, session: snapshot.value.session, userId: snapshot.value.user?.id,
|
||||
authMarker: [snapshot.value.user?.personId, snapshot.value.user?.role, snapshot.value.admin].join('|'), loggedIn: snapshot.value.loggedIn, active: props.active && props.device.source === 'device'}))
|
||||
const contextKey = computed(() => JSON.stringify(context.value))
|
||||
watch(contextKey, () => {editing.value = false; selectedId.value = ''; values.value = {}; bound.value = null; notice.value = ''; viewDraft.value = null; typeSession.setContext(context.value); dataSession.setContext(context.value); viewTypeSession.setContext(context.value)}, {immediate: true, flush: 'sync'})
|
||||
const device = computed(() => bound.value || props.device)
|
||||
const dataInstance = computed(() => device.value.dataInstance || null)
|
||||
const currentType = computed(() => listing.value.types.find(type => type.id === (device.value.typeId || 'generic')))
|
||||
const currentDataType = computed(() => dataTypes.value.types.find(type => type.id === dataInstance.value?.dataTypeId))
|
||||
const selectedType = computed(() => listing.value.types.find(type => type.id === selectedId.value))
|
||||
const rows = computed(() => propertyRows(currentType.value, device.value.properties))
|
||||
const dataTypeId = computed(() => dataInstance.value?.dataTypeId || '')
|
||||
const compatibleViews = computed(() => compatibleViewTypes(viewTypes.value.types, dataTypeId.value))
|
||||
const viewContext = computed(() => {const {deviceId, ...scope} = context.value; return {...scope, dataInstanceId: dataInstance.value?.id || '', dataTypeId: dataTypeId.value}})
|
||||
watch(() => JSON.stringify(viewContext.value), () => {viewDraft.value = null; viewSession.setContext(viewContext.value)}, {immediate: true, flush: 'sync'})
|
||||
watch(() => JSON.stringify([props.device.typeId, props.device.properties, props.device.dataInstance]), () => {bound.value = null})
|
||||
watch(() => listing.value.canManage, value => {if (!value) editing.value = false})
|
||||
watch(() => views.value.canManage, value => {if (!value) viewDraft.value = null})
|
||||
onBeforeUnmount(() => {clearInterval(clockTimer); typeSession.dispose(); dataSession.dispose(); viewTypeSession.dispose(); viewSession.dispose()})
|
||||
const viewTypeName = id => viewTypes.value.types.find(type => type.id === id)?.name || '正在读取'
|
||||
const definitionForView = item => viewTypes.value.types.find(type => type.id === item.viewTypeId)
|
||||
const dataTypeForView = item => dataTypes.value.types.find(type => type.id === definitionForView(item)?.dataTypeId)
|
||||
function edit() {selectedId.value = currentType.value?.id || ''; values.value = initialProperties(currentType.value, device.value.properties); editing.value = true}
|
||||
function selectType() {values.value = initialProperties(selectedType.value)}
|
||||
async function save() {
|
||||
const key = contextKey.value
|
||||
const result = await typeSession.bind(props.device.id, selectedId.value, values.value)
|
||||
if (!result) return
|
||||
bound.value = result.device || null; editing.value = false
|
||||
try {await bridge().refresh()} catch {if (contextKey.value === key) notice.value = '绑定与参数已保存;目录暂未刷新,可稍后重新读取。'}
|
||||
if (contextKey.value === key) await viewSession.refresh()
|
||||
}
|
||||
function newView() {const type = compatibleViews.value[0]; viewDraft.value = {viewTypeId: type?.id || '', title: (device.value.name + ' · ' + (type?.name || '新视图')).slice(0, 80)}}
|
||||
async function saveView() {if (await viewSession.save(viewDraft.value, viewTypes.value.types)) viewDraft.value = null}
|
||||
function removeView(item) {if (window.confirm(`删除视图“${item.title}”?设备本身和设备数据会保留。`)) viewSession.remove(item.id)}
|
||||
function reload() {editing.value = false; viewDraft.value = null; typeSession.refresh(); dataSession.refresh(); viewTypeSession.refresh(); viewSession.refresh()}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel device-type-binding" :aria-busy="listing.pending || views.pending">
|
||||
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3"><h3 class="mb-0">设备实例与视图实例</h3><button type="button" class="btn btn-sm btn-outline-secondary" :disabled="listing.pending || views.pending" @click="reload">重新读取</button></div>
|
||||
<p class="small text-secondary mb-1">设备实例:{{ device.name }} · 数据实例:<span class="font-monospace instance-identity">{{ device.dataInstance?.id || device.id }}</span></p>
|
||||
<p class="small text-secondary">设备类型(FB):<strong>{{ currentType?.name || device.typeName || '正在读取' }}</strong><template v-if="currentType"> · 数据类型:{{ currentDataType?.name || currentType.dataTypeName || '正在读取' }}</template></p>
|
||||
<dl v-if="rows.length" class="instance-properties">
|
||||
<div v-for="row in rows" :key="row.key"><dt>{{ row.label }}</dt><dd>{{ row.value || '未填写' }}<span v-if="row.unit"> {{ row.unit }}</span></dd></div>
|
||||
</dl>
|
||||
<p v-else-if="currentType" class="small text-secondary">此设备类型没有附加参数。运行状态由设备功能块提供。</p>
|
||||
<button v-if="listing.canManage && !editing" type="button" class="btn btn-sm btn-outline-primary" :disabled="listing.pending" @click="edit">绑定类型与编辑参数</button>
|
||||
<form v-if="editing && listing.canManage" class="border rounded p-3 mt-3" @submit.prevent="save">
|
||||
<fieldset :disabled="listing.pending"><legend class="fs-6">此设备的数据实例</legend>
|
||||
<label class="d-block mb-3">设备类型(FB)<select v-model="selectedId" class="form-select mt-1" required @change="selectType"><option value="" disabled>请选择设备类型</option><option v-for="type in listing.types" :key="type.id" :value="type.id">{{ type.name }}</option></select></label>
|
||||
<div class="row g-3">
|
||||
<div v-for="field in selectedType?.fields || []" :key="field.key" class="col-12 col-md-6">
|
||||
<label v-if="field.type === 'boolean'" class="form-check"><input v-model="values[field.key]" class="form-check-input" type="checkbox">{{ field.label }}</label>
|
||||
<label v-else class="d-block">{{ field.label }}<span v-if="field.unit">({{ field.unit }})</span><input v-model="values[field.key]" class="form-control mt-1" :type="field.type === 'number' ? 'number' : 'text'" :min="field.min" :max="field.max" step="any" maxlength="500" :required="field.type === 'number'"></label>
|
||||
</div>
|
||||
</div>
|
||||
<p class="small text-secondary mt-3">更换类型会按新数据类型的默认值建立参数。视图实例共享这份设备数据;开关机权限仍由设备授权决定。</p>
|
||||
<div class="d-flex flex-wrap gap-2"><button type="submit" class="btn btn-sm btn-primary" :disabled="!selectedType">保存类型与参数</button><button type="button" class="btn btn-sm btn-outline-secondary" @click="editing = false">取消</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
<p v-if="listing.error" class="small text-danger mt-2" role="alert">{{ listing.error }}</p><p v-if="listing.message" class="small text-success mt-2" role="status">{{ listing.message }}</p><p v-if="notice" class="small text-secondary mt-2" role="status">{{ notice }}</p>
|
||||
<p v-if="dataTypes.error" class="small text-danger mt-2" role="alert">{{ dataTypes.error }}</p>
|
||||
|
||||
<div class="border-top mt-4 pt-3">
|
||||
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2"><h4 class="fs-6 mb-0">视图实例</h4><button v-if="views.canManage" type="button" class="btn btn-sm btn-outline-primary" :disabled="views.pending || viewTypes.pending || !compatibleViews.length" @click="newView">新建视图</button></div>
|
||||
<p class="small text-secondary mt-2">每个视图实例绑定数据实例和兼容的视图类型。可用视图类型只由数据类型决定,多个视图展示同一份数据,操作权限与设备一致。</p>
|
||||
<p v-if="!compatibleViews.length && !viewTypes.pending" class="small text-secondary">尚无兼容的视图类型,可在设备目录的“视图类型”中选择此数据类型新建。</p>
|
||||
<div v-for="item in views.items" :key="item.id" class="view-instance-row border rounded p-3 mb-2">
|
||||
<div class="flex-grow-1"><strong>{{ item.title }}</strong><div class="small text-secondary mt-1">视图类型:{{ item.viewTypeName || viewTypeName(item.viewTypeId) }} · 数据实例:{{ item.dataInstanceId }}</div></div>
|
||||
<div v-if="views.canManage" class="d-flex flex-wrap gap-2"><button type="button" class="btn btn-sm btn-outline-secondary" :disabled="views.pending || viewTypes.pending" @click="viewDraft = {id: item.id, title: item.title, revision: item.revision, viewTypeId: item.viewTypeId}">编辑视图</button><button type="button" class="btn btn-sm btn-outline-danger" :disabled="views.pending" @click="removeView(item)">删除视图</button></div>
|
||||
<DataView class="w-100 border-top pt-3" :data-type="dataTypeForView(item)" :view-type="definitionForView(item)" :data-instance="item.dataInstanceId === dataInstance?.id ? dataInstance : null" :now="observedAt" />
|
||||
</div>
|
||||
<p v-if="!views.items.length && !views.pending" class="small text-secondary">尚无命名视图,设备状态与参数仍可在本页查看。</p>
|
||||
<form v-if="viewDraft && views.canManage" class="border rounded p-3 mt-3" @submit.prevent="saveView"><fieldset :disabled="views.pending || viewTypes.pending"><legend class="fs-6">{{ viewDraft.id ? '编辑视图实例' : '新建视图实例' }}</legend><label class="d-block mb-3">视图名称<input v-model="viewDraft.title" class="form-control mt-1" maxlength="80" required></label><label class="d-block">视图类型<select v-model="viewDraft.viewTypeId" class="form-select mt-1" required><option value="" disabled>请选择兼容的视图类型</option><option v-for="type in compatibleViews" :key="type.id" :value="type.id">{{ type.name }}</option></select></label><div class="d-flex flex-wrap gap-2 mt-3"><button type="submit" class="btn btn-sm btn-primary" :disabled="!viewDraft.viewTypeId">保存视图</button><button type="button" class="btn btn-sm btn-outline-secondary" @click="viewDraft = null">取消</button></div></fieldset></form>
|
||||
<p v-if="views.error" class="small text-danger mt-2" role="alert">{{ views.error }}</p><p v-if="views.message" class="small text-success mt-2" role="status">{{ views.message }}</p>
|
||||
<p v-if="viewTypes.error" class="small text-danger mt-2" role="alert">{{ viewTypes.error }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.instance-properties {display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: .75rem}
|
||||
.instance-properties dt {font-weight: 500; font-size: .875rem; color: var(--bs-secondary-color)}
|
||||
.instance-properties dd {margin: .2rem 0 0; overflow-wrap: anywhere}
|
||||
.view-instance-row {display: flex; align-items: center; flex-wrap: wrap; gap: .75rem; overflow-wrap: anywhere}
|
||||
.instance-identity {overflow-wrap: anywhere}
|
||||
fieldset {min-width: 0}
|
||||
</style>
|
||||
@@ -0,0 +1,138 @@
|
||||
<script setup>
|
||||
import {computed, onBeforeUnmount, ref, shallowRef, watch} from 'vue'
|
||||
import {bridge, snapshot} from '../composables/bridge.js'
|
||||
import {createDataTypeSession, createDeviceTypeSession, createViewTypeSession, dataTypeDraft, typeDraft, viewTypeDraft} from '../composables/device-types.mjs'
|
||||
|
||||
const props = defineProps({active: {type: Boolean, default: true}})
|
||||
const open = ref(false), tab = ref('data'), dataDraft = ref(null), fbDraft = ref(null), viewDraft = ref(null), notice = ref('')
|
||||
const dataState = shallowRef({types: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const typeState = shallowRef({types: [], blocks: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const viewState = shallowRef({types: [], canManage: false, pending: false, error: '', message: ''})
|
||||
const request = (...args) => bridge().api(...args)
|
||||
const dataSession = createDataTypeSession({request, onChange: value => {dataState.value = value}})
|
||||
const typeSession = createDeviceTypeSession({request, onChange: value => {typeState.value = value}})
|
||||
const viewSession = createViewTypeSession({request, onChange: value => {viewState.value = value}})
|
||||
const context = computed(() => ({familyId: snapshot.value.state.familyId, session: snapshot.value.session, userId: snapshot.value.user?.id,
|
||||
authMarker: [snapshot.value.user?.personId, snapshot.value.user?.role, snapshot.value.admin].join('|'), loggedIn: snapshot.value.loggedIn, active: props.active && open.value}))
|
||||
const contextKey = computed(() => JSON.stringify(context.value))
|
||||
watch(contextKey, () => {dataDraft.value = null; fbDraft.value = null; viewDraft.value = null; notice.value = ''; dataSession.setContext(context.value); typeSession.setContext(context.value); viewSession.setContext(context.value)}, {immediate: true, flush: 'sync'})
|
||||
watch(() => dataState.value.canManage, value => {if (!value) dataDraft.value = null})
|
||||
watch(() => typeState.value.canManage, value => {if (!value) fbDraft.value = null})
|
||||
watch(() => viewState.value.canManage, value => {if (!value) viewDraft.value = null})
|
||||
onBeforeUnmount(() => {dataSession.dispose(); typeSession.dispose(); viewSession.dispose()})
|
||||
const pending = computed(() => dataState.value.pending || typeState.value.pending || viewState.value.pending)
|
||||
const compatibleData = computed(() => dataState.value.types.filter(item => (fbDraft.value?.fbType === 'computer.power.v1') === (item.id === 'computer-power')))
|
||||
const dataName = id => dataState.value.types.find(item => item.id === id)?.name || id || '未绑定'
|
||||
const driverName = id => ({'computer.power.v1': '电脑电源驱动', 'manual.v1': '手动参数驱动'}[id] || id)
|
||||
const kindName = id => ({text: '文本', number: '数值', boolean: '是 / 否', enum: '枚举', object: '对象'}[id] || id)
|
||||
function addField() {dataDraft.value.fields.push({key: '', label: '', type: 'text', unit: '', min: '', max: '', hasDefault: false, defaultValue: ''})}
|
||||
function fieldKindChanged(field) {field.min = ''; field.max = ''; field.defaultValue = field.type === 'boolean' ? false : field.type === 'number' ? 0 : ''}
|
||||
function editType(type, copy = false) {
|
||||
fbDraft.value = typeDraft(type)
|
||||
if (copy) Object.assign(fbDraft.value, {id: '', builtin: false, revision: 0, name: (type.name + ' · 自定义').slice(0, 80)})
|
||||
}
|
||||
function driverChanged() {
|
||||
if (!compatibleData.value.some(item => item.id === fbDraft.value.dataTypeId)) fbDraft.value.dataTypeId = compatibleData.value[0]?.id || ''
|
||||
}
|
||||
async function refreshSnapshot(key) {
|
||||
try {await bridge().refresh()} catch {if (key === contextKey.value) notice.value = '保存已完成;目录暂未刷新,可稍后重新读取。'}
|
||||
}
|
||||
async function saveData() {
|
||||
const key = contextKey.value
|
||||
if (await dataSession.save(dataDraft.value)) {dataDraft.value = null; await typeSession.refresh(); if (key === contextKey.value) await refreshSnapshot(key)}
|
||||
}
|
||||
async function saveType() {
|
||||
const key = contextKey.value
|
||||
if (await typeSession.save(fbDraft.value, dataState.value.types)) {fbDraft.value = null; await refreshSnapshot(key)}
|
||||
}
|
||||
async function saveViewType() {if (await viewSession.save(viewDraft.value, dataState.value.types)) viewDraft.value = null}
|
||||
function reload() {dataDraft.value = null; fbDraft.value = null; viewDraft.value = null; dataSession.refresh(); typeSession.refresh(); viewSession.refresh()}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details v-if="snapshot.loggedIn" class="panel device-type-library mb-3" :open="open" @toggle="open = $event.target.open">
|
||||
<summary>数据类型 · 设备类型(FB) · 视图类型</summary>
|
||||
<div v-if="open" class="mt-3">
|
||||
<p class="small text-secondary">数据类型定义数据结构;设备类型(FB)使用数据类型定义设备行为;视图类型只依赖数据类型,定义展示方式。每个设备实例拥有数据实例,多个视图实例可以展示同一份数据。</p>
|
||||
<div class="d-flex flex-wrap gap-2 mb-3" role="group" aria-label="类型库分类">
|
||||
<button type="button" class="btn btn-sm" :class="tab === 'data' ? 'btn-primary' : 'btn-outline-secondary'" :aria-pressed="tab === 'data'" @click="tab = 'data'">数据类型</button>
|
||||
<button type="button" class="btn btn-sm" :class="tab === 'fb' ? 'btn-primary' : 'btn-outline-secondary'" :aria-pressed="tab === 'fb'" @click="tab = 'fb'">设备类型(FB)</button>
|
||||
<button type="button" class="btn btn-sm" :class="tab === 'view' ? 'btn-primary' : 'btn-outline-secondary'" :aria-pressed="tab === 'view'" @click="tab = 'view'">视图类型</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary ms-auto" :disabled="pending" @click="reload">重新读取</button>
|
||||
</div>
|
||||
<section v-if="tab === 'data'" aria-label="数据类型库">
|
||||
<div class="d-flex flex-wrap justify-content-between gap-2 mb-3"><h3 class="fs-6 mb-0">数据类型</h3><button v-if="dataState.canManage" type="button" class="btn btn-sm btn-outline-primary" :disabled="pending" @click="dataDraft = dataTypeDraft()">新建数据类型</button></div>
|
||||
<div class="type-library-grid">
|
||||
<article v-for="item in dataState.types" :key="item.id" class="border rounded p-3">
|
||||
<div class="d-flex flex-wrap align-items-center gap-2"><strong>{{ item.name }}</strong><span class="badge text-bg-secondary">{{ item.builtin ? '内置' : '自定义' }}</span></div>
|
||||
<p class="small text-secondary mt-2 mb-1">参数:{{ item.fields.length ? item.fields.map(field => field.label).join('、') : '无附加参数' }}</p>
|
||||
<div v-if="item.signals?.length" class="small mt-2">运行数据:<span v-for="(signal, index) in item.signals" :key="signal.key">{{ index ? ' · ' : '' }}{{ signal.key }}({{ signal.name || signal.label || kindName(signal.type) }})</span></div>
|
||||
<button v-if="dataState.canManage && !item.builtin" type="button" class="btn btn-sm btn-outline-secondary mt-2" :disabled="pending" @click="dataDraft = dataTypeDraft(item)">编辑数据类型</button>
|
||||
</article>
|
||||
</div>
|
||||
<form v-if="dataDraft && dataState.canManage" class="border rounded p-3 mt-3" @submit.prevent="saveData">
|
||||
<fieldset :disabled="pending">
|
||||
<legend class="fs-6">{{ dataDraft.id ? '编辑' : '新建' }}数据类型</legend>
|
||||
<label class="d-block mb-3">数据类型名称<input v-model="dataDraft.name" class="form-control mt-1" maxlength="80" required></label>
|
||||
<p class="small text-secondary">参数标识以字母开头,可含字母、数字及下划线。未设置默认值时,文本为空、数值为 0、是 / 否为否;设定数值范围后,默认值也需在范围内。</p>
|
||||
<fieldset v-for="(field, index) in dataDraft.fields" :key="index" class="border rounded p-3 mb-3">
|
||||
<legend class="float-none w-auto px-1 fs-6">参数 {{ index + 1 }}</legend>
|
||||
<div class="row g-2">
|
||||
<label class="col-12 col-md-4">名称<input v-model="field.label" class="form-control" maxlength="80" required></label>
|
||||
<label class="col-12 col-md-4">标识<input v-model="field.key" class="form-control font-monospace" maxlength="40" pattern="[A-Za-z][A-Za-z0-9_]{0,39}" required></label>
|
||||
<label class="col-12 col-md-4">类型<select v-model="field.type" class="form-select" @change="fieldKindChanged(field)"><option value="text">文本</option><option value="number">数值</option><option value="boolean">是 / 否</option></select></label>
|
||||
<label class="col-12 col-md-4">单位(可选)<input v-model="field.unit" class="form-control" maxlength="20"></label>
|
||||
<template v-if="field.type === 'number'"><label class="col-6 col-md-4">最小值(可选)<input v-model="field.min" class="form-control" type="number" step="any"></label><label class="col-6 col-md-4">最大值(可选)<input v-model="field.max" class="form-control" type="number" step="any"></label></template>
|
||||
<div class="col-12"><label class="form-check"><input v-model="field.hasDefault" class="form-check-input" type="checkbox">设置默认值</label>
|
||||
<label v-if="field.hasDefault && field.type === 'boolean'" class="form-check"><input v-model="field.defaultValue" class="form-check-input" type="checkbox">默认值为是</label>
|
||||
<label v-else-if="field.hasDefault" class="d-block">默认值<input v-model="field.defaultValue" class="form-control" :type="field.type === 'number' ? 'number' : 'text'" step="any" maxlength="500" :required="field.type === 'number'"></label>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger mt-2" @click="dataDraft.fields.splice(index, 1)">移除此参数</button>
|
||||
</fieldset>
|
||||
<div class="d-flex flex-wrap gap-2"><button type="button" class="btn btn-sm btn-outline-secondary" :disabled="dataDraft.fields.length >= 24" @click="addField">增加参数</button><button type="submit" class="btn btn-sm btn-primary">保存数据类型</button><button type="button" class="btn btn-sm btn-outline-secondary" @click="dataDraft = null">取消</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</section>
|
||||
<section v-else-if="tab === 'fb'" aria-label="设备类型功能块库">
|
||||
<div class="d-flex flex-wrap justify-content-between gap-2 mb-3"><h3 class="fs-6 mb-0">设备类型(FB)</h3><button v-if="typeState.canManage" type="button" class="btn btn-sm btn-outline-primary" :disabled="pending" @click="editType()">新建设备类型</button></div>
|
||||
<div class="type-library-grid">
|
||||
<article v-for="item in typeState.types" :key="item.id" class="border rounded p-3">
|
||||
<div class="d-flex flex-wrap align-items-center gap-2"><strong>{{ item.name }}</strong><span class="badge text-bg-secondary">{{ item.builtin ? '内置' : '自定义' }}</span></div>
|
||||
<p class="small text-secondary mt-2 mb-1">数据类型:{{ dataName(item.dataTypeId) }}<br>执行驱动:{{ driverName(item.fbType) }}</p>
|
||||
<div v-if="typeState.canManage" class="d-flex flex-wrap gap-2 mt-2"><button v-if="!item.builtin" type="button" class="btn btn-sm btn-outline-secondary" :disabled="pending" @click="editType(item)">编辑设备类型</button><button type="button" class="btn btn-sm btn-outline-secondary" :disabled="pending" @click="editType(item, true)">复制为自定义</button></div>
|
||||
</article>
|
||||
</div>
|
||||
<form v-if="fbDraft && typeState.canManage" class="border rounded p-3 mt-3" @submit.prevent="saveType">
|
||||
<fieldset :disabled="pending"><legend class="fs-6">{{ fbDraft.id ? '编辑' : '新建' }}设备类型(FB)</legend>
|
||||
<div class="row g-3"><label class="col-12">设备类型名称<input v-model="fbDraft.name" class="form-control" maxlength="80" required></label>
|
||||
<label class="col-12 col-md-6">执行驱动<select v-model="fbDraft.fbType" class="form-select" @change="driverChanged"><option v-for="block in typeState.blocks" :key="block.id" :value="block.id">{{ driverName(block.id) }}</option></select></label>
|
||||
<label class="col-12 col-md-6">数据类型<select v-model="fbDraft.dataTypeId" class="form-select" required><option value="" disabled>请选择数据类型</option><option v-for="item in compatibleData" :key="item.id" :value="item.id">{{ item.name }}</option></select></label>
|
||||
</div>
|
||||
<p class="small text-secondary mt-3">参数结构在“数据类型”中维护。绑定电脑类型后,实际开关机能力仍由设备的受管配置和授权决定。</p>
|
||||
<div class="d-flex flex-wrap gap-2"><button type="submit" class="btn btn-sm btn-primary">保存设备类型</button><button type="button" class="btn btn-sm btn-outline-secondary" @click="fbDraft = null">取消</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</section>
|
||||
<section v-else aria-label="视图类型库">
|
||||
<div class="d-flex flex-wrap justify-content-between gap-2 mb-3"><h3 class="fs-6 mb-0">视图类型</h3><button v-if="viewState.canManage" type="button" class="btn btn-sm btn-outline-primary" :disabled="pending" @click="viewDraft = viewTypeDraft()">新建视图类型</button></div>
|
||||
<p class="small text-secondary">视图类型直接选择数据类型,可用于所有使用该数据类型的数据实例。</p>
|
||||
<div class="type-library-grid"><article v-for="item in viewState.types" :key="item.id" class="border rounded p-3"><div class="d-flex flex-wrap align-items-center gap-2"><strong>{{ item.name }}</strong><span class="badge text-bg-secondary">{{ item.builtin ? '内置' : '自定义' }}</span></div><p class="small text-secondary mt-2 mb-1">数据类型:{{ dataName(item.dataTypeId) }}<br>展示方式:{{ item.renderer === 'power' ? '电源状态与操作' : '数据参数' }}</p><button v-if="viewState.canManage && !item.builtin" type="button" class="btn btn-sm btn-outline-secondary mt-2" :disabled="pending" @click="viewDraft = viewTypeDraft(item)">编辑视图类型</button></article></div>
|
||||
<form v-if="viewDraft && viewState.canManage" class="border rounded p-3 mt-3" @submit.prevent="saveViewType"><fieldset :disabled="pending"><legend class="fs-6">{{ viewDraft.id ? '编辑' : '新建' }}视图类型</legend><div class="row g-3"><label class="col-12 col-md-6">视图类型名称<input v-model="viewDraft.name" class="form-control mt-1" maxlength="80" required></label><label class="col-12 col-md-6">数据类型<select v-model="viewDraft.dataTypeId" class="form-select mt-1" required><option v-for="item in dataState.types" :key="item.id" :value="item.id">{{ item.name }}</option></select></label></div><p class="small text-secondary mt-3">自定义视图以参数面板展示所选数据类型。</p><div class="d-flex flex-wrap gap-2"><button type="submit" class="btn btn-sm btn-primary">保存视图类型</button><button type="button" class="btn btn-sm btn-outline-secondary" @click="viewDraft = null">取消</button></div></fieldset></form>
|
||||
</section>
|
||||
<p v-if="pending" class="small text-secondary mt-3" role="status">正在读取或保存…</p>
|
||||
<p v-if="dataState.error" class="small text-danger mt-3" role="alert">{{ dataState.error }}</p><p v-if="typeState.error" class="small text-danger mt-3" role="alert">{{ typeState.error }}</p>
|
||||
<p v-if="viewState.error" class="small text-danger mt-3" role="alert">{{ viewState.error }}</p>
|
||||
<p v-if="tab === 'data' && dataState.message" class="small text-success mt-3" role="status">{{ dataState.message }}</p><p v-if="tab === 'fb' && typeState.message" class="small text-success mt-3" role="status">{{ typeState.message }}</p>
|
||||
<p v-if="tab === 'view' && viewState.message" class="small text-success mt-3" role="status">{{ viewState.message }}</p>
|
||||
<p v-if="notice" class="small text-secondary mt-3" role="status">{{ notice }}</p>
|
||||
</div>
|
||||
</details>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.device-type-library summary {cursor: pointer; font-weight: 600}
|
||||
.type-library-grid {display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 250px), 1fr)); gap: .75rem}
|
||||
.type-library-grid article {overflow-wrap: anywhere}
|
||||
fieldset {min-width: 0}
|
||||
</style>
|
||||
@@ -0,0 +1,54 @@
|
||||
const owns = (value, key) => Object.prototype.hasOwnProperty.call(value || {}, key)
|
||||
function validValue(field, value) {
|
||||
if (field.type === 'boolean') return typeof value === 'boolean'
|
||||
if (field.type === 'number') return typeof value === 'number' && Number.isFinite(value)
|
||||
if (field.type === 'enum') return Array.isArray(field.values) && field.values.includes(value)
|
||||
if (field.type === 'text') return typeof value === 'string'
|
||||
return false
|
||||
}
|
||||
function displayValue(field, value, renderer) {
|
||||
if (renderer === 'power') {
|
||||
if (field.key === 'RUN') return value ? '在线' : '离线 · 网络不可达'
|
||||
if (field.key === 'OP') return ({0: '空闲(0)', 1: '开机(1)', 2: '关机(2)'})[value] || String(value)
|
||||
if (field.key === 'BUSY') return value ? '处理中' : '空闲'
|
||||
if (field.key === 'RESULT') return value || '暂无结果'
|
||||
}
|
||||
if (field.type === 'boolean') return value ? '是' : '否'
|
||||
return String(value) || '未填写'
|
||||
}
|
||||
|
||||
export function dataViewModel({dataType, viewType, dataInstance, capabilities, hasOperation = false, now = Date.now() / 1000}) {
|
||||
const compatible = !!dataType?.id && viewType?.dataTypeId === dataType.id && dataInstance?.dataTypeId === dataType.id && ['properties', 'power'].includes(viewType.renderer)
|
||||
if (!compatible) return {compatible: false, renderer: '', rows: [], actions: [], error: '视图类型与数据实例的数据类型不匹配,或定义尚未加载'}
|
||||
const values = dataInstance.values && typeof dataInstance.values === 'object' ? dataInstance.values : {}
|
||||
const signals = Array.isArray(dataType.signals) ? dataType.signals : []
|
||||
const fields = Array.isArray(dataType.fields) ? dataType.fields : []
|
||||
const checkedAt = dataInstance.checkedAt
|
||||
const consistent = viewType.renderer !== 'power' || (dataInstance.quality === 'online' && values.RUN === true) || (dataInstance.quality === 'offline' && values.RUN === false)
|
||||
const fresh = !signals.length || (consistent && Number.isFinite(checkedAt) && checkedAt > 0 && checkedAt <= now + 5 && now - checkedAt <= 45 && dataInstance.quality !== 'unknown')
|
||||
const rows = [...fields.map(field => ({field, runtime: false})), ...signals.map(field => ({field, runtime: true}))].map(({field, runtime}) => {
|
||||
const known = owns(values, field.key) && validValue(field, values[field.key]) && (!runtime || fresh || field.key === 'RESULT')
|
||||
return {key: field.key, label: field.label || field.name || field.key, unit: field.unit || '', runtime,
|
||||
value: known ? displayValue(field, values[field.key], viewType.renderer) : '未知', unknown: !known}
|
||||
})
|
||||
const signalKnown = signals.every(field => owns(values, field.key) && validValue(field, values[field.key]))
|
||||
const authorized = hasOperation && capabilities?.dataInstanceId === dataInstance.id
|
||||
const actions = authorized && Array.isArray(capabilities.operations) ? capabilities.operations.filter(action => {
|
||||
const field = signals.find(item => item.key === action.field && item.access === 'write')
|
||||
return typeof action.id === 'string' && typeof action.label === 'string' && action.allowed === true && field && validValue(field, action.value)
|
||||
}).map(action => {
|
||||
let enabled = fresh && signalKnown && capabilities.pending !== true
|
||||
if (viewType.renderer === 'power') enabled = enabled && values.OP === 0 && values.BUSY === false &&
|
||||
(action.field !== 'OP' || (action.value === 1 && values.RUN === false) || (action.value === 2 && values.RUN === true))
|
||||
return {id: action.id, label: action.label, field: action.field, value: action.value, enabled}
|
||||
}) : []
|
||||
return {compatible: true, renderer: viewType.renderer, rows, actions, error: ''}
|
||||
}
|
||||
|
||||
export async function runDataViewOperation(options, actionId) {
|
||||
const model = dataViewModel({...options, hasOperation: typeof options.operation === 'function'})
|
||||
const action = model.actions.find(item => item.id === actionId && item.enabled)
|
||||
if (!action) return false
|
||||
await options.operation({dataInstanceId: options.dataInstance.id, field: action.field, value: action.value})
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
const FRESH_SECONDS = 45
|
||||
|
||||
export function powerView(power, {now = Date.now() / 1000, pending = false} = {}) {
|
||||
const checkedAt = power?.checkedAt
|
||||
const valid = power?.managed === true && Number.isFinite(checkedAt) && checkedAt > 0 &&
|
||||
checkedAt <= now + 5 && now - checkedAt <= FRESH_SECONDS && [0, 1, 2].includes(power.op) &&
|
||||
((power.state === 'online' && power.run === 1) || (power.state === 'offline' && power.run === 0))
|
||||
const run = valid ? power.run : null
|
||||
const idle = valid && !pending && power.op === 0
|
||||
return {
|
||||
run, state: valid ? power.state : 'unknown',
|
||||
canStart: idle && run === 0 && power.canStart === true,
|
||||
canShutdown: idle && run === 1 && power.canShutdown === true,
|
||||
}
|
||||
}
|
||||
|
||||
export function grantRows(listing) {
|
||||
if (listing?.canManage !== true) return []
|
||||
const grants = new Map((Array.isArray(listing.grants) ? listing.grants : []).map(item => [item.personId, item]))
|
||||
const seen = new Set()
|
||||
return (Array.isArray(listing.candidates) ? listing.candidates : []).filter(item => {
|
||||
if (typeof item?.personId !== 'string' || !item.personId || seen.has(item.personId)) return false
|
||||
seen.add(item.personId)
|
||||
return true
|
||||
}).map(item => {
|
||||
const grant = grants.get(item.personId), view = grant?.view === true
|
||||
return {personId: item.personId, name: item.name || '未命名成员', view, control: view && grant?.control === true}
|
||||
})
|
||||
}
|
||||
|
||||
export function createDevicePowerSession({request, onChange = () => {}, now = () => Date.now() / 1000,
|
||||
later = setTimeout, cancel = clearTimeout,
|
||||
makeRequestId = () => globalThis.crypto.randomUUID().replaceAll('-', ''),
|
||||
}) {
|
||||
let context = {}, contextKey = '', generation = 0, stopped = false, pollTimer, expiryTimer
|
||||
const empty = () => ({power: null, grants: [], candidates: [], canManage: false, pending: false, error: '', message: '', observedAt: now()})
|
||||
let state = empty()
|
||||
const emit = patch => {state = {...state, ...patch, observedAt: now()}; onChange(state)}
|
||||
const enabled = () => !stopped && context.loggedIn === true && context.active === true && !!context.deviceId && !!context.familyId
|
||||
const clearPoll = () => {cancel(pollTimer); pollTimer = undefined}
|
||||
const clearExpiry = () => {cancel(expiryTimer); expiryTimer = undefined}
|
||||
const current = version => version === generation && enabled()
|
||||
function schedule() {
|
||||
clearPoll()
|
||||
if (enabled()) pollTimer = later(refresh, 10000)
|
||||
}
|
||||
function setPower(power) {
|
||||
clearExpiry()
|
||||
emit({power: power && typeof power === 'object' ? power : null})
|
||||
if (Number.isFinite(power?.checkedAt)) {
|
||||
const delay = (power.checkedAt + FRESH_SECONDS - now()) * 1000 + 1, version = generation
|
||||
if (delay > 0 && delay <= (FRESH_SECONDS + 5) * 1000 + 1) {
|
||||
expiryTimer = later(() => {if (current(version)) emit({})}, delay)
|
||||
}
|
||||
}
|
||||
}
|
||||
function applyListing(value) {
|
||||
const rows = grantRows(value), canManage = value?.canManage === true
|
||||
emit({canManage, grants: rows.filter(row => row.view).map(({personId, view, control}) => ({personId, view, control})),
|
||||
candidates: rows.map(({personId, name}) => ({personId, name}))})
|
||||
setPower(value?.power)
|
||||
}
|
||||
function fail(error) {
|
||||
clearExpiry()
|
||||
emit({...empty(), pending: true, error: error?.stale ? '' : error?.message || '无法读取设备电源状态,请重试'})
|
||||
}
|
||||
async function refresh() {
|
||||
if (!enabled() || state.pending) return false
|
||||
clearPoll()
|
||||
const version = generation
|
||||
emit({pending: true, error: ''})
|
||||
let retry = true
|
||||
try {
|
||||
const value = await request('/api/device-power?id=' + encodeURIComponent(context.deviceId))
|
||||
if (!current(version)) return false
|
||||
applyListing(value)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (!current(version)) return false
|
||||
fail(error)
|
||||
retry = !error?.stale && ![401, 403, 404].includes(error?.status)
|
||||
return false
|
||||
} finally {
|
||||
if (current(version)) {emit({pending: false}); if (retry) schedule()}
|
||||
}
|
||||
}
|
||||
async function mutate(payload, permissions = false) {
|
||||
clearPoll()
|
||||
const version = generation
|
||||
emit({pending: true, error: '', message: ''})
|
||||
let retry = true
|
||||
try {
|
||||
const value = await request('/api/device-power', payload)
|
||||
if (!current(version)) return false
|
||||
if (permissions) {
|
||||
applyListing(value)
|
||||
emit({message: '设备权限已保存'})
|
||||
} else setPower(value?.power)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (!current(version)) return false
|
||||
fail(error)
|
||||
retry = !error?.stale && ![401, 403, 404].includes(error?.status)
|
||||
return false
|
||||
} finally {
|
||||
if (current(version)) {emit({pending: false}); if (retry) schedule()}
|
||||
}
|
||||
}
|
||||
function setContext(value) {
|
||||
const key = JSON.stringify([value.deviceId, value.familyId, value.session, value.userId, value.authMarker, value.loggedIn, value.active])
|
||||
if (stopped || key === contextKey) return
|
||||
generation++; contextKey = key; context = {...value}
|
||||
clearPoll(); clearExpiry(); emit(empty())
|
||||
if (enabled()) refresh()
|
||||
}
|
||||
async function command(op, confirmed = false) {
|
||||
if (!enabled() || state.pending || (op === 2 && confirmed !== true)) return false
|
||||
const view = powerView(state.power, {now: now()})
|
||||
if (!((op === 1 && view.canStart) || (op === 2 && view.canShutdown))) return false
|
||||
let requestId
|
||||
try {requestId = makeRequestId()} catch {emit({error: '无法生成安全操作编号,请刷新页面后重试'}); return false}
|
||||
if (!/^[a-f0-9]{32}$/.test(requestId)) {emit({error: '操作编号无效,请刷新页面后重试'}); return false}
|
||||
return mutate({action: 'command', deviceId: context.deviceId, op, requestId, confirm: true})
|
||||
}
|
||||
async function saveGrants(draft) {
|
||||
if (!enabled() || state.pending || !state.canManage) return false
|
||||
const grants = grantRows({...state, grants: Array.isArray(draft) ? draft : []})
|
||||
.filter(row => row.view).map(({personId, view, control}) => ({personId, view, control}))
|
||||
return mutate({action: 'grants', deviceId: context.deviceId, grants}, true)
|
||||
}
|
||||
function dispose() {
|
||||
stopped = true; generation++; clearPoll(); clearExpiry(); emit(empty())
|
||||
}
|
||||
return {setContext, refresh, command, saveGrants, dispose}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
const kinds = ['text', 'number', 'boolean']
|
||||
const reserved = new Set(['run', 'op', 'busy', 'result', 'state', 'checkedat', 'canstart', 'canshutdown', 'managed', 'powermanaged', 'last', 'id', 'familyid', 'deviceid', 'typeid', 'datatypeid', 'fbtype', 'viewtemplate', 'properties', 'revision', 'bootid', 'nonce', 'signature', 'payload', 'sshkey', 'knownhosts'])
|
||||
const has = (value, key) => Object.prototype.hasOwnProperty.call(value, key)
|
||||
const present = value => value !== '' && value !== undefined && value !== null
|
||||
const fallback = field => has(field, 'default') ? field.default : field.type === 'number' ? 0 : field.type === 'boolean' ? false : ''
|
||||
function text(value, label, max, required = true) {
|
||||
const result = typeof value === 'string' ? value.trim() : ''
|
||||
if ((required && !result) || result.length > max) throw Error(`${label}请填写 1–${max} 个字符`)
|
||||
return result
|
||||
}
|
||||
function number(value, label) {
|
||||
if ((typeof value !== 'number' && typeof value !== 'string') || !present(value) || (typeof value === 'string' && !value.trim()) || !Number.isFinite(Number(value))) throw Error(`${label}必须是有效数值`)
|
||||
return Number(value)
|
||||
}
|
||||
function fieldValue(field, value, label = field.label) {
|
||||
if (field.type === 'number') {
|
||||
const result = number(value, label)
|
||||
if ((has(field, 'min') && result < field.min) || (has(field, 'max') && result > field.max)) throw Error(`${label}超出允许范围`)
|
||||
return result
|
||||
}
|
||||
if (field.type === 'boolean') {
|
||||
if (typeof value !== 'boolean') throw Error(`${label}必须为是或否`)
|
||||
return value
|
||||
}
|
||||
if (typeof value !== 'string' || value.length > 500) throw Error(`${label}最多填写 500 个字符`)
|
||||
return value
|
||||
}
|
||||
|
||||
export function dataTypeDraft(type) {
|
||||
return {
|
||||
id: type?.id || '', builtin: type?.builtin === true, revision: type?.revision || 0,
|
||||
name: type?.name || '',
|
||||
fields: (type?.fields || []).map(field => ({key: field.key, label: field.label, type: field.type, unit: field.unit || '',
|
||||
min: field.min ?? '', max: field.max ?? '', hasDefault: has(field, 'default'), defaultValue: fallback(field)})),
|
||||
}
|
||||
}
|
||||
|
||||
export function dataTypePayload(draft) {
|
||||
if (draft.builtin) throw Error('内置数据类型只读,请新建自定义数据类型')
|
||||
if (draft.id && !/^[a-f0-9]{16}$/.test(draft.id)) throw Error('数据类型标识无效')
|
||||
if (!Array.isArray(draft.fields) || draft.fields.length > 24) throw Error('每个类型最多定义 24 个参数字段')
|
||||
const seen = new Set()
|
||||
const fields = draft.fields.map(row => {
|
||||
const key = String(row.key || '').trim(), normalized = key.toLowerCase().replaceAll('_', '')
|
||||
if (!/^[A-Za-z][A-Za-z0-9_]{0,39}$/.test(key) || reserved.has(normalized) || /password|passphrase|token|secret|credential|privatekey|apikey|accesskey/.test(normalized)) throw Error('字段标识须使用字母、数字或下划线,不能使用运行状态、操作或凭据字段')
|
||||
if (seen.has(key.toLowerCase())) throw Error(`参数字段“${key}”重复`)
|
||||
seen.add(key.toLowerCase())
|
||||
if (!kinds.includes(row.type)) throw Error('参数字段类型无效')
|
||||
const field = {key, label: text(row.label, '参数名称', 80), type: row.type}
|
||||
const unit = text(row.unit || '', '单位', 20, false)
|
||||
if (unit) field.unit = unit
|
||||
if (row.type === 'number') {
|
||||
if (present(row.min)) field.min = number(row.min, field.label + '最小值')
|
||||
if (present(row.max)) field.max = number(row.max, field.label + '最大值')
|
||||
if (has(field, 'min') && has(field, 'max') && field.min > field.max) throw Error(`${field.label}最小值不能大于最大值`)
|
||||
}
|
||||
const value = fieldValue(field, row.hasDefault ? row.defaultValue : fallback(field), field.label + '默认值')
|
||||
if (row.hasDefault) field.default = value
|
||||
return field
|
||||
})
|
||||
const payload = {action: 'save', name: text(draft.name, '数据类型名称', 80), fields}
|
||||
if (draft.id) {
|
||||
if (!Number.isInteger(draft.revision) || draft.revision < 1) throw Error('请重新读取数据类型版本')
|
||||
payload.id = draft.id; payload.revision = draft.revision
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
export function typeDraft(type) {
|
||||
return {id: type?.id || '', builtin: type?.builtin === true, revision: type?.revision || 0, name: type?.name || '',
|
||||
dataTypeId: type?.dataTypeId || 'generic', fbType: type?.fbType || 'manual.v1'}
|
||||
}
|
||||
export function typePayload(draft, blocks, dataTypes = []) {
|
||||
if (draft.builtin) throw Error('内置设备类型只读,请复制为自定义类型')
|
||||
if (draft.id && !/^[a-f0-9]{16}$/.test(draft.id)) throw Error('设备类型标识无效')
|
||||
const block = blocks.find(item => item.id === draft.fbType)
|
||||
if (!block) throw Error('请选择已注册的执行驱动')
|
||||
const dataType = dataTypes.find(item => item.id === draft.dataTypeId)
|
||||
if (!dataType || (block.id === 'computer.power.v1') !== (dataType.id === 'computer-power')) throw Error('数据类型不适用于当前执行驱动')
|
||||
const payload = {action: 'save', name: text(draft.name, '设备类型名称', 80), fbType: block.id, dataTypeId: dataType.id,
|
||||
dataTypeRevision: dataType.revision}
|
||||
if (draft.id) {
|
||||
if (!Number.isInteger(draft.revision) || draft.revision < 1) throw Error('请重新读取设备类型版本')
|
||||
payload.id = draft.id; payload.revision = draft.revision
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
export function viewTypeDraft(type) {
|
||||
return {id: type?.id || '', builtin: type?.builtin === true, revision: type?.revision || 0,
|
||||
name: type?.name || '', dataTypeId: type?.dataTypeId || 'generic'}
|
||||
}
|
||||
export function viewTypePayload(draft, dataTypes) {
|
||||
if (draft.builtin) throw Error('内置视图类型只读,请新建自定义视图类型')
|
||||
if (draft.id && !/^[a-f0-9]{16}$/.test(draft.id)) throw Error('视图类型标识无效')
|
||||
const dataType = dataTypes.find(item => item.id === draft.dataTypeId)
|
||||
if (!dataType) throw Error('请选择可用的数据类型')
|
||||
const payload = {action: 'save', name: text(draft.name, '视图类型名称', 80), dataTypeId: dataType.id, dataTypeRevision: dataType.revision, renderer: 'properties'}
|
||||
if (draft.id) {
|
||||
if (!Number.isInteger(draft.revision) || draft.revision < 1) throw Error('请重新读取视图类型版本')
|
||||
payload.id = draft.id; payload.revision = draft.revision
|
||||
}
|
||||
return payload
|
||||
}
|
||||
export function compatibleViewTypes(types, dataTypeId) {
|
||||
return (types || []).filter(type => type.dataTypeId === dataTypeId)
|
||||
}
|
||||
|
||||
export function initialProperties(type, properties = {}) {
|
||||
return Object.fromEntries((type?.fields || []).map(field => [field.key, has(properties || {}, field.key) ? properties[field.key] : fallback(field)]))
|
||||
}
|
||||
export function bindingPayload(deviceId, type, values = {}) {
|
||||
if (!deviceId || !type?.id) throw Error('请选择设备与设备类型')
|
||||
const properties = initialProperties(type, values)
|
||||
for (const field of type.fields || []) properties[field.key] = fieldValue(field, properties[field.key])
|
||||
return {action: 'bind', deviceId, typeId: type.id, typeRevision: type.revision, properties}
|
||||
}
|
||||
export function propertyRows(type, properties) {
|
||||
const values = initialProperties(type, properties)
|
||||
return (type?.fields || []).map(field => ({key: field.key, label: field.label,
|
||||
value: field.type === 'boolean' ? values[field.key] === true ? '是' : '否' : String(values[field.key] ?? ''), unit: field.unit || ''}))
|
||||
}
|
||||
|
||||
function createSession({request, onChange = () => {}, endpoint, shape, requiredContext = '', mapListing = value => value}) {
|
||||
const empty = () => ({...shape, canManage: false, pending: false, error: '', message: ''})
|
||||
let state = empty(), context = {}, key = '', generation = 0, disposed = false
|
||||
const emit = patch => {state = {...state, ...patch}; onChange(state)}
|
||||
const active = () => !disposed && context.active === true && context.loggedIn === true && !!context.familyId && (!requiredContext || !!context[requiredContext])
|
||||
const current = version => version === generation && active()
|
||||
const apply = raw => {
|
||||
const value = mapListing(raw)
|
||||
const patch = {canManage: value?.canManage === true}
|
||||
for (const field of Object.keys(shape)) patch[field] = Array.isArray(value?.[field]) ? value[field] : []
|
||||
emit(patch)
|
||||
}
|
||||
function failure(error, clear) {
|
||||
emit({...clear ? empty() : {}, pending: true, error: error?.stale ? '' : error?.message || '操作未完成,请重试'})
|
||||
}
|
||||
async function refresh() {
|
||||
if (!active() || state.pending) return null
|
||||
const version = generation
|
||||
emit({pending: true, error: ''})
|
||||
try {
|
||||
const value = await request(endpoint(context))
|
||||
if (!current(version)) return null
|
||||
apply(value); return value
|
||||
} catch (error) {
|
||||
if (current(version)) failure(error, true)
|
||||
return null
|
||||
} finally {if (current(version)) emit({pending: false})}
|
||||
}
|
||||
async function mutate(build, message, listing = true) {
|
||||
if (!active() || state.pending || !state.canManage) return null
|
||||
let payload
|
||||
try {payload = build(state, context)} catch (error) {emit({error: error.message, message: ''}); return null}
|
||||
const version = generation
|
||||
emit({pending: true, error: '', message: ''})
|
||||
try {
|
||||
const value = await request(endpoint(context).split('?')[0], payload)
|
||||
if (!current(version)) return null
|
||||
if (listing) apply(value)
|
||||
emit({message}); return value
|
||||
} catch (error) {
|
||||
if (current(version)) failure(error, error?.stale || [401, 403, 404].includes(error?.status))
|
||||
return null
|
||||
} finally {if (current(version)) emit({pending: false})}
|
||||
}
|
||||
function setContext(value) {
|
||||
const next = JSON.stringify([value.familyId, value.session, value.userId, value.authMarker, value.loggedIn, value.active, value.deviceId, value.dataInstanceId, value.dataTypeId])
|
||||
if (disposed || key === next) return
|
||||
generation++; key = next; context = {...value}; emit(empty())
|
||||
if (active()) refresh()
|
||||
}
|
||||
function dispose() {disposed = true; generation++; emit(empty())}
|
||||
return {setContext, refresh, mutate, dispose}
|
||||
}
|
||||
|
||||
export function createDeviceTypeSession(options) {
|
||||
const client = createSession({...options, endpoint: () => '/api/device-types', shape: {types: [], blocks: []}})
|
||||
return {
|
||||
setContext: client.setContext, refresh: client.refresh, dispose: client.dispose,
|
||||
save: (draft, dataTypes) => client.mutate(state => typePayload(draft, state.blocks, dataTypes), '设备类型(FB)已保存'),
|
||||
bind: (deviceId, typeId, values) => client.mutate((state, context) => {
|
||||
if (context.deviceId && context.deviceId !== deviceId) throw Error('设备已变化,请重新操作')
|
||||
return bindingPayload(deviceId, state.types.find(type => type.id === typeId), values)
|
||||
}, '设备类型与参数已保存', false),
|
||||
}
|
||||
}
|
||||
|
||||
export function createDataTypeSession(options) {
|
||||
const client = createSession({...options, endpoint: () => '/api/data-types', shape: {types: []}})
|
||||
return {setContext: client.setContext, refresh: client.refresh, dispose: client.dispose,
|
||||
save: draft => client.mutate(() => dataTypePayload(draft), '数据类型已保存')}
|
||||
}
|
||||
|
||||
export function createViewTypeSession(options) {
|
||||
const client = createSession({...options, endpoint: () => '/api/view-types', shape: {types: []}})
|
||||
return {setContext: client.setContext, refresh: client.refresh, dispose: client.dispose,
|
||||
save: (draft, dataTypes) => client.mutate(() => viewTypePayload(draft, dataTypes), '视图类型已保存')}
|
||||
}
|
||||
|
||||
export function createDeviceViewSession(options) {
|
||||
const client = createSession({...options, endpoint: context => '/api/device-views?dataInstanceId=' + encodeURIComponent(context.dataInstanceId), shape: {items: []}, requiredContext: 'dataInstanceId',
|
||||
mapListing: value => ({...value, items: Array.isArray(value?.items) ? value.items.map(row => ({...row, dataInstanceId: row.dataInstanceId || row.deviceId, viewTypeId: row.viewTypeId || row.templateId})) : []})})
|
||||
function existing(state, context, id) {
|
||||
const item = state.items.find(row => row.id === id && row.dataInstanceId === context.dataInstanceId)
|
||||
if (!item || !Number.isInteger(item.revision)) throw Error('该视图已变化,请重新读取后操作')
|
||||
return item
|
||||
}
|
||||
return {
|
||||
setContext(value) {const {deviceId, ...canonical} = value; client.setContext({...canonical, dataInstanceId: canonical.dataInstanceId || deviceId})},
|
||||
refresh: client.refresh, dispose: client.dispose,
|
||||
save: (draft, viewTypes) => client.mutate((state, context) => {
|
||||
const viewType = compatibleViewTypes(viewTypes, context.dataTypeId).find(type => type.id === draft.viewTypeId)
|
||||
if (!viewType) throw Error('请选择与此数据实例的数据类型一致的视图类型')
|
||||
const payload = {action: 'save', dataInstanceId: context.dataInstanceId, viewTypeId: viewType.id, title: text(draft.title, '视图名称', 80)}
|
||||
if (draft.id) {const item = existing(state, context, draft.id); payload.id = item.id; payload.revision = Number.isInteger(draft.revision) ? draft.revision : item.revision}
|
||||
return payload
|
||||
}, '视图实例已保存'),
|
||||
remove: id => client.mutate((state, context) => {
|
||||
const item = existing(state, context, id)
|
||||
return {action: 'delete', id: item.id, revision: item.revision}
|
||||
}, '视图实例已删除'),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user