MainForm.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Threading.Tasks;
  5. using System.Windows.Forms;
  6. using APS7100TestTool.Controllers;
  7. using APS7100TestTool.Services;
  8. using APS7100TestTool.Models;
  9. namespace APS7100TestTool.Forms
  10. {
  11. public partial class MainForm : Form
  12. {
  13. // Devices
  14. private ScpiDevice? _deviceAPS7100;
  15. private ScpiDevice? _devicePSW250;
  16. private IPowerSupplyController? _controllerAPS7100;
  17. private IPowerSupplyController? _controllerPSW250;
  18. // Services
  19. private ModbusTcpServerService? _modbusService;
  20. private ConfigService _configService;
  21. private AppSettings _appSettings;
  22. private List<ModbusRegisterMapping> _modbusMappings = new List<ModbusRegisterMapping>();
  23. // Timers
  24. private System.Windows.Forms.Timer _measureTimer;
  25. // Child Windows
  26. private ManualTestForm? _manualTestFormAPS7100;
  27. private ManualTestForm? _manualTestFormPSW250;
  28. // 静默启动控制
  29. private bool _startMinimizedToTray = false;
  30. private bool _hasShownOnce = false;
  31. // 缓存的设备标识(避免频繁查询阻塞UI)
  32. private string _cachedAPS7100IDN = "";
  33. private string _cachedPSW250IDN = "";
  34. // 连接中标志(防止定时器阻塞UI)
  35. private volatile bool _isConnectingAPS7100 = false;
  36. private volatile bool _isConnectingPSW250 = false;
  37. public MainForm()
  38. {
  39. InitializeComponent();
  40. // 启用双缓冲减少闪烁
  41. this.DoubleBuffered = true;
  42. this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
  43. ControlStyles.AllPaintingInWmPaint |
  44. ControlStyles.UserPaint, true);
  45. this.UpdateStyles();
  46. _configService = new ConfigService();
  47. _appSettings = _configService.LoadAppSettings();
  48. // SCPI 命令调试日志(如需诊断,将 false 改为 true)
  49. ScpiDevice.EnableCommandLog = false;
  50. ScpiDevice.OnCommandLog += (msg) =>
  51. {
  52. BeginInvoke(() => LogMessage(msg));
  53. };
  54. // 初始化测量定时器
  55. _measureTimer = new System.Windows.Forms.Timer();
  56. _measureTimer.Interval = 1000;
  57. _measureTimer.Tick += MeasureTimer_Tick;
  58. _measureTimer.Start();
  59. // 初始化系统托盘
  60. InitializeSystemTray();
  61. // 如果设置启动时最小化,则标记为静默启动
  62. _startMinimizedToTray = _appSettings.StartMinimized;
  63. InitializeUI();
  64. }
  65. /// <summary>
  66. /// 初始化系统托盘图标
  67. /// </summary>
  68. private void InitializeSystemTray()
  69. {
  70. // 创建托盘右键菜单
  71. trayContextMenu = new ContextMenuStrip();
  72. trayMenuShow = new ToolStripMenuItem("显示主窗口(&S)");
  73. trayMenuShow.Font = new Font(trayMenuShow.Font, FontStyle.Bold);
  74. trayMenuShow.Click += (s, e) => ShowMainWindow();
  75. trayMenuAPS7100 = new ToolStripMenuItem("APS-7100: 未连接");
  76. trayMenuAPS7100.Enabled = false;
  77. trayMenuPSW250 = new ToolStripMenuItem("PSW-250: 未连接");
  78. trayMenuPSW250.Enabled = false;
  79. trayMenuSep1 = new ToolStripSeparator();
  80. trayMenuExit = new ToolStripMenuItem("退出(&X)");
  81. trayMenuExit.Click += (s, e) => ExitApplication();
  82. trayContextMenu.Items.AddRange(new ToolStripItem[] {
  83. trayMenuShow, new ToolStripSeparator(),
  84. trayMenuAPS7100, trayMenuPSW250,
  85. trayMenuSep1, trayMenuExit
  86. });
  87. // 创建托盘图标
  88. notifyIcon = new NotifyIcon();
  89. notifyIcon.Text = "固纬电源测试工具";
  90. notifyIcon.Icon = this.Icon ?? SystemIcons.Application;
  91. notifyIcon.ContextMenuStrip = trayContextMenu;
  92. notifyIcon.Visible = true;
  93. // 双击托盘图标显示窗口
  94. notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
  95. // 托盘气泡提示点击
  96. notifyIcon.BalloonTipClicked += (s, e) => ShowMainWindow();
  97. }
  98. /// <summary>
  99. /// 重写 SetVisibleCore 以实现静默启动(开机自启动时不显示窗口)
  100. /// </summary>
  101. protected override void SetVisibleCore(bool value)
  102. {
  103. // 第一次显示时,如果是静默启动模式,则不显示窗口
  104. if (!_hasShownOnce)
  105. {
  106. _hasShownOnce = true;
  107. if (_startMinimizedToTray)
  108. {
  109. // 静默启动:不显示窗口,只在托盘运行
  110. base.SetVisibleCore(false);
  111. return;
  112. }
  113. }
  114. base.SetVisibleCore(value);
  115. }
  116. /// <summary>
  117. /// 显示主窗口
  118. /// </summary>
  119. private void ShowMainWindow()
  120. {
  121. this.Show();
  122. this.ShowInTaskbar = true;
  123. this.WindowState = FormWindowState.Normal;
  124. this.Activate();
  125. this.BringToFront();
  126. }
  127. /// <summary>
  128. /// 退出应用程序
  129. /// </summary>
  130. private void ExitApplication()
  131. {
  132. // 先清理资源,再退出
  133. CleanupResources();
  134. notifyIcon.Visible = false;
  135. notifyIcon.Dispose();
  136. Application.Exit();
  137. }
  138. /// <summary>
  139. /// 清理所有资源(确保端口和连接被正确释放)
  140. /// </summary>
  141. private void CleanupResources()
  142. {
  143. try
  144. {
  145. _measureTimer?.Stop();
  146. _measureTimer?.Dispose();
  147. // 停止并释放 Modbus 服务
  148. if (_modbusService != null)
  149. {
  150. _modbusService.Stop();
  151. _modbusService.Dispose();
  152. _modbusService = null;
  153. }
  154. // 释放设备连接
  155. if (_deviceAPS7100 != null)
  156. {
  157. _deviceAPS7100.Disconnect();
  158. _deviceAPS7100.Dispose();
  159. _deviceAPS7100 = null;
  160. }
  161. if (_devicePSW250 != null)
  162. {
  163. _devicePSW250.Disconnect();
  164. _devicePSW250.Dispose();
  165. _devicePSW250 = null;
  166. }
  167. _controllerAPS7100 = null;
  168. _controllerPSW250 = null;
  169. }
  170. catch (Exception ex)
  171. {
  172. System.Diagnostics.Debug.WriteLine($"清理资源时出错: {ex.Message}");
  173. }
  174. }
  175. /// <summary>
  176. /// 窗口大小改变时处理(最小化到托盘)
  177. /// </summary>
  178. protected override void OnResize(EventArgs e)
  179. {
  180. base.OnResize(e);
  181. if (this.WindowState == FormWindowState.Minimized)
  182. {
  183. this.Hide();
  184. this.ShowInTaskbar = false;
  185. }
  186. }
  187. /// <summary>
  188. /// 更新托盘菜单中的设备状态
  189. /// </summary>
  190. private void UpdateTrayStatus()
  191. {
  192. if (trayMenuAPS7100 != null)
  193. {
  194. bool aps7100Connected = _deviceAPS7100?.IsConnected == true;
  195. trayMenuAPS7100.Text = aps7100Connected ? "APS-7100: ✓ 已连接" : "APS-7100: 未连接";
  196. }
  197. if (trayMenuPSW250 != null)
  198. {
  199. bool psw250Connected = _devicePSW250?.IsConnected == true;
  200. trayMenuPSW250.Text = psw250Connected ? "PSW-250: ✓ 已连接" : "PSW-250: 未连接";
  201. }
  202. // 更新托盘图标提示文字
  203. if (notifyIcon != null)
  204. {
  205. bool aps = _deviceAPS7100?.IsConnected == true;
  206. bool psw = _devicePSW250?.IsConnected == true;
  207. string status = "";
  208. if (aps) status += "APS7100 ✓ ";
  209. if (psw) status += "PSW250 ✓";
  210. if (string.IsNullOrEmpty(status)) status = "未连接设备";
  211. notifyIcon.Text = $"固纬电源测试工具\n{status}";
  212. }
  213. }
  214. private void InitializeUI()
  215. {
  216. UpdateAPS7100Status();
  217. UpdatePSW250Status();
  218. UpdateModbusStatus();
  219. LogMessage("程序启动完成");
  220. // 自动加载 Modbus 配置
  221. AutoLoadModbusConfig();
  222. // 执行自动连接和 Modbus 启动(异步)
  223. _ = AutoConnectAndStartModbusAsync();
  224. }
  225. /// <summary>
  226. /// 自动连接设备并启动 Modbus 服务(按顺序执行,确保时序正确)
  227. /// </summary>
  228. private async Task AutoConnectAndStartModbusAsync()
  229. {
  230. var connectTasks = new List<Task>();
  231. // 自动连接设备(并行执行)
  232. if (_appSettings.AutoConnectAPS7100)
  233. {
  234. LogMessage("正在自动连接 APS-7100...");
  235. connectTasks.Add(ConnectAPS7100Async());
  236. }
  237. if (_appSettings.AutoConnectPSW250)
  238. {
  239. LogMessage("正在自动连接 PSW-250...");
  240. connectTasks.Add(ConnectPSW250Async());
  241. }
  242. // 等待所有连接任务完成(无论成功还是失败)
  243. if (connectTasks.Count > 0)
  244. {
  245. await Task.WhenAll(connectTasks);
  246. }
  247. // 连接完成后再启动 Modbus 服务(带重试机制)
  248. if (_appSettings.AutoStartModbus && _modbusMappings.Count > 0)
  249. {
  250. LogMessage("正在自动启动 Modbus 服务...");
  251. await StartModbusServiceWithRetryAsync(maxRetries: 3, delayMs: 1000);
  252. }
  253. }
  254. /// <summary>
  255. /// 带重试机制的 Modbus 服务启动
  256. /// </summary>
  257. private async Task StartModbusServiceWithRetryAsync(int maxRetries = 3, int delayMs = 1000)
  258. {
  259. for (int attempt = 1; attempt <= maxRetries; attempt++)
  260. {
  261. try
  262. {
  263. StartModbusService();
  264. // 检查是否真的启动成功
  265. if (_modbusService != null && _modbusService.IsRunning)
  266. {
  267. return; // 启动成功,退出
  268. }
  269. else
  270. {
  271. LogMessage($"Modbus 服务启动后状态异常 (尝试 {attempt}/{maxRetries})");
  272. }
  273. }
  274. catch (Exception ex)
  275. {
  276. LogMessage($"Modbus 服务启动异常 (尝试 {attempt}/{maxRetries}): {ex.Message}");
  277. }
  278. // 如果不是最后一次尝试,等待后重试
  279. if (attempt < maxRetries)
  280. {
  281. LogMessage($"将在 {delayMs}ms 后重试...");
  282. await Task.Delay(delayMs);
  283. }
  284. }
  285. LogMessage("⚠ Modbus 服务自动启动失败,请手动启动");
  286. }
  287. /// <summary>
  288. /// 将相对路径转换为绝对路径(相对于程序运行目录)
  289. /// </summary>
  290. private string ResolveConfigPath(string path)
  291. {
  292. if (string.IsNullOrEmpty(path)) return path;
  293. // 如果已经是绝对路径,直接返回
  294. if (System.IO.Path.IsPathRooted(path)) return path;
  295. // 相对路径:转换为相对于程序运行目录的绝对路径
  296. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
  297. }
  298. /// <summary>
  299. /// 自动加载上次保存的 Modbus 配置
  300. /// </summary>
  301. private void AutoLoadModbusConfig()
  302. {
  303. // 优先使用上次保存的配置文件路径(支持相对路径)
  304. string configPath = ResolveConfigPath(_appSettings.ModbusConfigPath);
  305. // 如果没有配置路径或文件不存在,尝试使用默认路径
  306. if (string.IsNullOrEmpty(configPath) || !System.IO.File.Exists(configPath))
  307. {
  308. configPath = ConfigService.DefaultModbusConfigPath;
  309. }
  310. if (System.IO.File.Exists(configPath))
  311. {
  312. try
  313. {
  314. _modbusMappings = _configService.LoadModbusConfig(configPath);
  315. LogMessage($"✓ 自动加载 Modbus 配置: {configPath} ({_modbusMappings.Count} 条规则)");
  316. UpdateModbusStatus();
  317. }
  318. catch (Exception ex)
  319. {
  320. LogMessage($"自动加载 Modbus 配置失败: {ex.Message}");
  321. }
  322. }
  323. }
  324. #region APS7100 Connection
  325. private async void btnConnectAPS7100_Click(object sender, EventArgs e)
  326. {
  327. // 如果正在连接中,忽略点击
  328. if (_isConnectingAPS7100)
  329. {
  330. LogMessage("APS7100 正在连接中,请稍候...");
  331. return;
  332. }
  333. if (_deviceAPS7100 != null && _deviceAPS7100.IsConnected)
  334. {
  335. DisconnectAPS7100();
  336. }
  337. else
  338. {
  339. await ShowConnectionDialogAsync(DeviceType.APS7100);
  340. }
  341. }
  342. private async void menuConnectAPS7100_Click(object sender, EventArgs e)
  343. {
  344. if (_deviceAPS7100 != null && _deviceAPS7100.IsConnected)
  345. {
  346. DisconnectAPS7100();
  347. }
  348. else
  349. {
  350. await ShowConnectionDialogAsync(DeviceType.APS7100);
  351. }
  352. }
  353. private async Task ConnectAPS7100Async()
  354. {
  355. // 禁用按钮,显示连接中状态
  356. btnConnectAPS7100.Enabled = false;
  357. btnConnectAPS7100.Text = "连接中...";
  358. menuConnectAPS7100.Enabled = false;
  359. _isConnectingAPS7100 = true;
  360. try
  361. {
  362. LogMessage("APS7100 开始连接...");
  363. // 确保旧连接被正确清理
  364. if (_deviceAPS7100 != null)
  365. {
  366. LogMessage(" 清理旧连接...");
  367. try { _deviceAPS7100.Disconnect(); } catch { }
  368. try { _deviceAPS7100.Dispose(); } catch { }
  369. _deviceAPS7100 = null;
  370. _controllerAPS7100 = null;
  371. }
  372. // 等待后台任务完成和资源释放
  373. await Task.Delay(500);
  374. // 强制垃圾回收以释放网络资源
  375. GC.Collect();
  376. GC.WaitForPendingFinalizers();
  377. await Task.Delay(200);
  378. // 尝试连接(带重试)
  379. // 设备断电重启后可能需要时间初始化网络服务,使用递增间隔重试
  380. int maxRetries = 5;
  381. int[] retryDelays = { 0, 1000, 2000, 3000, 5000 }; // 递增间隔
  382. Exception? lastException = null;
  383. for (int retry = 0; retry < maxRetries; retry++)
  384. {
  385. if (retry > 0)
  386. {
  387. int delay = retryDelays[Math.Min(retry, retryDelays.Length - 1)];
  388. LogMessage($" [APS7100] 等待 {delay / 1000.0:F1} 秒后重试连接 ({retry}/{maxRetries - 1})...");
  389. await Task.Delay(delay);
  390. }
  391. try
  392. {
  393. await Task.Run(() =>
  394. {
  395. _deviceAPS7100 = new ScpiDevice();
  396. if (_appSettings.APS7100ConnectionType == "Serial")
  397. {
  398. if (string.IsNullOrEmpty(_appSettings.APS7100ComPort))
  399. {
  400. throw new Exception("未配置串口");
  401. }
  402. _deviceAPS7100.ConnectSerial(_appSettings.APS7100ComPort, _appSettings.APS7100BaudRate);
  403. }
  404. else
  405. {
  406. _deviceAPS7100.ConnectEthernet(_appSettings.APS7100IpAddress, _appSettings.APS7100Port);
  407. }
  408. _controllerAPS7100 = new APS7100Controller(_deviceAPS7100);
  409. });
  410. string connInfo = _appSettings.APS7100ConnectionType == "Serial"
  411. ? $"{_appSettings.APS7100ComPort} @ {_appSettings.APS7100BaudRate}"
  412. : $"{_appSettings.APS7100IpAddress}:{_appSettings.APS7100Port}";
  413. LogMessage($"APS7100 连接成功: {connInfo}");
  414. // 获取设备标识(异步执行,避免阻塞UI)
  415. _cachedAPS7100IDN = await Task.Run(() => _controllerAPS7100!.GetIdentification());
  416. LogMessage($"✓ APS7100 设备识别: {_cachedAPS7100IDN}");
  417. // 进入远程控制模式(部分设备可能不支持)
  418. try
  419. { //发送*IDN? 命令后,会自动切换到远程模式,无需再发送远程切换
  420. //await Task.Run(() => _controllerAPS7100!.SetRemoteMode());
  421. LogMessage($"✓ APS7100 已进入远程控制模式");
  422. }
  423. catch (Exception remEx)
  424. {
  425. LogMessage($"⚠ APS7100 远程模式命令失败(可忽略): {remEx.Message}");
  426. }
  427. UpdateAPS7100Status();
  428. UpdateManualTestController(DeviceType.APS7100);
  429. // 更新 Modbus 服务的控制器引用
  430. _modbusService?.UpdateControllers(_controllerAPS7100, _controllerPSW250);
  431. // 连接成功,退出重试循环
  432. break;
  433. }
  434. catch (Exception ex)
  435. {
  436. lastException = ex;
  437. LogMessage($" [APS7100] 连接尝试 {retry + 1} 失败: {ex.Message}");
  438. // 清理本次失败的连接资源
  439. if (_deviceAPS7100 != null)
  440. {
  441. try { _deviceAPS7100.Disconnect(); } catch { }
  442. try { _deviceAPS7100.Dispose(); } catch { }
  443. _deviceAPS7100 = null;
  444. }
  445. _controllerAPS7100 = null;
  446. // 如果不是最后一次重试,继续
  447. if (retry < maxRetries - 1)
  448. {
  449. continue;
  450. }
  451. // 最后一次重试也失败了
  452. int totalWaitTime = 0;
  453. for (int i = 0; i < maxRetries; i++) totalWaitTime += retryDelays[Math.Min(i, retryDelays.Length - 1)];
  454. LogMessage($"[APS7100] 连接失败(已尝试 {maxRetries} 次,总等待约 {totalWaitTime / 1000 + maxRetries * 5} 秒)");
  455. LogMessage($" 错误: {ex.Message}");
  456. if (ex.InnerException != null)
  457. {
  458. LogMessage($" 内部错误: {ex.InnerException.Message}");
  459. }
  460. LogMessage($" 提示: 如果设备刚断电重启,请等待设备完全启动后再试");
  461. UpdateAPS7100Status();
  462. }
  463. } // end for retry loop
  464. }
  465. finally
  466. {
  467. // 恢复按钮状态
  468. _isConnectingAPS7100 = false;
  469. btnConnectAPS7100.Enabled = true;
  470. menuConnectAPS7100.Enabled = true;
  471. UpdateAPS7100Status(); // 更新按钮文字
  472. }
  473. }
  474. // 防止重复断开
  475. private volatile bool _isDisconnectingAPS7100 = false;
  476. private void DisconnectAPS7100()
  477. {
  478. // 防止重复断开
  479. if (_isDisconnectingAPS7100) return;
  480. if (_deviceAPS7100 == null && _controllerAPS7100 == null) return;
  481. _isDisconnectingAPS7100 = true;
  482. try
  483. {
  484. // 断开前返回本地模式
  485. if (_controllerAPS7100 != null && _deviceAPS7100?.IsConnected == true)
  486. {
  487. try
  488. {
  489. _controllerAPS7100.SetLocalMode();
  490. }
  491. catch { /* 忽略断开时的错误 */ }
  492. }
  493. var device = _deviceAPS7100;
  494. _deviceAPS7100 = null;
  495. _controllerAPS7100 = null;
  496. if (device != null)
  497. {
  498. try { device.Disconnect(); } catch { }
  499. try { device.Dispose(); } catch { }
  500. }
  501. LogMessage("APS7100 已断开连接");
  502. UpdateAPS7100Status();
  503. UpdateManualTestController(DeviceType.APS7100);
  504. // 更新 Modbus 服务的控制器引用
  505. _modbusService?.UpdateControllers(_controllerAPS7100, _controllerPSW250);
  506. }
  507. catch (Exception ex)
  508. {
  509. LogMessage($"断开APS7100失败: {ex.Message}");
  510. }
  511. finally
  512. {
  513. _isDisconnectingAPS7100 = false;
  514. }
  515. }
  516. private async Task ShowConnectionDialogAsync(DeviceType deviceType)
  517. {
  518. using (var dialog = new ConnectionDialog(_appSettings, deviceType))
  519. {
  520. if (dialog.ShowDialog() == DialogResult.OK)
  521. {
  522. _appSettings = dialog.Settings;
  523. _configService.SaveAppSettings(_appSettings);
  524. if (deviceType == DeviceType.APS7100)
  525. await ConnectAPS7100Async();
  526. else
  527. await ConnectPSW250Async();
  528. }
  529. }
  530. }
  531. #endregion
  532. #region PSW250 Connection
  533. private async void btnConnectPSW250_Click(object sender, EventArgs e)
  534. {
  535. // 如果正在连接中,忽略点击
  536. if (_isConnectingPSW250)
  537. {
  538. LogMessage("PSW250 正在连接中,请稍候...");
  539. return;
  540. }
  541. if (_devicePSW250 != null && _devicePSW250.IsConnected)
  542. {
  543. DisconnectPSW250();
  544. }
  545. else
  546. {
  547. await ShowConnectionDialogAsync(DeviceType.PSW250);
  548. }
  549. }
  550. private async void menuConnectPSW250_Click(object sender, EventArgs e)
  551. {
  552. if (_devicePSW250 != null && _devicePSW250.IsConnected)
  553. {
  554. DisconnectPSW250();
  555. }
  556. else
  557. {
  558. await ShowConnectionDialogAsync(DeviceType.PSW250);
  559. }
  560. }
  561. private async Task ConnectPSW250Async()
  562. {
  563. // 禁用按钮,显示连接中状态
  564. btnConnectPSW250.Enabled = false;
  565. btnConnectPSW250.Text = "连接中...";
  566. menuConnectPSW250.Enabled = false;
  567. _isConnectingPSW250 = true;
  568. try
  569. {
  570. LogMessage("PSW250 开始连接...");
  571. // 确保旧连接被正确清理
  572. if (_devicePSW250 != null)
  573. {
  574. LogMessage(" 清理旧连接...");
  575. try { _devicePSW250.Disconnect(); } catch { }
  576. try { _devicePSW250.Dispose(); } catch { }
  577. _devicePSW250 = null;
  578. _controllerPSW250 = null;
  579. }
  580. // 等待后台任务完成和资源释放
  581. await Task.Delay(500);
  582. // 强制垃圾回收以释放网络资源
  583. GC.Collect();
  584. GC.WaitForPendingFinalizers();
  585. await Task.Delay(200);
  586. // 尝试连接(带重试)
  587. // 设备断电重启后可能需要时间初始化网络服务,使用递增间隔重试
  588. int maxRetries = 5;
  589. int[] retryDelays = { 0, 1000, 2000, 3000, 5000 }; // 递增间隔
  590. Exception? lastException = null;
  591. for (int retry = 0; retry < maxRetries; retry++)
  592. {
  593. if (retry > 0)
  594. {
  595. int delay = retryDelays[Math.Min(retry, retryDelays.Length - 1)];
  596. LogMessage($" [PSW250] 等待 {delay / 1000.0:F1} 秒后重试连接 ({retry}/{maxRetries - 1})...");
  597. await Task.Delay(delay);
  598. }
  599. try
  600. {
  601. await Task.Run(() =>
  602. {
  603. _devicePSW250 = new ScpiDevice();
  604. if (_appSettings.PSW250ConnectionType == "Serial")
  605. {
  606. if (string.IsNullOrEmpty(_appSettings.PSW250ComPort))
  607. {
  608. throw new Exception("未配置串口");
  609. }
  610. _devicePSW250.ConnectSerial(_appSettings.PSW250ComPort, _appSettings.PSW250BaudRate);
  611. }
  612. else
  613. {
  614. _devicePSW250.ConnectEthernet(_appSettings.PSW250IpAddress, _appSettings.PSW250Port);
  615. }
  616. _controllerPSW250 = new PSW250Controller(_devicePSW250);
  617. });
  618. string connInfo = _appSettings.PSW250ConnectionType == "Serial"
  619. ? $"{_appSettings.PSW250ComPort} @ {_appSettings.PSW250BaudRate}"
  620. : $"{_appSettings.PSW250IpAddress}:{_appSettings.PSW250Port}";
  621. LogMessage($"PSW250 连接成功: {connInfo}");
  622. // 获取设备标识(异步执行,避免阻塞UI)
  623. _cachedPSW250IDN = await Task.Run(() => _controllerPSW250!.GetIdentification());
  624. LogMessage($"✓ PSW250 设备识别: {_cachedPSW250IDN}");
  625. // 进入远程控制模式
  626. await Task.Run(() => _controllerPSW250!.SetRemoteMode());
  627. LogMessage($"✓ PSW250 已进入远程控制模式");
  628. UpdatePSW250Status();
  629. UpdateManualTestController(DeviceType.PSW250);
  630. // 更新 Modbus 服务的控制器引用
  631. _modbusService?.UpdateControllers(_controllerAPS7100, _controllerPSW250);
  632. // 连接成功,退出重试循环
  633. break;
  634. }
  635. catch (Exception ex)
  636. {
  637. lastException = ex;
  638. LogMessage($" [PSW250] 连接尝试 {retry + 1} 失败: {ex.Message}");
  639. // 清理本次失败的连接资源
  640. if (_devicePSW250 != null)
  641. {
  642. try { _devicePSW250.Disconnect(); } catch { }
  643. try { _devicePSW250.Dispose(); } catch { }
  644. _devicePSW250 = null;
  645. }
  646. _controllerPSW250 = null;
  647. // 如果不是最后一次重试,继续
  648. if (retry < maxRetries - 1)
  649. {
  650. continue;
  651. }
  652. // 最后一次重试也失败了
  653. int totalWaitTime = 0;
  654. for (int i = 0; i < maxRetries; i++) totalWaitTime += retryDelays[Math.Min(i, retryDelays.Length - 1)];
  655. LogMessage($"[PSW250] 连接失败(已尝试 {maxRetries} 次,总等待约 {totalWaitTime / 1000 + maxRetries * 5} 秒)");
  656. LogMessage($" 错误: {ex.Message}");
  657. if (ex.InnerException != null)
  658. {
  659. LogMessage($" 内部错误: {ex.InnerException.Message}");
  660. }
  661. LogMessage($" 提示: 如果设备刚断电重启,请等待设备完全启动后再试");
  662. UpdatePSW250Status();
  663. }
  664. } // end for retry loop
  665. }
  666. finally
  667. {
  668. // 恢复按钮状态
  669. _isConnectingPSW250 = false;
  670. btnConnectPSW250.Enabled = true;
  671. menuConnectPSW250.Enabled = true;
  672. UpdatePSW250Status(); // 更新按钮文字
  673. }
  674. }
  675. // 防止重复断开
  676. private volatile bool _isDisconnectingPSW250 = false;
  677. private void DisconnectPSW250()
  678. {
  679. // 防止重复断开
  680. if (_isDisconnectingPSW250) return;
  681. if (_devicePSW250 == null && _controllerPSW250 == null) return;
  682. _isDisconnectingPSW250 = true;
  683. try
  684. {
  685. // 断开前返回本地模式
  686. if (_controllerPSW250 != null && _devicePSW250?.IsConnected == true)
  687. {
  688. try
  689. {
  690. _controllerPSW250.SetLocalMode();
  691. }
  692. catch { /* 忽略断开时的错误 */ }
  693. }
  694. var device = _devicePSW250;
  695. _devicePSW250 = null;
  696. _controllerPSW250 = null;
  697. if (device != null)
  698. {
  699. try { device.Disconnect(); } catch { }
  700. try { device.Dispose(); } catch { }
  701. }
  702. LogMessage("PSW250 已断开连接");
  703. UpdatePSW250Status();
  704. UpdateManualTestController(DeviceType.PSW250);
  705. // 更新 Modbus 服务的控制器引用
  706. _modbusService?.UpdateControllers(_controllerAPS7100, _controllerPSW250);
  707. }
  708. catch (Exception ex)
  709. {
  710. LogMessage($"断开PSW250失败: {ex.Message}");
  711. }
  712. finally
  713. {
  714. _isDisconnectingPSW250 = false;
  715. }
  716. }
  717. #endregion
  718. #region Status Updates
  719. private void UpdateAPS7100Status()
  720. {
  721. bool connected = _deviceAPS7100 != null && _deviceAPS7100.IsConnected;
  722. if (connected)
  723. {
  724. pnlAPS7100Indicator.BackColor = Color.LimeGreen;
  725. lblAPS7100ConnStatus.Text = "已连接";
  726. lblAPS7100ConnStatus.ForeColor = Color.Green;
  727. string connInfo = _appSettings.APS7100ConnectionType == "Serial"
  728. ? $"串口: {_appSettings.APS7100ComPort}"
  729. : $"网口: {_appSettings.APS7100IpAddress}:{_appSettings.APS7100Port}";
  730. lblAPS7100ConnInfo.Text = $"连接信息: {connInfo}";
  731. // 使用缓存的设备标识,避免阻塞UI
  732. string idn = !string.IsNullOrEmpty(_cachedAPS7100IDN) ? _cachedAPS7100IDN : "--";
  733. lblAPS7100IDN.Text = $"设备: {(idn.Length > 40 ? idn.Substring(0, 40) + "..." : idn)}";
  734. btnConnectAPS7100.Text = "断 开";
  735. btnConnectAPS7100.BackColor = Color.LightCoral;
  736. menuConnectAPS7100.Text = "断开 APS-7100";
  737. }
  738. else
  739. {
  740. pnlAPS7100Indicator.BackColor = Color.Gray;
  741. lblAPS7100ConnStatus.Text = "未连接";
  742. lblAPS7100ConnStatus.ForeColor = Color.Gray;
  743. lblAPS7100ConnInfo.Text = "连接信息: --";
  744. lblAPS7100IDN.Text = "设备: --";
  745. lblAPS7100OutputStatus.Text = "OFF";
  746. lblAPS7100OutputStatus.ForeColor = Color.Gray;
  747. lblAPS7100VoltageValue.Text = "--- V";
  748. lblAPS7100CurrentValue.Text = "--- A";
  749. lblAPS7100PowerValue.Text = "--- W";
  750. lblAPS7100FreqValue.Text = "--- Hz";
  751. lblAPS7100PFValue.Text = "---";
  752. btnConnectAPS7100.Text = "连 接";
  753. btnConnectAPS7100.BackColor = Color.LightGreen;
  754. menuConnectAPS7100.Text = "连接 APS-7100...";
  755. // 清除缓存
  756. _cachedAPS7100IDN = "";
  757. }
  758. UpdateTrayStatus();
  759. }
  760. private void UpdatePSW250Status()
  761. {
  762. bool connected = _devicePSW250 != null && _devicePSW250.IsConnected;
  763. if (connected)
  764. {
  765. pnlPSW250Indicator.BackColor = Color.LimeGreen;
  766. lblPSW250ConnStatus.Text = "已连接";
  767. lblPSW250ConnStatus.ForeColor = Color.Green;
  768. string connInfo = _appSettings.PSW250ConnectionType == "Serial"
  769. ? $"串口: {_appSettings.PSW250ComPort}"
  770. : $"网口: {_appSettings.PSW250IpAddress}:{_appSettings.PSW250Port}";
  771. lblPSW250ConnInfo.Text = $"连接信息: {connInfo}";
  772. // 使用缓存的设备标识,避免阻塞UI
  773. string idn = !string.IsNullOrEmpty(_cachedPSW250IDN) ? _cachedPSW250IDN : "--";
  774. lblPSW250IDN.Text = $"设备: {(idn.Length > 40 ? idn.Substring(0, 40) + "..." : idn)}";
  775. btnConnectPSW250.Text = "断 开";
  776. btnConnectPSW250.BackColor = Color.LightCoral;
  777. menuConnectPSW250.Text = "断开 PSW-250";
  778. }
  779. else
  780. {
  781. pnlPSW250Indicator.BackColor = Color.Gray;
  782. lblPSW250ConnStatus.Text = "未连接";
  783. lblPSW250ConnStatus.ForeColor = Color.Gray;
  784. lblPSW250ConnInfo.Text = "连接信息: --";
  785. lblPSW250IDN.Text = "设备: --";
  786. lblPSW250OutputStatus.Text = "OFF";
  787. lblPSW250OutputStatus.ForeColor = Color.Gray;
  788. lblPSW250ModeValue.Text = "--";
  789. lblPSW250ModeValue.ForeColor = Color.DarkOrange;
  790. lblPSW250VoltageValue.Text = "--- V";
  791. lblPSW250CurrentValue.Text = "--- A";
  792. lblPSW250PowerValue.Text = "--- W";
  793. btnConnectPSW250.Text = "连 接";
  794. btnConnectPSW250.BackColor = Color.LightGreen;
  795. menuConnectPSW250.Text = "连接 PSW-250...";
  796. // 清除缓存
  797. _cachedPSW250IDN = "";
  798. }
  799. UpdateTrayStatus();
  800. }
  801. private void UpdateModbusStatus()
  802. {
  803. bool running = _modbusService != null && _modbusService.IsRunning;
  804. if (running)
  805. {
  806. lblModbusStatusText.Text = "● 运行中";
  807. lblModbusStatusText.ForeColor = Color.Green;
  808. menuModbusStart.Text = "停止服务";
  809. }
  810. else
  811. {
  812. lblModbusStatusText.Text = "● 未启动";
  813. lblModbusStatusText.ForeColor = Color.Gray;
  814. menuModbusStart.Text = "启动服务";
  815. // 服务未运行时重置客户端状态显示
  816. lblModbusClientCount.Text = "客户端: --";
  817. lblModbusClientCount.ForeColor = Color.Gray;
  818. lblModbusRequestCount.Text = "请求: --";
  819. lblModbusLastRequest.Text = "最后通讯: --";
  820. }
  821. lblModbusPort.Text = $"端口: {_appSettings.ModbusPort}";
  822. lblModbusConfigCount.Text = $"规则: {_modbusMappings.Count} 条";
  823. }
  824. /// <summary>
  825. /// 更新 Modbus 客户端连接状态显示
  826. /// </summary>
  827. private void UpdateModbusClientStatus(int clientCount, int requestCount, DateTime lastRequest)
  828. {
  829. // 更新客户端数
  830. lblModbusClientCount.Text = $"客户端: {clientCount}";
  831. lblModbusClientCount.ForeColor = clientCount > 0 ? Color.Green : Color.Gray;
  832. // 更新请求数
  833. lblModbusRequestCount.Text = $"请求: {requestCount}";
  834. // 更新最后通讯时间
  835. if (lastRequest > DateTime.MinValue)
  836. {
  837. var elapsed = DateTime.Now - lastRequest;
  838. if (elapsed.TotalSeconds < 60)
  839. lblModbusLastRequest.Text = $"最后通讯: {elapsed.TotalSeconds:F0}秒前";
  840. else if (elapsed.TotalMinutes < 60)
  841. lblModbusLastRequest.Text = $"最后通讯: {elapsed.TotalMinutes:F0}分钟前";
  842. else
  843. lblModbusLastRequest.Text = $"最后通讯: {lastRequest:HH:mm:ss}";
  844. }
  845. else
  846. {
  847. lblModbusLastRequest.Text = "最后通讯: --";
  848. }
  849. }
  850. /// <summary>
  851. /// 实时更新 Modbus 心跳和设备状态显示
  852. /// </summary>
  853. private void UpdateModbusHeartbeatDisplay()
  854. {
  855. if (_modbusService != null && _modbusService.IsRunning)
  856. {
  857. // 显示心跳(地址:值)
  858. lblModbusHeartbeat.Text = $"心跳[{_appSettings.HeartbeatRegisterAddress}]: {_modbusService.HeartbeatValue}";
  859. // 显示设备状态(地址:值)
  860. var (aps, psw) = _modbusService.DeviceStatus;
  861. ushort statusValue = 0;
  862. if (aps) statusValue |= 0x0001;
  863. if (psw) statusValue |= 0x0002;
  864. string statusText = "";
  865. if (aps && psw) statusText = "APS+PSW";
  866. else if (aps) statusText = "APS";
  867. else if (psw) statusText = "PSW";
  868. else statusText = "无";
  869. lblModbusDeviceStatus.Text = $"设备[{_appSettings.DeviceStatusRegisterAddress}]: {statusValue} ({statusText})";
  870. lblModbusDeviceStatus.ForeColor = (aps || psw) ? Color.DarkCyan : Color.Gray;
  871. }
  872. else
  873. {
  874. lblModbusHeartbeat.Text = "心跳: --";
  875. lblModbusDeviceStatus.Text = "设备: --";
  876. lblModbusDeviceStatus.ForeColor = Color.Gray;
  877. }
  878. }
  879. #endregion
  880. #region Timer Tick
  881. // 防止测量操作重叠
  882. private volatile bool _isMeasuring = false;
  883. private async void MeasureTimer_Tick(object? sender, EventArgs e)
  884. {
  885. // 如果正在连接或正在测量,跳过本次
  886. if (_isConnectingAPS7100 || _isConnectingPSW250 || _isMeasuring)
  887. return;
  888. _isMeasuring = true;
  889. try
  890. {
  891. bool aps7100Connected = _deviceAPS7100?.IsConnected == true && !_isConnectingAPS7100;
  892. bool psw250Connected = _devicePSW250?.IsConnected == true && !_isConnectingPSW250;
  893. // 更新 Modbus 服务的设备状态(用于心跳)
  894. _modbusService?.UpdateDeviceStatus(aps7100Connected, psw250Connected);
  895. // 实时更新 Modbus 心跳和设备状态显示
  896. UpdateModbusHeartbeatDisplay();
  897. // 并行执行两个设备的测量,避免串行等待
  898. Task? aps7100Task = null;
  899. Task? psw250Task = null;
  900. // APS7100 测量任务
  901. if (_controllerAPS7100 != null && aps7100Connected)
  902. {
  903. var controller = _controllerAPS7100;
  904. aps7100Task = Task.Run(() =>
  905. {
  906. // 为每个命令单独处理异常,避免一个失败导致全部失败
  907. double voltage = 0, current = 0, power = 0, frequency = 0, powerFactor = 0;
  908. bool outputOn = false;
  909. int failCount = 0;
  910. try { voltage = controller.MeasureVoltage(); } catch { failCount++; }
  911. try { current = controller.MeasureCurrent(); } catch { failCount++; }
  912. try { power = controller.MeasurePower(); } catch { failCount++; }
  913. try { frequency = controller.MeasureFrequency(); } catch { failCount++; }
  914. try { powerFactor = controller.MeasurePowerFactor(); } catch { failCount++; }
  915. try { outputOn = controller.GetOutputState(); } catch { failCount++; }
  916. return new
  917. {
  918. Voltage = voltage,
  919. Current = current,
  920. Power = power,
  921. Frequency = frequency,
  922. PowerFactor = powerFactor,
  923. OutputOn = outputOn,
  924. ConnectionLost = failCount >= 2
  925. }; // 2个以上命令失败认为连接丢失
  926. }).ContinueWith(t =>
  927. {
  928. if (t.IsCompletedSuccessfully && !this.IsDisposed)
  929. {
  930. var m = t.Result;
  931. this.BeginInvoke((MethodInvoker)delegate
  932. {
  933. if (m.ConnectionLost)
  934. {
  935. // 连接丢失,自动断开
  936. LogMessage("⚠ APS7100 连接丢失,设备可能已断电");
  937. DisconnectAPS7100();
  938. }
  939. else
  940. {
  941. lblAPS7100VoltageValue.Text = $"{m.Voltage:F2} V";
  942. lblAPS7100CurrentValue.Text = $"{m.Current:F3} A";
  943. lblAPS7100PowerValue.Text = $"{m.Power:F2} W";
  944. lblAPS7100FreqValue.Text = $"{m.Frequency:F2} Hz";
  945. lblAPS7100PFValue.Text = $"{m.PowerFactor:F3}";
  946. lblAPS7100OutputStatus.Text = m.OutputOn ? "ON" : "OFF";
  947. lblAPS7100OutputStatus.ForeColor = m.OutputOn ? Color.Green : Color.Gray;
  948. }
  949. });
  950. }
  951. }, TaskScheduler.Default);
  952. }
  953. // PSW250 测量任务
  954. if (_controllerPSW250 != null && psw250Connected)
  955. {
  956. var controller = _controllerPSW250;
  957. psw250Task = Task.Run(() =>
  958. {
  959. double voltage = 0, current = 0, power = 0;
  960. bool outputOn = false;
  961. int failCount = 0;
  962. try { voltage = controller.MeasureVoltage(); } catch { failCount++; }
  963. try { current = controller.MeasureCurrent(); } catch { failCount++; }
  964. try { power = controller.MeasurePower(); } catch { failCount++; }
  965. try { outputOn = controller.GetOutputState(); } catch { failCount++; }
  966. // 获取 OUTP:MODE 控制优先级设置
  967. string outputMode = "CVHS";
  968. if (controller is Controllers.PSW250Controller pswController)
  969. {
  970. try
  971. {
  972. var mode = pswController.GetOutputMode();
  973. outputMode = mode.ToString();
  974. }
  975. catch { outputMode = "--"; }
  976. }
  977. // 判断实际运行状态(CV/CC)
  978. string runState = "CV";
  979. try
  980. {
  981. var setCurrent = controller.GetCurrent();
  982. if (setCurrent > 0.01 && current >= setCurrent * 0.98)
  983. {
  984. runState = "CC";
  985. }
  986. }
  987. catch { }
  988. return new
  989. {
  990. Voltage = voltage,
  991. Current = current,
  992. Power = power,
  993. OutputOn = outputOn,
  994. OutputMode = outputMode,
  995. RunState = runState,
  996. ConnectionLost = failCount >= 2 // 2个以上命令失败认为连接丢失
  997. };
  998. }).ContinueWith(t =>
  999. {
  1000. if (t.IsCompletedSuccessfully && !this.IsDisposed)
  1001. {
  1002. var m = t.Result;
  1003. this.BeginInvoke((MethodInvoker)delegate
  1004. {
  1005. if (m.ConnectionLost)
  1006. {
  1007. // 连接丢失,自动断开
  1008. LogMessage("⚠ PSW250 连接丢失,设备可能已断电");
  1009. DisconnectPSW250();
  1010. }
  1011. else
  1012. {
  1013. lblPSW250VoltageValue.Text = $"{m.Voltage:F2} V";
  1014. lblPSW250CurrentValue.Text = $"{m.Current:F3} A";
  1015. lblPSW250PowerValue.Text = $"{m.Power:F2} W";
  1016. lblPSW250OutputStatus.Text = m.OutputOn ? "ON" : "OFF";
  1017. lblPSW250OutputStatus.ForeColor = m.OutputOn ? Color.Green : Color.Gray;
  1018. // 显示: 运行状态(控制优先级),如 "CV(CVHS)" 或 "CC(CCHS)"
  1019. lblPSW250ModeValue.Text = $"{m.RunState}({m.OutputMode})";
  1020. lblPSW250ModeValue.ForeColor = m.RunState == "CC" ? Color.OrangeRed : Color.DodgerBlue;
  1021. }
  1022. });
  1023. }
  1024. }, TaskScheduler.Default);
  1025. }
  1026. // 等待所有任务完成(并行执行,不会互相阻塞)
  1027. var tasks = new List<Task>();
  1028. if (aps7100Task != null) tasks.Add(aps7100Task);
  1029. if (psw250Task != null) tasks.Add(psw250Task);
  1030. if (tasks.Count > 0)
  1031. {
  1032. await Task.WhenAll(tasks);
  1033. }
  1034. }
  1035. catch { }
  1036. finally
  1037. {
  1038. _isMeasuring = false;
  1039. }
  1040. }
  1041. #endregion
  1042. #region Menu Events
  1043. private void menuSettings_Click(object sender, EventArgs e)
  1044. {
  1045. using (var form = new SettingsForm())
  1046. {
  1047. if (form.ShowDialog() == DialogResult.OK)
  1048. {
  1049. _appSettings = _configService.LoadAppSettings();
  1050. UpdateModbusStatus();
  1051. }
  1052. }
  1053. }
  1054. private void menuExit_Click(object sender, EventArgs e)
  1055. {
  1056. this.Close();
  1057. }
  1058. private void menuManualTestAPS7100_Click(object sender, EventArgs e)
  1059. {
  1060. if (_manualTestFormAPS7100 == null || _manualTestFormAPS7100.IsDisposed)
  1061. {
  1062. // 暂停主窗口测量定时器,避免与手动测试冲突
  1063. // ⚠ APS7100 收到任何 SCPI 命令后会自动进入远程模式
  1064. _measureTimer.Stop();
  1065. LogMessage("ℹ 主窗口测量已暂停(手动测试窗口已打开)");
  1066. _manualTestFormAPS7100 = new ManualTestForm(_controllerAPS7100, DeviceType.APS7100);
  1067. // 设置 Modbus 轮询控制回调
  1068. _manualTestFormAPS7100.OnSuspendModbusPolling = () =>
  1069. {
  1070. _modbusService?.SuspendPolling();
  1071. LogMessage("ℹ Modbus 服务轮询已暂停");
  1072. };
  1073. _manualTestFormAPS7100.OnResumeModbusPolling = () =>
  1074. {
  1075. _modbusService?.ResumePolling();
  1076. LogMessage("ℹ Modbus 服务轮询已恢复");
  1077. };
  1078. _manualTestFormAPS7100.FormClosed += (s, args) =>
  1079. {
  1080. // 手动测试窗口关闭后,恢复主窗口测量和 Modbus 轮询
  1081. _modbusService?.ResumePolling();
  1082. if (_deviceAPS7100?.IsConnected == true || _devicePSW250?.IsConnected == true)
  1083. {
  1084. _measureTimer.Start();
  1085. LogMessage("ℹ 主窗口测量已恢复");
  1086. }
  1087. };
  1088. _manualTestFormAPS7100.Show();
  1089. }
  1090. else
  1091. {
  1092. _manualTestFormAPS7100.Focus();
  1093. }
  1094. }
  1095. private void menuManualTestPSW250_Click(object sender, EventArgs e)
  1096. {
  1097. if (_manualTestFormPSW250 == null || _manualTestFormPSW250.IsDisposed)
  1098. {
  1099. // 暂停主窗口测量定时器,避免与手动测试冲突
  1100. _measureTimer.Stop();
  1101. LogMessage("ℹ 主窗口测量已暂停(手动测试窗口已打开)");
  1102. _manualTestFormPSW250 = new ManualTestForm(_controllerPSW250, DeviceType.PSW250);
  1103. // 设置 Modbus 轮询控制回调
  1104. _manualTestFormPSW250.OnSuspendModbusPolling = () =>
  1105. {
  1106. _modbusService?.SuspendPolling();
  1107. LogMessage("ℹ Modbus 服务轮询已暂停");
  1108. };
  1109. _manualTestFormPSW250.OnResumeModbusPolling = () =>
  1110. {
  1111. _modbusService?.ResumePolling();
  1112. LogMessage("ℹ Modbus 服务轮询已恢复");
  1113. };
  1114. _manualTestFormPSW250.FormClosed += (s, args) =>
  1115. {
  1116. // 手动测试窗口关闭后,恢复主窗口测量和 Modbus 轮询
  1117. _modbusService?.ResumePolling();
  1118. if (_deviceAPS7100?.IsConnected == true || _devicePSW250?.IsConnected == true)
  1119. {
  1120. _measureTimer.Start();
  1121. LogMessage("ℹ 主窗口测量已恢复");
  1122. }
  1123. };
  1124. _manualTestFormPSW250.Show();
  1125. }
  1126. else
  1127. {
  1128. _manualTestFormPSW250.Focus();
  1129. }
  1130. }
  1131. private void menuModbusConfig_Click(object sender, EventArgs e)
  1132. {
  1133. using (var form = new ModbusConfigForm(_modbusMappings))
  1134. {
  1135. if (form.ShowDialog() == DialogResult.OK)
  1136. {
  1137. _modbusMappings = form.Mappings;
  1138. // 确定配置文件路径
  1139. string configPath;
  1140. if (!string.IsNullOrEmpty(form.LastLoadedFilePath))
  1141. {
  1142. // 使用导入的配置文件路径
  1143. configPath = form.LastLoadedFilePath;
  1144. }
  1145. else if (!string.IsNullOrEmpty(_appSettings.ModbusConfigPath))
  1146. {
  1147. // 使用之前保存的路径
  1148. configPath = _appSettings.ModbusConfigPath;
  1149. }
  1150. else
  1151. {
  1152. // 使用默认路径
  1153. configPath = ConfigService.DefaultModbusConfigPath;
  1154. }
  1155. // 自动保存配置到文件
  1156. try
  1157. {
  1158. _configService.SaveModbusConfig(configPath, _modbusMappings);
  1159. _appSettings.ModbusConfigPath = configPath;
  1160. _configService.SaveAppSettings(_appSettings);
  1161. LogMessage($"✓ Modbus 配置已保存: {configPath} ({_modbusMappings.Count} 条规则)");
  1162. }
  1163. catch (Exception ex)
  1164. {
  1165. LogMessage($"⚠ 保存配置文件失败: {ex.Message}");
  1166. MessageBox.Show($"保存配置文件失败: {ex.Message}\n配置仅在本次运行有效。",
  1167. "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  1168. }
  1169. UpdateModbusStatus();
  1170. // 如果 Modbus 服务正在运行,提示用户重启
  1171. if (_modbusService != null && _modbusService.IsRunning)
  1172. {
  1173. if (MessageBox.Show("配置已更新,是否重启 Modbus 服务以使更改生效?",
  1174. "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  1175. {
  1176. StopModbusService();
  1177. StartModbusService();
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. private void menuModbusStart_Click(object sender, EventArgs e)
  1184. {
  1185. ToggleModbusService();
  1186. }
  1187. private void menuModbusSimulation_Click(object sender, EventArgs e)
  1188. {
  1189. bool isSimulation = menuModbusSimulation.Checked;
  1190. if (_modbusService != null)
  1191. {
  1192. _modbusService.SimulationMode = isSimulation;
  1193. }
  1194. if (isSimulation)
  1195. {
  1196. LogMessage("✓ 仿真模式已开启 - 设备未连接时也会生成命令(仅记录,不发送)");
  1197. }
  1198. else
  1199. {
  1200. LogMessage("✗ 仿真模式已关闭 - 仅在设备连接时发送命令");
  1201. }
  1202. }
  1203. private void menuModbusRegisterViewer_Click(object sender, EventArgs e)
  1204. {
  1205. if (_modbusService == null || !_modbusService.IsRunning)
  1206. {
  1207. MessageBox.Show("请先启动 Modbus 服务后再查看寄存器。", "提示",
  1208. MessageBoxButtons.OK, MessageBoxIcon.Information);
  1209. return;
  1210. }
  1211. using (var form = new RegisterViewerForm(_modbusService))
  1212. {
  1213. form.ShowDialog(this);
  1214. }
  1215. }
  1216. #endregion
  1217. #region Modbus Service
  1218. private void ToggleModbusService()
  1219. {
  1220. if (_modbusService != null && _modbusService.IsRunning)
  1221. {
  1222. StopModbusService();
  1223. }
  1224. else
  1225. {
  1226. StartModbusService();
  1227. }
  1228. }
  1229. private void StartModbusService()
  1230. {
  1231. if (_modbusService != null && _modbusService.IsRunning) return;
  1232. if (_modbusMappings.Count == 0)
  1233. {
  1234. LogMessage("Modbus 配置为空,无法启动服务");
  1235. return;
  1236. }
  1237. try
  1238. {
  1239. // 传入两个控制器,支持同时控制两个设备
  1240. _modbusService = new ModbusTcpServerService(_controllerAPS7100, _controllerPSW250);
  1241. _modbusService.OnLog += (msg) =>
  1242. {
  1243. if (!this.IsDisposed && this.IsHandleCreated)
  1244. {
  1245. this.Invoke((MethodInvoker)delegate { LogMessage(msg); });
  1246. }
  1247. };
  1248. // 订阅客户端状态变化事件
  1249. _modbusService.OnClientStatusChanged += (clientCount, requestCount, lastRequest) =>
  1250. {
  1251. if (!this.IsDisposed && this.IsHandleCreated)
  1252. {
  1253. this.Invoke((MethodInvoker)delegate
  1254. {
  1255. UpdateModbusClientStatus(clientCount, requestCount, lastRequest);
  1256. });
  1257. }
  1258. };
  1259. // 设置心跳寄存器地址
  1260. _modbusService.SetHeartbeatAddresses(
  1261. _appSettings.HeartbeatRegisterAddress,
  1262. _appSettings.DeviceStatusRegisterAddress);
  1263. // 立即更新设备状态
  1264. bool aps7100Connected = _deviceAPS7100?.IsConnected == true;
  1265. bool psw250Connected = _devicePSW250?.IsConnected == true;
  1266. _modbusService.UpdateDeviceStatus(aps7100Connected, psw250Connected);
  1267. // 设置仿真模式状态
  1268. _modbusService.SimulationMode = menuModbusSimulation.Checked;
  1269. // 获取绑定IP,如果为空则使用0.0.0.0(所有接口)
  1270. string bindIp = string.IsNullOrEmpty(_appSettings.ModbusBindIpAddress)
  1271. ? "0.0.0.0"
  1272. : _appSettings.ModbusBindIpAddress;
  1273. _modbusService.Start(bindIp, _appSettings.ModbusPort, _modbusMappings);
  1274. string bindInfo = bindIp == "0.0.0.0" ? "所有接口" : bindIp;
  1275. LogMessage($"Modbus TCP 服务已启动,绑定: {bindInfo}:{_appSettings.ModbusPort}");
  1276. LogMessage($" 心跳寄存器地址: {_appSettings.HeartbeatRegisterAddress}");
  1277. LogMessage($" 设备状态寄存器地址: {_appSettings.DeviceStatusRegisterAddress}");
  1278. }
  1279. catch (Exception ex)
  1280. {
  1281. LogMessage($"启动 Modbus 服务失败: {ex.Message}");
  1282. _modbusService?.Stop();
  1283. _modbusService = null;
  1284. }
  1285. UpdateModbusStatus();
  1286. }
  1287. private void StopModbusService()
  1288. {
  1289. if (_modbusService == null) return;
  1290. _modbusService.Stop();
  1291. _modbusService.Dispose();
  1292. _modbusService = null;
  1293. LogMessage("Modbus TCP 服务已停止");
  1294. UpdateModbusStatus();
  1295. }
  1296. #endregion
  1297. #region Helper Methods
  1298. private void UpdateManualTestController(DeviceType deviceType)
  1299. {
  1300. if (deviceType == DeviceType.APS7100)
  1301. {
  1302. _manualTestFormAPS7100?.UpdateController(_controllerAPS7100);
  1303. }
  1304. else
  1305. {
  1306. _manualTestFormPSW250?.UpdateController(_controllerPSW250);
  1307. }
  1308. }
  1309. private void btnClearLog_Click(object sender, EventArgs e) => txtLog.Clear();
  1310. private void LogMessage(string msg)
  1311. {
  1312. if (this.InvokeRequired)
  1313. {
  1314. this.Invoke(new Action<string>(LogMessage), msg);
  1315. return;
  1316. }
  1317. txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {msg}\r\n");
  1318. }
  1319. protected override void OnFormClosing(FormClosingEventArgs e)
  1320. {
  1321. // 如果是用户点击关闭按钮,最小化到托盘而不是退出
  1322. if (e.CloseReason == CloseReason.UserClosing)
  1323. {
  1324. e.Cancel = true;
  1325. this.WindowState = FormWindowState.Minimized;
  1326. return;
  1327. }
  1328. // 真正退出时清理资源
  1329. CleanupResources();
  1330. if (notifyIcon != null)
  1331. {
  1332. notifyIcon.Visible = false;
  1333. notifyIcon.Dispose();
  1334. }
  1335. base.OnFormClosing(e);
  1336. }
  1337. #endregion
  1338. }
  1339. }