ModbusTcpServerService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using APS7100TestTool.Controllers;
  10. using APS7100TestTool.Models;
  11. using NModbus;
  12. namespace APS7100TestTool.Services
  13. {
  14. public class ModbusTcpServerService : IDisposable
  15. {
  16. private TcpListener _tcpListener;
  17. private IModbusSlaveNetwork _modbusNetwork;
  18. private IModbusSlave _slave;
  19. private IPowerSupplyController _controllerAPS7100; // APS7100 控制器
  20. private IPowerSupplyController _controllerPSW250; // PSW250 控制器
  21. private List<ModbusRegisterMapping> _mappings;
  22. private CancellationTokenSource _cts;
  23. private Task _syncTask;
  24. // 缓存上一次的写入值,用于检测变化(使用数值比较避免字符串格式不一致问题)
  25. private Dictionary<int, double> _lastWriteValues = new Dictionary<int, double>();
  26. // 线程安全锁
  27. private readonly object _controllerLock = new object();
  28. private readonly object _dataStoreLock = new object();
  29. private volatile bool _isStopping = false;
  30. // 暂停轮询标志(用于保持设备在本地模式)
  31. private volatile bool _isPollingSuspended = false;
  32. // 心跳相关
  33. private ushort _heartbeatCounter = 0;
  34. private ushort _heartbeatRegisterAddress = 1; // 心跳寄存器地址(默认1,避免地址0的兼容性问题)
  35. private ushort _deviceStatusRegisterAddress = 2; // 设备状态寄存器地址
  36. // 设备连接状态 (由外部更新)
  37. private bool _isAPS7100Connected = false;
  38. private bool _isPSW250Connected = false;
  39. // 客户端连接跟踪
  40. private readonly object _clientLock = new object();
  41. private HashSet<string> _connectedClients = new HashSet<string>();
  42. private int _totalRequests = 0;
  43. private DateTime _lastRequestTime = DateTime.MinValue;
  44. private Task _connectionMonitorTask;
  45. public event Action<string> OnLog;
  46. public event Action<int, int, DateTime> OnClientStatusChanged; // (客户端数, 请求数, 最后请求时间)
  47. public bool IsRunning { get; private set; }
  48. public int ConnectedClientCount => _connectedClients.Count;
  49. public int TotalRequests => _totalRequests;
  50. public DateTime LastRequestTime => _lastRequestTime;
  51. /// <summary>
  52. /// 仿真模式:当设备未连接时,也会生成并记录命令(不实际发送)
  53. /// </summary>
  54. public bool SimulationMode { get; set; } = false;
  55. /// <summary>
  56. /// 轮询是否已暂停
  57. /// 暂停轮询后,Modbus 服务将不再向设备发送 SCPI 命令
  58. /// 用于保持设备在本地模式
  59. /// </summary>
  60. public bool IsPollingSuspended => _isPollingSuspended;
  61. /// <summary>
  62. /// 暂停设备轮询
  63. /// 暂停后 Modbus 服务不再向设备发送 SCPI 命令,设备可保持本地模式
  64. /// </summary>
  65. public void SuspendPolling()
  66. {
  67. _isPollingSuspended = true;
  68. Log("⚠ 设备轮询已暂停 - 设备将保持当前模式");
  69. }
  70. /// <summary>
  71. /// 恢复设备轮询
  72. /// 恢复后 Modbus 服务将继续向设备发送 SCPI 命令
  73. /// ⚠ 注意:这会使 APS7100 自动切换到远程模式
  74. /// </summary>
  75. public void ResumePolling()
  76. {
  77. _isPollingSuspended = false;
  78. Log("✓ 设备轮询已恢复");
  79. }
  80. /// <summary>
  81. /// 当前心跳计数值
  82. /// </summary>
  83. public ushort HeartbeatValue => _heartbeatCounter;
  84. /// <summary>
  85. /// 当前设备状态 (Bit0=APS7100, Bit1=PSW250)
  86. /// </summary>
  87. public (bool APS7100, bool PSW250) DeviceStatus => (_isAPS7100Connected, _isPSW250Connected);
  88. public ModbusTcpServerService(IPowerSupplyController controllerAPS7100, IPowerSupplyController controllerPSW250)
  89. {
  90. _controllerAPS7100 = controllerAPS7100;
  91. _controllerPSW250 = controllerPSW250;
  92. }
  93. /// <summary>
  94. /// 设置心跳寄存器地址
  95. /// </summary>
  96. public void SetHeartbeatAddresses(ushort heartbeatAddress, ushort deviceStatusAddress)
  97. {
  98. _heartbeatRegisterAddress = heartbeatAddress;
  99. _deviceStatusRegisterAddress = deviceStatusAddress;
  100. }
  101. /// <summary>
  102. /// 更新设备连接状态 (由主窗体调用)
  103. /// </summary>
  104. public void UpdateDeviceStatus(bool aps7100Connected, bool psw250Connected)
  105. {
  106. _isAPS7100Connected = aps7100Connected;
  107. _isPSW250Connected = psw250Connected;
  108. }
  109. public void UpdateControllers(IPowerSupplyController controllerAPS7100, IPowerSupplyController controllerPSW250)
  110. {
  111. lock (_controllerLock)
  112. {
  113. _controllerAPS7100 = controllerAPS7100;
  114. _controllerPSW250 = controllerPSW250;
  115. }
  116. }
  117. /// <summary>
  118. /// 根据设备目标获取对应的控制器
  119. /// </summary>
  120. private IPowerSupplyController GetController(string deviceTarget)
  121. {
  122. if (string.IsNullOrEmpty(deviceTarget) || deviceTarget.Equals("Universal", StringComparison.OrdinalIgnoreCase))
  123. {
  124. // Universal: 优先使用 APS7100,如果没有则用 PSW250
  125. return _controllerAPS7100 ?? _controllerPSW250;
  126. }
  127. if (deviceTarget.Equals("APS7100", StringComparison.OrdinalIgnoreCase))
  128. {
  129. return _controllerAPS7100;
  130. }
  131. if (deviceTarget.Equals("PSW250", StringComparison.OrdinalIgnoreCase))
  132. {
  133. return _controllerPSW250;
  134. }
  135. return null;
  136. }
  137. /// <summary>
  138. /// 启动 Modbus TCP 服务器(绑定所有接口)
  139. /// </summary>
  140. public void Start(int port, List<ModbusRegisterMapping> mappings)
  141. {
  142. Start("0.0.0.0", port, mappings);
  143. }
  144. /// <summary>
  145. /// 启动 Modbus TCP 服务器(绑定指定IP)
  146. /// </summary>
  147. /// <param name="bindIpAddress">绑定的IP地址,0.0.0.0表示所有接口</param>
  148. /// <param name="port">端口号</param>
  149. /// <param name="mappings">寄存器映射配置</param>
  150. public void Start(string bindIpAddress, int port, List<ModbusRegisterMapping> mappings)
  151. {
  152. if (IsRunning) return;
  153. _mappings = mappings;
  154. try
  155. {
  156. // 解析绑定IP地址
  157. IPAddress bindAddress;
  158. if (string.IsNullOrEmpty(bindIpAddress) || bindIpAddress == "0.0.0.0")
  159. {
  160. bindAddress = IPAddress.Any;
  161. }
  162. else
  163. {
  164. if (!IPAddress.TryParse(bindIpAddress, out bindAddress))
  165. {
  166. throw new Exception($"无效的IP地址: {bindIpAddress}");
  167. }
  168. }
  169. _tcpListener = new TcpListener(bindAddress, port);
  170. _tcpListener.Start();
  171. var factory = new ModbusFactory();
  172. _modbusNetwork = factory.CreateSlaveNetwork(_tcpListener);
  173. _slave = factory.CreateSlave(1); // Slave ID 1
  174. _modbusNetwork.AddSlave(_slave);
  175. _modbusNetwork.ListenAsync();
  176. _cts = new CancellationTokenSource();
  177. _syncTask = Task.Run(() => SyncLoop(_cts.Token));
  178. // 启动连接监控任务
  179. _connectionMonitorTask = Task.Run(() => MonitorConnections(_cts.Token));
  180. IsRunning = true;
  181. _totalRequests = 0;
  182. _lastRequestTime = DateTime.MinValue;
  183. lock (_clientLock) { _connectedClients.Clear(); }
  184. string bindInfo = bindAddress.Equals(IPAddress.Any) ? "所有接口" : bindIpAddress;
  185. Log($"Modbus TCP 服务器已启动,绑定: {bindInfo}:{port}");
  186. }
  187. catch (Exception ex)
  188. {
  189. IsRunning = false;
  190. throw new Exception($"启动 Modbus 服务失败: {ex.Message}", ex);
  191. }
  192. }
  193. /// <summary>
  194. /// 监控客户端连接
  195. /// </summary>
  196. private async Task MonitorConnections(CancellationToken token)
  197. {
  198. int lastClientCount = 0;
  199. int lastRequestCount = 0;
  200. while (!token.IsCancellationRequested && !_isStopping)
  201. {
  202. try
  203. {
  204. // 检查活动的 TCP 连接
  205. var activeConnections = GetActiveTcpConnections();
  206. lock (_clientLock)
  207. {
  208. _connectedClients = activeConnections;
  209. }
  210. int currentClientCount = _connectedClients.Count;
  211. int currentRequestCount = _totalRequests;
  212. // 如果有变化,触发事件
  213. if (currentClientCount != lastClientCount || currentRequestCount != lastRequestCount)
  214. {
  215. lastClientCount = currentClientCount;
  216. lastRequestCount = currentRequestCount;
  217. OnClientStatusChanged?.Invoke(currentClientCount, currentRequestCount, _lastRequestTime);
  218. }
  219. await Task.Delay(500, token);
  220. }
  221. catch (TaskCanceledException)
  222. {
  223. break;
  224. }
  225. catch { }
  226. }
  227. }
  228. /// <summary>
  229. /// 获取当前活动的 TCP 连接
  230. /// </summary>
  231. private HashSet<string> GetActiveTcpConnections()
  232. {
  233. var connections = new HashSet<string>();
  234. try
  235. {
  236. var properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
  237. var tcpConnections = properties.GetActiveTcpConnections();
  238. var localEndpoint = _tcpListener?.LocalEndpoint as IPEndPoint;
  239. if (localEndpoint != null)
  240. {
  241. foreach (var conn in tcpConnections)
  242. {
  243. // 检查是否是连接到我们服务器端口的客户端
  244. if (conn.LocalEndPoint.Port == localEndpoint.Port &&
  245. conn.State == System.Net.NetworkInformation.TcpState.Established)
  246. {
  247. connections.Add(conn.RemoteEndPoint.ToString());
  248. }
  249. }
  250. }
  251. }
  252. catch { }
  253. return connections;
  254. }
  255. /// <summary>
  256. /// 记录请求(供外部调用或内部调用)
  257. /// </summary>
  258. public void RecordRequest()
  259. {
  260. Interlocked.Increment(ref _totalRequests);
  261. _lastRequestTime = DateTime.Now;
  262. }
  263. public void Stop()
  264. {
  265. if (!IsRunning) return;
  266. _isStopping = true;
  267. _cts?.Cancel();
  268. // 等待同步任务结束
  269. try
  270. {
  271. if (_syncTask != null && !_syncTask.IsCompleted)
  272. {
  273. _syncTask.Wait(2000); // 最多等待 2 秒
  274. }
  275. }
  276. catch { /* 忽略取消异常 */ }
  277. try { _tcpListener?.Stop(); } catch { }
  278. try { _modbusNetwork?.Dispose(); } catch { }
  279. IsRunning = false;
  280. _isStopping = false;
  281. Log("Modbus TCP 服务器已停止");
  282. }
  283. private async Task SyncLoop(CancellationToken token)
  284. {
  285. while (!token.IsCancellationRequested && !_isStopping)
  286. {
  287. // 更新心跳和设备状态(这些不涉及设备通讯,始终执行)
  288. UpdateHeartbeat();
  289. UpdateDeviceStatusRegister();
  290. // 如果轮询已暂停,跳过设备通讯操作
  291. // 这样可以保持设备在本地模式
  292. if (!_isPollingSuspended)
  293. {
  294. try
  295. {
  296. // 处理写入命令(根据配置的设备目标分发到对应设备)
  297. ProcessWriteCommands();
  298. // 处理读取状态(根据配置的设备目标从对应设备读取)
  299. ProcessReadStatus();
  300. }
  301. catch (Exception ex)
  302. {
  303. Log($"同步错误: {ex.Message}");
  304. }
  305. }
  306. try
  307. {
  308. await Task.Delay(200, token);
  309. }
  310. catch (TaskCanceledException)
  311. {
  312. break;
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// 更新心跳寄存器 (每次调用+1,溢出后从0重新开始)
  318. /// PLC可以通过监测此值是否变化来判断APP是否正常运行
  319. /// </summary>
  320. private void UpdateHeartbeat()
  321. {
  322. lock (_dataStoreLock)
  323. {
  324. if (_slave == null) return;
  325. try
  326. {
  327. _heartbeatCounter++;
  328. var dataStore = _slave.DataStore;
  329. dataStore.HoldingRegisters.WritePoints(_heartbeatRegisterAddress, new[] { _heartbeatCounter });
  330. }
  331. catch { }
  332. }
  333. }
  334. /// <summary>
  335. /// 更新设备状态寄存器
  336. /// Bit 0: APS7100 连接状态 (1=已连接, 0=未连接)
  337. /// Bit 1: PSW250 连接状态 (1=已连接, 0=未连接)
  338. /// Bit 2-15: 预留
  339. /// </summary>
  340. private void UpdateDeviceStatusRegister()
  341. {
  342. lock (_dataStoreLock)
  343. {
  344. if (_slave == null) return;
  345. try
  346. {
  347. ushort status = 0;
  348. if (_isAPS7100Connected) status |= 0x0001; // Bit 0
  349. if (_isPSW250Connected) status |= 0x0002; // Bit 1
  350. var dataStore = _slave.DataStore;
  351. dataStore.HoldingRegisters.WritePoints(_deviceStatusRegisterAddress, new[] { status });
  352. }
  353. catch { }
  354. }
  355. }
  356. private void ProcessWriteCommands()
  357. {
  358. if (_mappings == null) return;
  359. // 浮点数比较的容差值(用于判断值是否变化、是否为零、是否匹配触发值)
  360. const double VALUE_TOLERANCE = 0.0001;
  361. var writeMappings = _mappings.Where(m => m.GetOpType() == ModbusOperationType.WriteCommand).ToList();
  362. // 按地址分组,先读取所有地址的当前值
  363. var addressGroups = writeMappings.GroupBy(m => m.Address);
  364. foreach (var group in addressGroups)
  365. {
  366. if (_isStopping) return;
  367. int address = group.Key;
  368. string currentValueStr = ReadFromDataStore(group.First());
  369. double currentValue = 0;
  370. try
  371. {
  372. currentValue = double.Parse(currentValueStr);
  373. }
  374. catch { continue; }
  375. // 检测该地址的值是否变化(使用数值比较,避免字符串格式不一致问题)
  376. bool addressValueChanged = false;
  377. if (!_lastWriteValues.ContainsKey(address))
  378. {
  379. _lastWriteValues[address] = currentValue;
  380. // 首次运行也检测触发(如果当前值正好等于某个触发值)
  381. addressValueChanged = true;
  382. }
  383. else if (Math.Abs(_lastWriteValues[address] - currentValue) > VALUE_TOLERANCE)
  384. {
  385. // 数值变化超过容差,认为值变化了
  386. addressValueChanged = true;
  387. _lastWriteValues[address] = currentValue;
  388. }
  389. if (!addressValueChanged) continue;
  390. // 值变化了,检查该地址下的所有配置,找到匹配的触发值
  391. // 特殊处理:当值变为0时,将所有配置了确认地址的映射的确认地址也设置为0(复位)
  392. if (Math.Abs(currentValue) < VALUE_TOLERANCE)
  393. {
  394. foreach (var map in group)
  395. {
  396. if (map.ResponseAddress.HasValue && map.ResponseAddress.Value > 0)
  397. {
  398. WriteResponseValue(map, 0);
  399. Log($"[复位] 地址:{address} 值为0 -> 确认地址:{map.ResponseAddress.Value} <- 0");
  400. }
  401. }
  402. continue; // 值为0时不执行任何命令,仅复位确认地址
  403. }
  404. foreach (var map in group)
  405. {
  406. if (_isStopping) return;
  407. // 根据配置的设备目标获取对应的控制器
  408. var controller = GetController(map.DeviceTarget);
  409. bool isSimulation = (controller == null && SimulationMode);
  410. // 非仿真模式下,设备未连接则跳过
  411. if (controller == null && !SimulationMode) continue;
  412. // 检查 TriggerValue 是否匹配
  413. if (map.TriggerValue.HasValue)
  414. {
  415. // 触发模式:只有当前值等于触发值时才执行
  416. if (Math.Abs(currentValue - map.TriggerValue.Value) > VALUE_TOLERANCE)
  417. {
  418. continue; // 不匹配,跳过
  419. }
  420. }
  421. // 没有 TriggerValue 的是数值同步模式,任何变化都执行
  422. try
  423. {
  424. string cmd;
  425. if (map.TriggerValue.HasValue)
  426. {
  427. // Trigger 模式
  428. if (!map.ScpiCommand.Contains("{0}"))
  429. {
  430. cmd = map.ScpiCommand;
  431. }
  432. else
  433. {
  434. // 命令包含 {0},需要从数据地址读取值
  435. double commandValue;
  436. if (map.DataAddress.HasValue && map.DataAddress.Value > 0)
  437. {
  438. var dataAddressType = map.GetDataAddressType();
  439. var dummyMap = new ModbusRegisterMapping
  440. {
  441. Address = map.DataAddress.Value,
  442. DataType = dataAddressType.ToString(),
  443. };
  444. string dataValStr = ReadFromDataStore(dummyMap);
  445. if (double.TryParse(dataValStr, out double dVal))
  446. {
  447. commandValue = dVal;
  448. }
  449. else
  450. {
  451. commandValue = 0;
  452. }
  453. }
  454. else
  455. {
  456. commandValue = currentValue;
  457. }
  458. double physicalValue = commandValue * map.ScaleFactor;
  459. cmd = string.Format(CultureInfo.InvariantCulture, map.ScpiCommand, physicalValue);
  460. }
  461. }
  462. else
  463. {
  464. // 数值同步模式
  465. double physicalValue = currentValue * map.ScaleFactor;
  466. cmd = string.Format(CultureInfo.InvariantCulture, map.ScpiCommand, physicalValue);
  467. }
  468. // 仿真模式:只记录命令,不实际发送
  469. if (isSimulation)
  470. {
  471. RecordRequest();
  472. Log($"[仿真->{map.DeviceTarget}] 地址:{map.Address} 触发值:{map.TriggerValue?.ToString() ?? "无"} 当前值:{currentValue} -> 命令:{cmd}");
  473. // 写入确认值(仿真模式也写入,方便测试)
  474. WriteResponseValue(map, (short)currentValue);
  475. }
  476. else
  477. {
  478. RecordRequest();
  479. controller.SendCustomCommand(cmd);
  480. Log($"[Modbus->{map.DeviceTarget}] 地址:{map.Address} 触发值:{map.TriggerValue?.ToString() ?? "无"} 当前值:{currentValue} -> 发送:{cmd}");
  481. // 执行成功,写入确认值(触发值)
  482. WriteResponseValue(map, (short)currentValue);
  483. }
  484. }
  485. catch (Exception ex)
  486. {
  487. Log($"执行命令失败 (Addr {map.Address}, {map.DeviceTarget}): {ex.Message}");
  488. // 执行失败,写入 -1
  489. WriteResponseValue(map, -1);
  490. }
  491. }
  492. }
  493. }
  494. private void ProcessReadStatus()
  495. {
  496. if (_mappings == null) return;
  497. var readMappings = _mappings.Where(m => m.GetOpType() == ModbusOperationType.ReadStatus);
  498. foreach (var map in readMappings)
  499. {
  500. // 检查是否正在停止
  501. if (_isStopping) return;
  502. // 根据配置的设备目标获取对应的控制器
  503. var controller = GetController(map.DeviceTarget);
  504. if (controller == null) continue; // 对应设备未连接,跳过
  505. try
  506. {
  507. string response = controller.SendCustomQuery(map.ScpiCommand);
  508. if (double.TryParse(response, out double val))
  509. {
  510. double regValueDouble = val / map.ScaleFactor;
  511. WriteToDataStore(map, regValueDouble);
  512. }
  513. }
  514. catch
  515. {
  516. // 忽略读取错误
  517. }
  518. }
  519. }
  520. private string ReadFromDataStore(ModbusRegisterMapping map)
  521. {
  522. lock (_dataStoreLock)
  523. {
  524. if (_slave == null) return "0";
  525. try
  526. {
  527. var dataStore = _slave.DataStore;
  528. ushort[] registers;
  529. if (map.GetDataType() == ModbusDataType.Float)
  530. {
  531. registers = dataStore.HoldingRegisters.ReadPoints((ushort)map.Address, 2);
  532. float f = GetFloatFromRegisters(registers);
  533. return f.ToString();
  534. }
  535. else
  536. {
  537. registers = dataStore.HoldingRegisters.ReadPoints((ushort)map.Address, 1);
  538. if (map.GetDataType() == ModbusDataType.Int16)
  539. return ((short)registers[0]).ToString();
  540. else
  541. return registers[0].ToString();
  542. }
  543. }
  544. catch (Exception)
  545. {
  546. return "0";
  547. }
  548. }
  549. }
  550. private void WriteToDataStore(ModbusRegisterMapping map, double value)
  551. {
  552. lock (_dataStoreLock)
  553. {
  554. if (_slave == null) return;
  555. try
  556. {
  557. var dataStore = _slave.DataStore;
  558. var collection = map.GetRegType() == ModbusRegisterType.Input
  559. ? dataStore.InputRegisters
  560. : dataStore.HoldingRegisters;
  561. if (map.GetDataType() == ModbusDataType.Float)
  562. {
  563. ushort[] regs = GetRegistersFromFloat((float)value);
  564. collection.WritePoints((ushort)map.Address, regs);
  565. }
  566. else
  567. {
  568. ushort val;
  569. if (map.GetDataType() == ModbusDataType.Int16)
  570. val = (ushort)((short)value);
  571. else
  572. val = (ushort)value;
  573. collection.WritePoints((ushort)map.Address, new[] { val });
  574. }
  575. }
  576. catch (Exception)
  577. {
  578. // 忽略写入错误
  579. }
  580. }
  581. }
  582. /// <summary>
  583. /// 写入命令执行确认值(只写一次)
  584. /// 成功:写入触发值;失败:写入 -1
  585. /// </summary>
  586. private void WriteResponseValue(ModbusRegisterMapping map, short value)
  587. {
  588. if (!map.ResponseAddress.HasValue || map.ResponseAddress.Value <= 0)
  589. return; // 未配置确认地址,跳过
  590. lock (_dataStoreLock)
  591. {
  592. if (_slave == null) return;
  593. try
  594. {
  595. var dataStore = _slave.DataStore;
  596. dataStore.HoldingRegisters.WritePoints((ushort)map.ResponseAddress.Value, new[] { (ushort)value });
  597. if (value >= 0)
  598. Log($"[确认] 地址:{map.ResponseAddress.Value} <- {value} (成功)");
  599. else
  600. Log($"[确认] 地址:{map.ResponseAddress.Value} <- {value} (失败)");
  601. }
  602. catch (Exception ex)
  603. {
  604. Log($"写入确认值失败: {ex.Message}");
  605. }
  606. }
  607. }
  608. private float GetFloatFromRegisters(ushort[] regs)
  609. {
  610. if (regs.Length < 2) return 0;
  611. byte[] bytes = new byte[4];
  612. // 假设 AB CD 顺序
  613. byte[] high = BitConverter.GetBytes(regs[0]); // AB ? No, Modbus register is 16-bit
  614. // 通常 Modbus Float:
  615. // Reg1: High Word, Reg2: Low Word (Big Endian Modbus)
  616. // 或者 Reg1: Low Word, Reg2: High Word (Little Endian Modbus)
  617. // 这是一个常见的坑。这里我们使用最简单的 Little Endian Words 组合
  618. Buffer.BlockCopy(regs, 0, bytes, 0, 4);
  619. return BitConverter.ToSingle(bytes, 0);
  620. }
  621. private ushort[] GetRegistersFromFloat(float value)
  622. {
  623. byte[] bytes = BitConverter.GetBytes(value);
  624. ushort[] regs = new ushort[2];
  625. Buffer.BlockCopy(bytes, 0, regs, 0, 4);
  626. return regs;
  627. }
  628. private void Log(string msg)
  629. {
  630. OnLog?.Invoke($"[Modbus] {msg}");
  631. }
  632. #region 公共读取寄存器方法
  633. /// <summary>
  634. /// 读取指定地址的 Holding 寄存器值(单个 UInt16)
  635. /// </summary>
  636. public ushort? ReadHoldingRegister(ushort address)
  637. {
  638. lock (_dataStoreLock)
  639. {
  640. if (_slave == null) return null;
  641. try
  642. {
  643. var registers = _slave.DataStore.HoldingRegisters.ReadPoints(address, 1);
  644. return registers[0];
  645. }
  646. catch { return null; }
  647. }
  648. }
  649. /// <summary>
  650. /// 读取指定地址的多个 Holding 寄存器值
  651. /// </summary>
  652. public ushort[] ReadHoldingRegisters(ushort startAddress, ushort count)
  653. {
  654. lock (_dataStoreLock)
  655. {
  656. if (_slave == null) return null;
  657. try
  658. {
  659. return _slave.DataStore.HoldingRegisters.ReadPoints(startAddress, count);
  660. }
  661. catch { return null; }
  662. }
  663. }
  664. /// <summary>
  665. /// 读取指定地址的 Float 值(占用 2 个寄存器)
  666. /// </summary>
  667. public float? ReadHoldingFloat(ushort address)
  668. {
  669. lock (_dataStoreLock)
  670. {
  671. if (_slave == null) return null;
  672. try
  673. {
  674. var registers = _slave.DataStore.HoldingRegisters.ReadPoints(address, 2);
  675. return GetFloatFromRegisters(registers);
  676. }
  677. catch { return null; }
  678. }
  679. }
  680. /// <summary>
  681. /// 获取当前配置的映射列表
  682. /// </summary>
  683. public List<ModbusRegisterMapping> GetMappings()
  684. {
  685. return _mappings ?? new List<ModbusRegisterMapping>();
  686. }
  687. /// <summary>
  688. /// 读取所有配置的寄存器值,返回地址和值的字典
  689. /// </summary>
  690. public Dictionary<int, (string RawValue, string Description, string DataType)> ReadAllConfiguredRegisters()
  691. {
  692. var result = new Dictionary<int, (string RawValue, string Description, string DataType)>();
  693. if (_mappings == null || _slave == null) return result;
  694. lock (_dataStoreLock)
  695. {
  696. foreach (var map in _mappings)
  697. {
  698. try
  699. {
  700. string value = "";
  701. if (map.GetDataType() == ModbusDataType.Float)
  702. {
  703. var registers = _slave.DataStore.HoldingRegisters.ReadPoints((ushort)map.Address, 2);
  704. float f = GetFloatFromRegisters(registers);
  705. value = f.ToString("F4");
  706. }
  707. else
  708. {
  709. var registers = _slave.DataStore.HoldingRegisters.ReadPoints((ushort)map.Address, 1);
  710. if (map.GetDataType() == ModbusDataType.Int16)
  711. value = ((short)registers[0]).ToString();
  712. else
  713. value = registers[0].ToString();
  714. }
  715. result[map.Address] = (value, map.Description ?? "", map.DataType ?? "Int16");
  716. }
  717. catch
  718. {
  719. result[map.Address] = ("读取失败", map.Description ?? "", map.DataType ?? "Int16");
  720. }
  721. }
  722. }
  723. return result;
  724. }
  725. #endregion
  726. public void Dispose()
  727. {
  728. Stop();
  729. }
  730. }
  731. }