feat(iot):增加 modbus 配置 50%

This commit is contained in:
YunaiV
2026-02-14 09:19:43 +08:00
parent 722afc85df
commit 38597dd19d
11 changed files with 1245 additions and 12 deletions

View File

@@ -0,0 +1,30 @@
import { requestClient } from '#/api/request';
export namespace IotDeviceModbusConfigApi {
/** Modbus 连接配置 VO */
export interface ModbusConfig {
id?: number; // 主键
deviceId: number; // 设备编号
ip: string; // Modbus 服务器 IP 地址
port: number; // Modbus 服务器端口
slaveId: number; // 从站地址
timeout: number; // 连接超时时间,单位:毫秒
retryInterval: number; // 重试间隔,单位:毫秒
mode: number; // 模式
frameFormat: number; // 帧格式
status: number; // 状态
}
}
/** 获取设备的 Modbus 连接配置 */
export function getModbusConfig(deviceId: number) {
return requestClient.get<IotDeviceModbusConfigApi.ModbusConfig>(
'/iot/device-modbus-config/get',
{ params: { deviceId } },
);
}
/** 保存 Modbus 连接配置 */
export function saveModbusConfig(data: IotDeviceModbusConfigApi.ModbusConfig) {
return requestClient.post('/iot/device-modbus-config/save', data);
}

View File

@@ -0,0 +1,56 @@
import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
export namespace IotDeviceModbusPointApi {
/** Modbus 点位配置 VO */
export interface ModbusPoint {
id?: number; // 主键
deviceId: number; // 设备编号
thingModelId?: number; // 物模型属性编号
identifier: string; // 属性标识符
name: string; // 属性名称
functionCode?: number; // Modbus 功能码
registerAddress?: number; // 寄存器起始地址
registerCount?: number; // 寄存器数量
byteOrder?: string; // 字节序
rawDataType?: string; // 原始数据类型
scale: number; // 缩放因子
pollInterval: number; // 轮询间隔,单位:毫秒
status: number; // 状态
}
}
/** 获取设备的 Modbus 点位分页 */
export function getModbusPointPage(params: PageParam) {
return requestClient.get<PageResult<IotDeviceModbusPointApi.ModbusPoint>>(
'/iot/device-modbus-point/page',
{ params },
);
}
/** 获取 Modbus 点位详情 */
export function getModbusPoint(id: number) {
return requestClient.get<IotDeviceModbusPointApi.ModbusPoint>(
`/iot/device-modbus-point/get?id=${id}`,
);
}
/** 创建 Modbus 点位配置 */
export function createModbusPoint(
data: IotDeviceModbusPointApi.ModbusPoint,
) {
return requestClient.post('/iot/device-modbus-point/create', data);
}
/** 更新 Modbus 点位配置 */
export function updateModbusPoint(
data: IotDeviceModbusPointApi.ModbusPoint,
) {
return requestClient.put('/iot/device-modbus-point/update', data);
}
/** 删除 Modbus 点位配置 */
export function deleteModbusPoint(id: number) {
return requestClient.delete(`/iot/device-modbus-point/delete?id=${id}`);
}

View File

