| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import { APIClient } from "@d8d-appcontainer/api"
- import type { VariablesContext } from "../middlewares.ts";
- import type { DeviceInstance } from "../../client/share/monitorTypes.ts";
- import { DeviceProtocolType } from "../../client/share/monitorTypes.ts";
- import debug from "debug";
- import { modbusRTUConnection } from "../utils/modbus_rtu.ts";
- const log = debug("d8d:device:controller");
- interface ModbusRTUDevice extends DeviceInstance {
- config?: {
- deviceAddress: number;
- ipAddress?: string;
- port?: number;
- baudRate?: number;
- };
- }
- export async function createModbusRTUDevice(c: VariablesContext) {
- try {
- const apiClient = c.get('apiClient');
- const deviceData: ModbusRTUDevice = await c.req.json();
- // 验证协议参数
- if (deviceData.protocol === DeviceProtocolType.MODBUS) {
-
- }
- // 创建设备记录
- await apiClient.database
- .table("device_instances")
- .insert({
- id: deviceData.id,
- type_id: deviceData.type_id,
- protocol: deviceData.protocol,
- address: deviceData.address,
- config: JSON.stringify(deviceData.config || {}),
- collect_interval: deviceData.collect_interval || 60,
- remark: deviceData.remark,
- is_enabled: deviceData.is_enabled ?? 1,
- is_deleted: 0,
- });
- // 查询刚创建的设备
- const [createdDevice] = await apiClient.database
- .table("device_instances")
- .where({ id: deviceData.id });
- return c.json({ data: createdDevice });
- } catch (error: unknown) {
- log("创建设备失败:", error);
- const message = error instanceof Error ? error.message : "未知错误";
- return c.json({ error: `创建设备失败: ${message}` }, 500);
- }
- }
- export async function collectModbusRTUData(c: VariablesContext) {
- try {
- const apiClient = c.get('apiClient');
- const { deviceId } = c.req.param();
- const [device] = await apiClient.database
- .table("device_instances")
- .where({ id: deviceId, is_deleted: 0 });
- if (!device) {
- return c.json({ error: "设备不存在" }, 404);
- }
- if (device.protocol !== DeviceProtocolType.MODBUS) {
- return c.json({ error: "不支持的协议类型" }, 400);
- }
- return c.json({ data: null });
- } catch (error: unknown) {
- log("采集数据失败:", error);
- const message = error instanceof Error ? error.message : "未知错误";
- return c.json({ error: `采集数据失败: ${message}` }, 500);
- }
- }
- export async function testModbusRTUConnection(c: VariablesContext) {
- try {
- const { ip, port, frameHexStrings } = await c.req.json();
-
- if (!ip || !port) {
- return c.json({ error: "缺少IP或端口参数" }, 400);
- }
- const result = await modbusRTUConnection({ ip, port, frameHexStrings });
- return c.json({ result }, 200);
-
- } catch (error: unknown) {
- log("Modbus RTU测试连接错误:", error);
- const message = error instanceof Error ? error.message : "未知错误";
- return c.json({ error: `测试连接失败: ${message}` }, 500);
- }
- }
|