using System; using System.Collections.Generic; using Aging.Infrastructure.Contracts; using log4net; namespace Aging.Infrastructure.Drivers { /// /// 设备驱动工厂。 /// 根据传输协议类型和端点信息创建对应的驱动适配器实例。 /// public static class DriverFactory { private static readonly ILog Log = LogManager.GetLogger(typeof(DriverFactory)); /// /// 根据传输协议类型和端点创建驱动适配器 /// /// 设备唯一标识符 /// 传输协议类型: "Tcp", "SCPI", "ModBus", "S7", "Serial" /// 端点信息,格式: "ip:port" 或 "ip:port:extra" /// IDeviceDriver 实例 /// 不支持的传输协议类型 /// 端点格式错误 public static IDeviceDriver CreateDriver(string deviceId, string transport, string endpoint) { return CreateDriver(deviceId, transport, endpoint, null); } /// /// 根据传输协议类型、端点和额外参数创建驱动适配器 /// /// 设备唯一标识符 /// 传输协议类型: "Tcp", "SCPI", "ModBus", "S7", "Serial" /// 端点信息,格式: "ip:port" 或 "ip:port:extra" /// 额外参数(可选) /// IDeviceDriver 实例 /// 不支持的传输协议类型 /// 端点格式错误 public static IDeviceDriver CreateDriver(string deviceId, string transport, string endpoint, Dictionary? extraParams) { if (string.IsNullOrWhiteSpace(deviceId)) throw new ArgumentNullException(nameof(deviceId)); if (string.IsNullOrWhiteSpace(transport)) throw new ArgumentNullException(nameof(transport)); if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentNullException(nameof(endpoint)); Log.Info($"[DriverFactory] 创建设备驱动: DeviceId={deviceId}, Transport={transport}, Endpoint={endpoint}"); string[] parts = endpoint.Split(':'); if (parts.Length < 2) { throw new ArgumentException($"端点格式错误,应为 'ip:port' 或 'ip:port:extra',实际: {endpoint}"); } string ip = parts[0]; if (!int.TryParse(parts[1], out int port)) { throw new ArgumentException($"端口号格式错误: {parts[1]}"); } switch (transport.ToUpper()) { case "TCP": Log.Info($"[DriverFactory] 创建 TCP 原始通信驱动: {ip}:{port}"); return new TcpRawDriverAdapter(deviceId, ip, port); case "SCPI": Log.Info($"[DriverFactory] 创建 SCPI 协议驱动: {ip}:{port}"); return new ScpiDriverAdapter(deviceId, ip, port); case "MODBUS": byte slaveId = 1; if (extraParams != null && extraParams.TryGetValue("slaveId", out string slaveIdStr)) { if (!byte.TryParse(slaveIdStr, out slaveId)) { slaveId = 1; } } // 如果 endpoint 有第三部分,作为 slaveId else if (parts.Length >= 3 && byte.TryParse(parts[2], out byte parsedSlaveId)) { slaveId = parsedSlaveId; } Log.Info($"[DriverFactory] 创建 ModBus TCP 驱动: {ip}:{port} (从站: {slaveId})"); return new ModBusDriverAdapter(deviceId, ip, port, slaveId); case "S7": Log.Info($"[DriverFactory] 创建 S7 PLC 驱动: {ip}:{port}"); return new S7DriverAdapter(deviceId, ip, port); case "SERIAL": // TODO: 实现串口驱动适配器 throw new NotSupportedException("串口驱动适配器尚未实现"); case "CAN": // CAN 驱动: endpoint 格式为 "busName:nodeIndex" 如 "CAN_BUS_1:0" string busName = ip; // ip 字段用作总线名称 int nodeIndex = port; // port 字段用作节点编号 Log.Info($"[DriverFactory] 创建 CAN 虚拟驱动: Bus={busName}, Node={nodeIndex}"); return new CanDriverAdapter(deviceId, busName, nodeIndex); default: throw new NotSupportedException($"不支持的传输协议类型: {transport}。支持的类型: Tcp, SCPI, ModBus, S7, Serial, CAN"); } } } }