@@ -10,7 +10,7 @@ export namespace IotProductApi {
productKey?: string; // 产品标识
productSecret?: string; // 产品密钥
protocolId?: number; // 协议编号
protocolType?: number; // 接入协议类型
protocolType?: string; // 协议类型
categoryId?: number; // 产品所属品类标识符
categoryName?: string; // 产品所属品类名称
icon?: string; // 产品图标
@@ -19,7 +19,7 @@ export namespace IotProductApi {
status?: number; // 产品状态
deviceType?: number; // 设备类型
netType?: number; // 联网方式
codecType?: string; // 数据格式(编解码器类型
serializeType?: string; // 序列化类型
dataFormat?: number; // 数据格式
validateType?: number; // 认证方式
registerEnabled?: boolean; // 是否开启动态注册
@@ -28,6 +28,25 @@ export namespace IotProductApi {
}
}
// IoT 协议类型枚举
export enum ProtocolTypeEnum {
COAP = 'coap',
EMQX = 'emqx',
HTTP = 'http',
MODBUS_TCP_CLIENT = 'modbus_tcp_client',
MODBUS_TCP_SERVER = 'modbus_tcp_server',
MQTT = 'mqtt',
TCP = 'tcp',
UDP = 'udp',
WEBSOCKET = 'websocket',
}
// IoT 序列化类型枚举
export enum SerializeTypeEnum {
BINARY = 'binary',
JSON = 'json',
}
/** 查询产品分页 */
export function getProductPage(params: PageParam) {
return requestClient.get<PageResult<IotProductApi.Product>>(

View File

@@ -12,13 +12,14 @@ import { DeviceTypeEnum } from '@vben/constants';
import { message, Tabs } from 'ant-design-vue';
import { getDevice } from '#/api/iot/device/device';
import { getProduct } from '#/api/iot/product/product';
import { getProduct, ProtocolTypeEnum } from '#/api/iot/product/product';
import { getThingModelListByProductId } from '#/api/iot/thingmodel';
import DeviceDetailConfig from './modules/config.vue';
import DeviceDetailsHeader from './modules/header.vue';
import DeviceDetailsInfo from './modules/info.vue';
import DeviceDetailsMessage from './modules/message.vue';
import DeviceModbusConfig from './modules/modbus-config.vue';
import DeviceDetailsSimulator from './modules/simulator.vue';
import DeviceDetailsSubDevice from './modules/sub-device.vue';
import DeviceDetailsThingModel from './modules/thing-model.vue';
@@ -141,6 +142,23 @@ onMounted(async () => {
@success="() => getDeviceData(id)"
/>
</Tabs.TabPane>
<Tabs.TabPane
v-if="
[
ProtocolTypeEnum.MODBUS_TCP_CLIENT,
ProtocolTypeEnum.MODBUS_TCP_SERVER,
].includes(product.protocolType as ProtocolTypeEnum)
"
key="modbus"
tab="Modbus 配置"
>
<DeviceModbusConfig
v-if="activeTab === 'modbus'"
:device="device"
:product="product"
:thing-model-list="thingModelList"
/>
</Tabs.TabPane>
</Tabs>
</Page>
</template>

View File

@@ -0,0 +1,225 @@
<!-- Modbus 连接配置弹窗 -->
<script lang="ts" setup>
import type { IotDeviceModbusConfigApi } from '#/api/iot/device/modbus/config';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { message } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
import { saveModbusConfig } from '#/api/iot/device/modbus/config';
import { ProtocolTypeEnum } from '#/api/iot/product/product';
import {
ModbusFrameFormatEnum,
ModbusModeEnum,
} from '#/views/iot/utils/constants';
defineOptions({ name: 'DeviceModbusConfigForm' });
const emit = defineEmits(['success']);
const formData = ref<IotDeviceModbusConfigApi.ModbusConfig>();
const deviceId = ref<number>(0);
const protocolType = ref<string>('');
const isClient = computed(
() => protocolType.value === ProtocolTypeEnum.MODBUS_TCP_CLIENT,
); // 是否为 Client 模式
const isServer = computed(
() => protocolType.value === ProtocolTypeEnum.MODBUS_TCP_SERVER,
); // 是否为 Server 模式
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'ip',
label: 'IP 地址',
component: 'Input',
componentProps: {
placeholder: '请输入 Modbus 服务器 IP 地址',
},
dependencies: {
triggerFields: [''],
show: () => isClient.value, // Client 模式专有字段IP 地址
},
rules: z.string().min(1, '请输入 IP 地址').optional(),
},
{
fieldName: 'port',
label: '端口',
component: 'InputNumber',
componentProps: {
placeholder: '请输入端口',
min: 1,
max: 65_535,
},
dependencies: {
triggerFields: [''],
show: () => isClient.value, // Client 模式专有字段:端口
},
rules: z.number().min(1).max(65_535).optional(),
},
{
fieldName: 'slaveId',
label: '从站地址',
component: 'InputNumber',
componentProps: {
placeholder: '请输入从站地址,范围 1-247',
min: 1,
max: 247,
},
rules: z.number().min(1, '请输入从站地址').max(247),
},
{
fieldName: 'timeout',
label: '连接超时(ms)',
component: 'InputNumber',
componentProps: {
placeholder: '请输入连接超时时间',
min: 1000,
step: 1000,
},
dependencies: {
triggerFields: [''],
show: () => isClient.value, // Client 模式专有字段:连接超时
},
rules: z.number().min(1000).optional(),
},
{
fieldName: 'retryInterval',
label: '重试间隔(ms)',
component: 'InputNumber',
componentProps: {
placeholder: '请输入重试间隔',
min: 1000,
step: 1000,
},
dependencies: {
triggerFields: [''],
show: () => isClient.value, // Client 模式专有字段:重试间隔
},
rules: z.number().min(1000).optional(),
},
{
fieldName: 'mode',
label: '工作模式',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.IOT_MODBUS_MODE, 'number'),
},
dependencies: {
triggerFields: [''],
show: () => isServer.value, // Server 模式专有字段:工作模式
},
rules: 'required',
},
{
fieldName: 'frameFormat',
label: '帧格式',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.IOT_MODBUS_FRAME_FORMAT, 'number'),
},
dependencies: {
triggerFields: [''],
show: () => isServer.value, // Server 模式专有字段:帧格式
},
rules: 'required',
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
],
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// TODO @AI这里的处理可以参考 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/system/user/modules/form.vue 的注释风格;
modalApi.lock();
const data =
(await formApi.getValues()) as IotDeviceModbusConfigApi.ModbusConfig;
try {
data.deviceId = deviceId.value;
await saveModbusConfig(data);
message.success('保存成功');
await modalApi.close();
emit('success');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
const data = modalApi.getData<{
config?: IotDeviceModbusConfigApi.ModbusConfig;
deviceId: number;
protocolType: string;
}>();
if (!data) return;
// TODO @AI这里的处理可以参考 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/system/user/modules/form.vue 的注释风格;
deviceId.value = data.deviceId;
protocolType.value = data.protocolType;
if (data.config && data.config.id) {
// 编辑模式:加载已有配置
formData.value = { ...data.config };
await formApi.setValues(formData.value);
} else {
// 新增模式:设置默认值
await formApi.setValues({
ip: '',
port: 502,
slaveId: 1,
timeout: 3000,
retryInterval: 10_000,
mode: ModbusModeEnum.POLLING,
frameFormat: ModbusFrameFormatEnum.MODBUS_TCP,
status: 0,
});
}
},
});
</script>
<template>
<Modal title="编辑 Modbus 连接配置" class="w-[600px]">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,367 @@
<!-- Modbus 配置 -->
<script lang="ts" setup>
import type { VbenFormSchema, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { IotDeviceApi } from '#/api/iot/device/device';
import type { IotDeviceModbusConfigApi } from '#/api/iot/device/modbus/config';
import type { IotDeviceModbusPointApi } from '#/api/iot/device/modbus/point';
import type { IotProductApi } from '#/api/iot/product/product';
import type { ThingModelData } from '#/api/iot/thingmodel';
import type { DescriptionItemSchema } from '#/components/description';
import { computed, h, onMounted, ref } from 'vue';
import { confirm, useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { Button, message, Tag } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { getModbusConfig } from '#/api/iot/device/modbus/config';
import {
deleteModbusPoint,
getModbusPointPage,
} from '#/api/iot/device/modbus/point';
import { ProtocolTypeEnum } from '#/api/iot/product/product';
import { useDescription } from '#/components/description';
import { DictTag } from '#/components/dict-tag';
import { ModbusFunctionCodeOptions } from '#/views/iot/utils/constants';
import DeviceModbusConfigForm from './modbus-config-form.vue';
import DeviceModbusPointForm from './modbus-point-form.vue';
defineOptions({ name: 'DeviceModbusConfig' });
const props = defineProps<{
device: IotDeviceApi.Device;
product: IotProductApi.Product;
thingModelList: ThingModelData[];
}>();
// ======================= 连接配置 =======================
const isClient = computed(
() => props.product.protocolType === ProtocolTypeEnum.MODBUS_TCP_CLIENT,
); // 是否为 Client 模式
const isServer = computed(
() => props.product.protocolType === ProtocolTypeEnum.MODBUS_TCP_SERVER,
); // 是否为 Server 模式
const modbusConfig = ref<IotDeviceModbusConfigApi.ModbusConfig>(
{} as IotDeviceModbusConfigApi.ModbusConfig,
); // 连接配置
/** 连接配置 Description Schema */
function useConfigDescriptionSchema(): DescriptionItemSchema[] {
return [
// Client 模式专有字段
{
field: 'ip',
label: 'IP 地址',
show: () => isClient.value,
},
{
field: 'port',
label: '端口',
show: () => isClient.value,
},
// 公共字段
{
field: 'slaveId',
label: '从站地址',
},
// Client 模式专有字段
{
field: 'timeout',
label: '连接超时',
show: () => isClient.value,
render: (val) => (val ? `${val} ms` : '-'),
},
{
field: 'retryInterval',
label: '重试间隔',
show: () => isClient.value,
render: (val) => (val ? `${val} ms` : '-'),
},
// Server 模式专有字段
{
field: 'mode',
label: '工作模式',
show: () => isServer.value,
render: (val) =>
h(DictTag, { type: DICT_TYPE.IOT_MODBUS_MODE, value: val }),
},
{
field: 'frameFormat',
label: '帧格式',
show: () => isServer.value,
render: (val) =>
h(DictTag, { type: DICT_TYPE.IOT_MODBUS_FRAME_FORMAT, value: val }),
},
// 公共字段
{
field: 'status',
label: '状态',
render: (val) =>
h(DictTag, { type: DICT_TYPE.COMMON_STATUS, value: val }),
},
];
}
const [ConfigDescriptions] = useDescription({
title: '连接配置',
column: 3,
bordered: true,
schema: useConfigDescriptionSchema(),
});
/** 获取连接配置 */
async function loadModbusConfig() {
modbusConfig.value = await getModbusConfig(props.device.id!);
}
/** 编辑连接配置 - 使用 useVbenModal */
const [ConfigFormModal, configFormModalApi] = useVbenModal({
connectedComponent: DeviceModbusConfigForm,
destroyOnClose: true,
});
/** 打开编辑连接配置弹窗 */
function handleEditConfig() {
configFormModalApi
.setData({
config: modbusConfig.value,
deviceId: props.device.id!,
protocolType: props.product.protocolType!,
})
.open();
}
// ======================= 点位配置 =======================
/** 格式化功能码 */
function formatFunctionCode(code: number) {
const option = ModbusFunctionCodeOptions.find((item) => item.value === code);
return option ? option.label : `${code}`;
}
/** 格式化寄存器地址为十六进制 */
function formatRegisterAddress(address: number) {
return `0x${address.toString(16).toUpperCase().padStart(4, '0')}`;
}
/** 点位搜索表单 Schema */
function usePointFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '属性名称',
component: 'Input',
componentProps: {
placeholder: '请输入属性名称',
allowClear: true,
},
},
{
fieldName: 'identifier',
label: '标识符',
component: 'Input',
componentProps: {
placeholder: '请输入标识符',
allowClear: true,
},
},
];
}
/** 点位列表列配置 */
function usePointColumns(): VxeTableGridOptions['columns'] {
return [
{ field: 'name', title: '属性名称', minWidth: 100 },
{
field: 'identifier',
title: '标识符',
minWidth: 100,
slots: { default: 'identifier' },
},
{
field: 'functionCode',
title: '功能码',
minWidth: 140,
formatter: ({ cellValue }) => formatFunctionCode(cellValue),
},
{
field: 'registerAddress',
title: '寄存器地址',
minWidth: 100,
formatter: ({ cellValue }) => formatRegisterAddress(cellValue),
},
{ field: 'registerCount', title: '寄存器数量', minWidth: 90 },
{
field: 'rawDataType',
title: '数据类型',
minWidth: 90,
slots: { default: 'rawDataType' },
},
{ field: 'byteOrder', title: '字节序', minWidth: 80 },
{ field: 'scale', title: '缩放因子', minWidth: 80 },
{
field: 'pollInterval',
title: '轮询间隔',
minWidth: 90,
formatter: ({ cellValue }) => `${cellValue} ms`,
},
{
field: 'status',
title: '状态',
minWidth: 80,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
title: '操作',
width: 140,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
const [Grid, gridApi] = useVbenVxeGrid<IotDeviceModbusPointApi.ModbusPoint>({
formOptions: {
schema: usePointFormSchema(),
submitOnChange: true,
},
gridOptions: {
columns: usePointColumns(),
height: 'auto',
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getModbusPointPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
deviceId: props.device.id,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
},
});
/** 新增点位 - 使用 useVbenModal */
const [PointFormModal, pointFormModalApi] = useVbenModal({
connectedComponent: DeviceModbusPointForm,
destroyOnClose: true,
});
/** 打开新增点位弹窗 */
function handleAddPoint() {
pointFormModalApi
.setData({
deviceId: props.device.id!,
thingModelList: props.thingModelList,
})
.open();
}
/** 编辑点位 */
function handleEditPoint(row: IotDeviceModbusPointApi.ModbusPoint) {
pointFormModalApi
.setData({
id: row.id,
deviceId: props.device.id!,
thingModelList: props.thingModelList,
})
.open();
}
/** 删除点位 */
async function handleDeletePoint(row: IotDeviceModbusPointApi.ModbusPoint) {
await confirm({ content: `确定要删除点位【${row.name}】吗?` });
await deleteModbusPoint(row.id!);
message.success('删除成功');
await gridApi.query();
}
/** 刷新点位列表 */
function handlePointSuccess() {
gridApi.query();
}
/** 初始化 */
onMounted(async () => {
await loadModbusConfig();
});
</script>
<template>
<div>
<!-- 连接配置区域 -->
<ConfigDescriptions :data="modbusConfig" class="mb-4">
<template #extra>
<Button type="primary" @click="handleEditConfig">编辑</Button>
</template>
</ConfigDescriptions>
<!-- 点位配置区域 -->
<!-- TODO @AI这里高度一直涨怎么限制下 -->
<Grid table-title="点位配置">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: '新增点位',
type: 'primary',
icon: ACTION_ICON.ADD,
onClick: handleAddPoint,
},
]"
/>
</template>
<!-- TODO@AI这里可以在 data 里声明么 -->
<template #identifier="{ row }">
<Tag color="blue">{{ row.identifier }}</Tag>
</template>
<!-- TODO@AI这里可以在 data 里声明么 -->
<template #rawDataType="{ row }">
<Tag>{{ row.rawDataType }}</Tag>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '编辑',
type: 'link',
onClick: () => handleEditPoint(row),
},
{
label: '删除',
type: 'link',
danger: true,
popConfirm: {
title: `确定要删除点位【${row.name}】吗?`,
confirm: () => handleDeletePoint(row),
},
},
]"
/>
</template>
</Grid>
<!-- 连接配置弹窗 -->
<ConfigFormModal @success="loadModbusConfig" />
<!-- 点位表单弹窗 -->
<PointFormModal @success="handlePointSuccess" />
</div>
</template>

View File

@@ -0,0 +1,365 @@
<!-- Modbus 点位表单弹窗 -->
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { IotDeviceModbusPointApi } from '#/api/iot/device/modbus/point';
import type { ThingModelData } from '#/api/iot/thingmodel';
import { computed, h, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { message } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
import {
createModbusPoint,
getModbusPoint,
updateModbusPoint,
} from '#/api/iot/device/modbus/point';
import {
getByteOrderOptions,
IoTThingModelTypeEnum,
ModbusFunctionCodeOptions,
ModbusRawDataTypeOptions,
} from '#/views/iot/utils/constants';
defineOptions({ name: 'DeviceModbusPointForm' });
const emit = defineEmits(['success']);
const formData = ref<IotDeviceModbusPointApi.ModbusPoint>();
const deviceId = ref<number>(0);
const thingModelList = ref<ThingModelData[]>([]);
const getTitle = computed(() => {
return formData.value?.id ? '编辑点位' : '新增点位';
});
/** 筛选属性类型的物模型 */
// TODO @AI这里 linter 报错TS2367: This comparison appears to be unintentional because the types string | undefined and number have no overlap.
const propertyList = computed(() => {
return thingModelList.value.filter(
(item) => item.type === IoTThingModelTypeEnum.PROPERTY,
);
});
/** 当前选中的数据类型 */
const currentRawDataType = ref<string>('');
/** 当前字节序选项(根据数据类型动态变化) */
const currentByteOrderOptions = computed(() => {
if (!currentRawDataType.value) {
return [];
}
return getByteOrderOptions(currentRawDataType.value).map((item) => ({
value: item.value,
label: `${item.label} - ${item.description}`,
}));
});
/** 表单 Schema */
function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'identifier',
dependencies: {
triggerFields: [''], // 隐藏字段identifier由物模型属性选择自动填充
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
dependencies: {
triggerFields: [''], // 隐藏字段name由物模型属性选择自动填充
show: () => false,
},
},
{
fieldName: 'thingModelId',
label: '物模型属性',
component: 'Select',
componentProps: {
placeholder: '请选择物模型属性',
showSearch: true,
// TODO @AI不用这种 => 格式,看起来不够清晰。只处理这里的。
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
options: propertyList.value.map((item) => ({
value: item.id,
label: `${item.name} (${item.identifier})`,
})),
},
rules: 'required',
},
{
fieldName: 'functionCode',
label: '功能码',
component: 'Select',
componentProps: {
placeholder: '请选择功能码',
options: ModbusFunctionCodeOptions.map((item) => ({
value: item.value,
label: item.label,
})),
},
rules: 'required',
},
{
fieldName: 'registerAddress',
label: '寄存器地址',
component: 'InputNumber',
componentProps: {
placeholder: '请输入寄存器地址',
min: 0,
max: 65_535,
},
rules: z.number().min(0, '请输入寄存器地址').max(65_535),
suffix: () => {
const values = formApi.form.values;
const addr = values?.registerAddress;
if (addr === undefined || addr === null) return '';
return h(
'span',
{ class: 'text-gray-400' },
`0x${Number(addr).toString(16).toUpperCase().padStart(4, '0')}`,
);
},
},
{
fieldName: 'registerCount',
label: '寄存器数量',
component: 'InputNumber',
componentProps: {
placeholder: '请输入寄存器数量',
min: 1,
max: 125,
},
rules: z.number().min(1, '请输入寄存器数量').max(125),
},
{
fieldName: 'rawDataType',
label: '原始数据类型',
component: 'Select',
componentProps: {
placeholder: '请选择数据类型',
options: ModbusRawDataTypeOptions.map((item) => ({
value: item.value,
label: `${item.label} - ${item.description}`,
})),
},
rules: 'required',
},
{
fieldName: 'byteOrder',
label: '字节序',
component: 'Select',
componentProps: {
placeholder: '请选择字节序',
options: currentByteOrderOptions.value,
},
},
{
fieldName: 'scale',
label: '缩放因子',
component: 'InputNumber',
componentProps: {
placeholder: '请输入缩放因子',
precision: 6,
step: 0.1,
},
defaultValue: 1,
},
{
fieldName: 'pollInterval',
label: '轮询间隔(ms)',
component: 'InputNumber',
componentProps: {
placeholder: '请输入轮询间隔',
min: 100,
step: 1000,
},
rules: z.number().min(100, '请输入轮询间隔'),
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
handleValuesChange: async (_values, changedFields) => {
// 物模型属性变化:自动填充 identifier 和 name
if (changedFields.includes('thingModelId')) {
const thingModelId = await formApi.getFieldValue('thingModelId');
const thingModel = thingModelList.value.find(
(item) => item.id === thingModelId,
);
if (thingModel) {
await formApi.setFieldValue('identifier', thingModel.identifier);
await formApi.setFieldValue('name', thingModel.name);
}
}
// 数据类型变化:自动设置寄存器数量和字节序
if (changedFields.includes('rawDataType')) {
const rawDataType = await formApi.getFieldValue('rawDataType');
currentRawDataType.value = rawDataType || '';
if (rawDataType) {
// 根据数据类型自动设置寄存器数量
const option = ModbusRawDataTypeOptions.find(
(item) => item.value === rawDataType,
);
if (option && option.registerCount > 0) {
await formApi.setFieldValue('registerCount', option.registerCount);
}
// 重置字节序为第一个选项
const byteOrderOptions = getByteOrderOptions(rawDataType);
if (byteOrderOptions.length > 0) {
await formApi.setFieldValue('byteOrder', byteOrderOptions[0]!.value);
}
// 更新字节序下拉选项
formApi.updateSchema([
{
fieldName: 'byteOrder',
componentProps: {
options: byteOrderOptions.map((item) => ({
value: item.value,
label: `${item.label} - ${item.description}`,
})),
},
},
]);
}
}
},
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
// TODO @AI这里的处理可以参考 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/system/user/modules/form.vue 的注释风格;
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
const data =
(await formApi.getValues()) as IotDeviceModbusPointApi.ModbusPoint;
try {
data.deviceId = deviceId.value;
await (formData.value?.id
? updateModbusPoint(data)
: createModbusPoint(data));
await modalApi.close();
emit('success');
message.success(formData.value?.id ? '更新成功' : '创建成功');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
currentRawDataType.value = '';
return;
}
// TODO @AI这里的处理可以参考 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/system/user/modules/form.vue 的注释风格;
const data = modalApi.getData<{
deviceId: number;
id?: number;
thingModelList: ThingModelData[];
}>();
if (!data) return;
deviceId.value = data.deviceId;
thingModelList.value = data.thingModelList || [];
// 更新物模型属性下拉选项
const properties = thingModelList.value.filter(
(item) => item.type === IoTThingModelTypeEnum.PROPERTY,
);
formApi.updateSchema([
{
fieldName: 'thingModelId',
componentProps: {
options: properties.map((item) => ({
value: item.id,
label: `${item.name} (${item.identifier})`,
})),
},
},
]);
if (data.id) {
// 编辑模式:加载数据
modalApi.lock();
try {
formData.value = await getModbusPoint(data.id);
// 先设置 rawDataType 以便更新字节序选项
currentRawDataType.value = formData.value.rawDataType || '';
if (formData.value.rawDataType) {
const byteOrderOptions = getByteOrderOptions(
formData.value.rawDataType,
);
formApi.updateSchema([
{
fieldName: 'byteOrder',
componentProps: {
options: byteOrderOptions.map((item) => ({
value: item.value,
label: `${item.label} - ${item.description}`,
})),
},
},
]);
}
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
} else {
// 新增模式:设置默认值
// TODO @AI这个是不是在 data 里处理;
await formApi.setValues({
scale: 1,
pollInterval: 5000,
status: 0,
});
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-[600px]">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -127,16 +127,26 @@ export function useBasicFormSchema(
rules: 'required',
},
{
fieldName: 'codecType',
label: '数据格式',
component: 'RadioGroup',
fieldName: 'protocolType',
label: '协议类型',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.IOT_CODEC_TYPE, 'string'),
buttonStyle: 'solid',
optionType: 'button',
options: getDictOptions(DICT_TYPE.IOT_PROTOCOL_TYPE, 'string'),
placeholder: '请选择协议类型',
},
rules: 'required',
},
{
fieldName: 'serializeType',
label: '序列化类型',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.IOT_SERIALIZE_TYPE, 'string'),
placeholder: '请选择序列化类型',
},
help: 'iot-gateway-server 默认根据接入的协议类型确定数据格式,仅 MQTT、EMQX 协议支持自定义序列化类型',
rules: 'required',
},
// TODO @haohao这个貌似不需要
{
fieldName: 'status',

View File

@@ -57,8 +57,17 @@ async function copyToClipboard(text: string) {
<Descriptions.Item label="创建时间">
{{ formatDate(product.createTime) }}
</Descriptions.Item>
<Descriptions.Item label="数据格式">
{{ product.codecType || '-' }}
<Descriptions.Item label="协议类型">
<DictTag
:type="DICT_TYPE.IOT_PROTOCOL_TYPE"
:value="product.protocolType"
/>
</Descriptions.Item>
<Descriptions.Item label="序列化类型">
<DictTag
:type="DICT_TYPE.IOT_SERIALIZE_TYPE"
:value="product.serializeType"
/>
</Descriptions.Item>
<Descriptions.Item label="产品状态">
<DictTag :type="DICT_TYPE.IOT_PRODUCT_STATUS" :value="product.status" />

View File

@@ -522,3 +522,135 @@ export const JSON_PARAMS_EXAMPLE_VALUES: Record<string, any> = {
[IoTDataSpecsDataTypeEnum.ARRAY]: { display: '[]', value: [] },
DEFAULT: { display: '""', value: '' },
};
// ========== Modbus 通用常量 ==========
/** Modbus 模式枚举 */
export const ModbusModeEnum = {
POLLING: 1, // 云端轮询
ACTIVE_REPORT: 2, // 主动上报
} as const;
/** Modbus 帧格式枚举 */
export const ModbusFrameFormatEnum = {
MODBUS_TCP: 1, // Modbus TCP
MODBUS_RTU: 2, // Modbus RTU
} as const;
/** Modbus 功能码枚举 */
export const ModbusFunctionCodeEnum = {
READ_COILS: 1, // 读线圈
READ_DISCRETE_INPUTS: 2, // 读离散输入
READ_HOLDING_REGISTERS: 3, // 读保持寄存器
READ_INPUT_REGISTERS: 4, // 读输入寄存器
} as const;
/** Modbus 功能码选项 */
export const ModbusFunctionCodeOptions = [
{ value: 1, label: '01 - 读线圈 (Coils)', description: '可读写布尔值' },
{
value: 2,
label: '02 - 读离散输入 (Discrete Inputs)',
description: '只读布尔值',
},
{
value: 3,
label: '03 - 读保持寄存器 (Holding Registers)',
description: '可读写 16 位数据',
},
{
value: 4,
label: '04 - 读输入寄存器 (Input Registers)',
description: '只读 16 位数据',
},
];
/** Modbus 原始数据类型枚举 */
export const ModbusRawDataTypeEnum = {
INT16: 'INT16',
UINT16: 'UINT16',
INT32: 'INT32',
UINT32: 'UINT32',
FLOAT: 'FLOAT',
DOUBLE: 'DOUBLE',
BOOLEAN: 'BOOLEAN',
STRING: 'STRING',
} as const;
/** Modbus 原始数据类型选项 */
export const ModbusRawDataTypeOptions = [
{
value: 'INT16',
label: 'INT16',
description: '有符号16位整数',
registerCount: 1,
},
{
value: 'UINT16',
label: 'UINT16',
description: '无符号16位整数',
registerCount: 1,
},
{
value: 'INT32',
label: 'INT32',
description: '有符号32位整数',
registerCount: 2,
},
{
value: 'UINT32',
label: 'UINT32',
description: '无符号32位整数',
registerCount: 2,
},
{
value: 'FLOAT',
label: 'FLOAT',
description: '32位浮点数',
registerCount: 2,
},
{
value: 'DOUBLE',
label: 'DOUBLE',
description: '64位浮点数',
registerCount: 4,
},
{
value: 'BOOLEAN',
label: 'BOOLEAN',
description: '布尔值',
registerCount: 1,
},
{
value: 'STRING',
label: 'STRING',
description: '字符串',
registerCount: 0,
},
];
/** Modbus 字节序选项 - 16位 */
export const ModbusByteOrder16Options = [
{ value: 'AB', label: 'AB', description: '大端序' },
{ value: 'BA', label: 'BA', description: '小端序' },
];
/** Modbus 字节序选项 - 32位 */
export const ModbusByteOrder32Options = [
{ value: 'ABCD', label: 'ABCD', description: '大端序' },
{ value: 'CDAB', label: 'CDAB', description: '大端字交换' },
{ value: 'DCBA', label: 'DCBA', description: '小端序' },
{ value: 'BADC', label: 'BADC', description: '小端字交换' },
];
/** 根据数据类型获取字节序选项 */
export const getByteOrderOptions = (rawDataType: string) => {
if (['FLOAT', 'INT32', 'UINT32'].includes(rawDataType)) {
return ModbusByteOrder32Options;
}
if (rawDataType === 'DOUBLE') {
// 64 位暂时复用 32 位字节序
return ModbusByteOrder32Options;
}
return ModbusByteOrder16Options;
};

View File

@@ -150,7 +150,7 @@ const AI_DICT = {
const IOT_DICT = {
IOT_ALERT_LEVEL: 'iot_alert_level', // IoT 告警级别
IOT_ALERT_RECEIVE_TYPE: 'iot_alert_receive_type', // IoT 告警接收类型
IOT_CODEC_TYPE: 'iot_codec_type', // IOT 数据格式(编解码器类型
IOT_SERIALIZE_TYPE: 'iot_serialize_type', // IOT 序列化类型
IOT_DATA_FORMAT: 'iot_data_format', // IOT 数据格式
IOT_DATA_SINK_TYPE_ENUM: 'iot_data_sink_type_enum', // IoT 数据流转目的类型
IOT_DATA_TYPE: 'iot_data_type', // IOT 数据类型
@@ -171,6 +171,8 @@ const IOT_DICT = {
IOT_THING_MODEL_UNIT: 'iot_thing_model_unit', // IOT 物模型单位
IOT_UNIT_TYPE: 'iot_unit_type', // IOT 单位类型
IOT_VALIDATE_TYPE: 'iot_validate_type', // IOT 数据校验级别
IOT_MODBUS_MODE: 'iot_modbus_mode', // IoT Modbus 工作模式
IOT_MODBUS_FRAME_FORMAT: 'iot_modbus_frame_format', // IoT Modbus 帧格式
} as const;
/** 字典类型枚举 - 统一导出 */