MainWindow.xaml.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. using Panuon.WPF.UI;
  2. using SWRIS.Core;
  3. using SWRIS.Dtos;
  4. using SWRIS.Enums;
  5. using SWRIS.Events;
  6. using SWRIS.Extensions;
  7. using SWRIS.Models;
  8. using SWRIS.Models.ViewModel;
  9. using SWRIS.Pages;
  10. using SWRIS.Repository;
  11. using System;
  12. using System.ComponentModel;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Speech.Synthesis;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Windows;
  20. using System.Windows.Controls;
  21. using System.Windows.Markup;
  22. using System.Windows.Threading;
  23. using Tools = SWRIS.Extensions.Tools;
  24. namespace SWRIS
  25. {
  26. /// <summary>
  27. /// MainWindow.xaml 的交互逻辑
  28. /// </summary>
  29. public partial class MainWindow : WindowX, IComponentConnector
  30. {
  31. // 屏幕比例阈值
  32. private const double ASPECT_RATIO_THRESHOLD = 1.5; // 大于此值视为宽屏(16:9),小于此值视为方屏(4:3)
  33. // 预状态(PreStop/PreRunning/PreCalibration)等待设备确认的超时阈值
  34. private static readonly long PreStatusTimeoutTicks = TimeSpan.FromSeconds(10).Ticks;
  35. private readonly SpeechSynthesizer speech;
  36. private readonly DispatcherTimer _preStatusTimer;
  37. public MainViewModel MainView { get; set; }
  38. private readonly IRecordRepository _recordRepository;
  39. private readonly IAlarmRepository _alarmRepository;
  40. public MainWindow()
  41. {
  42. InitializeComponent();
  43. _recordRepository = new RecordRepository();
  44. _alarmRepository = new AlarmRepository();
  45. speech = new SpeechSynthesizer()
  46. {
  47. Rate = 1,
  48. Volume = 100
  49. };
  50. MainView = new MainViewModel();
  51. Application.Current.MainWindow = this;
  52. App.TcpServer.ClientConnected += TcpServer_ClientConnected;
  53. App.TcpServer.ClientDisconnected += TcpServer_ClientDisconnected;
  54. App.TcpServer.LiveStreamReceived += TcpServer_LiveStreamReceived;
  55. App.TcpServer.AlarmDataReceived += TcpServer_AlarmDataReceived;
  56. App.TcpServer.DetectionDataReceived += TcpServer_DetectionDataReceived;
  57. App.TcpServer.RealTimeDataReceived += TcpServer_RealTimeDataReceived;
  58. App.TcpServer.FaultDataReceived += TcpServer_FaultDataReceived;
  59. App.TcpServer.DetectionRawDataReceived += TcpServer_DetectionRawDataReceived;
  60. App.TcpServer.DetectionRawDataResultReceived += TcpServer_DetectionRawDataResultReceived;
  61. App.TcpServer.DetectionStatusResultReceived += TcpServer_DetectionStatusResultReceived;
  62. App.TcpServer.SetAbsolutePositionDataReceived += TcpServer_SetAbsolutePositionDataReceived;
  63. App.TcpServer.DebugMessageReceived += TcpServer_DebugMessageReceived;
  64. App.TcpServer.HeartbeatReceived += TcpServer_HeartbeatReceived;
  65. App.TcpServer.UpgradedRequestResultReceived += TcpServer_UpgradedRequestResultReceived;
  66. App.Calibration.ConnectionStateChanged += Calibration_ConnectionStateChanged;
  67. App.Calibration.LimitStateChanged += Calibration_LimitStateChanged;
  68. App.TcpServer.Start();
  69. // 周期性检查预状态(PreStop/PreRunning/PreCalibration)是否超时未获设备确认,超时则回退
  70. _preStatusTimer = new DispatcherTimer
  71. {
  72. Interval = TimeSpan.FromSeconds(2)
  73. };
  74. _preStatusTimer.Tick += PreStatusTimer_Tick;
  75. _preStatusTimer.Start();
  76. DataContext = MainView;
  77. }
  78. /// <summary>
  79. /// 预状态超时检查:设备长时间未确认命令(检测状态结果),清除预状态位,回退为设备实际状态
  80. /// </summary>
  81. private void PreStatusTimer_Tick(object sender, EventArgs e)
  82. {
  83. foreach (var equipmentData in App.DataCenter.Equipments)
  84. {
  85. if (equipmentData.PreStatusTimestamp != 0 &&
  86. DateTime.UtcNow.Ticks - equipmentData.PreStatusTimestamp > PreStatusTimeoutTicks)
  87. {
  88. equipmentData.ClearAllPreStatus();
  89. }
  90. }
  91. }
  92. private async void TcpServer_LiveStreamReceived(object sender, LiveStreamReceivedEventArgs e)
  93. {
  94. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  95. if (equipmentData != null)
  96. {
  97. if (equipmentData.DetectionData?.DetectionNo == equipmentData.DetectionNo)
  98. {
  99. equipmentData.ClearData();
  100. }
  101. await Task.Run(() =>
  102. {
  103. equipmentData.Chart?.AddDataPoints((equipmentData.AbsolutePosition, e.LiveStream), equipmentData.InUseSensor);
  104. equipmentData.AddLiveStream(e.LiveStream);
  105. });
  106. }
  107. }
  108. /// <summary>
  109. /// 接收心跳数据
  110. /// </summary>
  111. private void TcpServer_HeartbeatReceived(object sender, HeartbeatReceviedEventArgs e)
  112. {
  113. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  114. if (equipmentData != null)
  115. {
  116. equipmentData.IsHeartbeatReceived = true;
  117. }
  118. }
  119. /// <summary>
  120. /// 接收调试信息
  121. /// </summary>
  122. private void TcpServer_DebugMessageReceived(object sender, DebugMessageReceivedEventArgs e)
  123. {
  124. if (e.IpAddress.IsNullOrEmpty() && e.SerialNo.IsNullOrEmpty())
  125. {
  126. DebugMessageShow(e.Message);
  127. }
  128. else
  129. {
  130. DebugMessageShow(e.Message, e.IpAddress, e.SerialNo);
  131. }
  132. }
  133. /// <summary>
  134. /// 显示调试信息
  135. /// </summary>
  136. /// <param name="message"> 调试信息 </param>
  137. /// <param name="ipAddress"> IP地址 </param>
  138. /// <param name="serialNo"> 序列号 </param>
  139. public void DebugMessageShow(string message, string ipAddress, string serialNo)
  140. {
  141. if (App.Config.ShowDebugMessage)
  142. {
  143. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => (!serialNo.IsNullOrEmpty() && c.SerialNo == serialNo) || c.IpAddress == ipAddress);
  144. if (equipmentData != null)
  145. {
  146. equipmentData.DebugMessage.DateTime = DateTime.Now;
  147. equipmentData.DebugMessage.Message = message;
  148. }
  149. }
  150. }
  151. /// <summary>
  152. /// 显示调试信息
  153. /// </summary>
  154. /// <param name="message"> 调试信息 </param>
  155. public void DebugMessageShow(string message)
  156. {
  157. if (App.Config.ShowDebugMessage)
  158. {
  159. MainView.DebugMessage.DateTime = DateTime.Now;
  160. MainView.DebugMessage.Message = message;
  161. }
  162. }
  163. /// <summary>
  164. /// 标定限位状态更改
  165. /// </summary>
  166. [Obfuscation(Feature = "virtualization", Exclude = false)]
  167. private void Calibration_LimitStateChanged(object sender, LimitData limitData)
  168. {
  169. foreach (var equipment in App.DataCenter.Equipments)
  170. {
  171. foreach (var limit in equipment.Limits)
  172. {
  173. if (limit.Name == limitData.Name && limit.IsEnable)
  174. {
  175. if (limitData.State == LimitState.AtLimit)
  176. {
  177. limit.State = LimitState.AtLimit;
  178. // 当前运行状态添加预标定状态并记录挂起时间,超时未确认时由定时器回退
  179. equipment.MarkPreStatus(RunningStatus.PreCalibration);
  180. if (App.TcpServer.SendRealTimeAbsolutePositionData(limit.SwitchIndex, (float)limitData.Position, equipment.SerialNo, equipment.ClientSocket))
  181. {
  182. DebugMessageShow($"{limitData.Name}标定成功", equipment.IpAddress, equipment.SerialNo);
  183. }
  184. }
  185. else if (limitData.State == LimitState.NotInLimit)
  186. {
  187. limit.State = LimitState.NotInLimit;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// 标定模块连接状态更改
  195. /// </summary>
  196. private void Calibration_ConnectionStateChanged(object sender, bool isConnect)
  197. {
  198. foreach (var equipment in App.DataCenter.Equipments)
  199. {
  200. foreach (var limit in equipment.Limits)
  201. {
  202. if (isConnect)
  203. {
  204. if (limit.State == LimitState.Offline)
  205. {
  206. limit.State = LimitState.NotInLimit;
  207. }
  208. }
  209. else
  210. {
  211. if (limit.State != LimitState.Offline)
  212. {
  213. limit.State = LimitState.Offline;
  214. }
  215. }
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// 接收检测状态开关结果(0x06 应答):确认 PreStop/PreRunning 预状态
  221. /// </summary>
  222. private void TcpServer_DetectionStatusResultReceived(object sender, DetectionStatusResultReceivedEventArgs e)
  223. {
  224. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  225. if (equipmentData != null)
  226. {
  227. if (equipmentData.RunningStatus.HasFlag(RunningStatus.PreStop))
  228. {
  229. // 按位合并,保留报警/故障等其他状态位
  230. equipmentData.ConfirmPreStatus(RunningStatus.PreStop, RunningStatus.Stopped);
  231. DebugMessageShow("自动检测停止", e.IpAddress, equipmentData.SerialNo);
  232. }
  233. else if (equipmentData.RunningStatus.HasFlag(RunningStatus.PreRunning))
  234. {
  235. // 用启动命令时记录的请求模式恢复检测形式(时域/空域),避免使用切换前的旧模式位
  236. var mode = equipmentData.PreStatusRunningMode == RunningStatus.TemporalNormal
  237. ? RunningStatus.TemporalNormal : RunningStatus.SpatialNormal;
  238. var modeName = mode == RunningStatus.TemporalNormal ? "时域检测" : "空域检测";
  239. equipmentData.ConfirmPreStatus(RunningStatus.PreRunning, mode);
  240. DebugMessageShow($"自动检测开始,检测形式:{modeName}", e.IpAddress, equipmentData.SerialNo);
  241. }
  242. }
  243. }
  244. /// <summary>
  245. /// 接收设置实时位置(标定)应答(0x15):确认 PreCalibration 预状态
  246. /// </summary>
  247. private void TcpServer_SetAbsolutePositionDataReceived(object sender, SetAbsolutePositionDataReceivedEventArgs e)
  248. {
  249. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  250. if (equipmentData != null && e.SetAbsolutePositionData != null)
  251. {
  252. // 标定命令已获得设备应答(无论成败均视为确认),清除预标定位;
  253. // 若还有其他挂起的预状态位则保留其超时时间戳
  254. equipmentData.RunningStatus &= ~RunningStatus.PreCalibration;
  255. if ((equipmentData.RunningStatus & (RunningStatus.PreStop | RunningStatus.PreRunning | RunningStatus.PreCalibration)) == 0)
  256. {
  257. equipmentData.PreStatusTimestamp = 0;
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// 接收故障数据
  263. /// </summary>
  264. private void TcpServer_FaultDataReceived(object sender, FaultDataReceivedEventArgs e)
  265. {
  266. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  267. equipmentData?.AddFault(e.FaultData);
  268. }
  269. /// <summary>
  270. /// 接收实时数据
  271. /// </summary>
  272. [Obfuscation(Feature = "virtualization", Exclude = false)]
  273. private void TcpServer_RealTimeDataReceived(object sender, RealTimeDataReceivedEventArgs e)
  274. {
  275. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  276. if (equipmentData != null)
  277. {
  278. equipmentData.Speed = Math.Round(e.RealTimeData.Speed * 60, 2);
  279. equipmentData.Position = e.RealTimeData.Position;
  280. var preStatusMask = RunningStatus.PreStop | RunningStatus.PreRunning | RunningStatus.PreCalibration;
  281. // 设备实时状态已带预状态位 => 设备已确认命令并进入预状态,清除本地挂起时间戳,预状态以设备状态为准
  282. if ((e.RealTimeData.Status & preStatusMask) != 0)
  283. {
  284. equipmentData.PreStatusTimestamp = 0;
  285. equipmentData.RunningStatus = e.RealTimeData.Status;
  286. }
  287. else if (equipmentData.PreStatusTimestamp != 0)
  288. {
  289. // 存在待设备确认的预状态且设备尚未确认:保留本地挂起的预状态位,等待确认或超时回退
  290. var pendingFlags = equipmentData.RunningStatus & preStatusMask;
  291. equipmentData.RunningStatus = e.RealTimeData.Status | pendingFlags;
  292. }
  293. else
  294. {
  295. // 无挂起预状态:0x0B 只更新设备实际状态位
  296. equipmentData.RunningStatus = e.RealTimeData.Status;
  297. }
  298. equipmentData.AbsolutePosition = e.RealTimeData.AbsolutePosition;
  299. if (equipmentData.RunningStatus == RunningStatus.SpatialNormal)
  300. {
  301. equipmentData.LiftHeight = (equipmentData.RopeLength - equipmentData.AbsolutePosition) / equipmentData.LiftHightRatio;
  302. }
  303. else if (equipmentData.LiftHeight != 0)
  304. {
  305. equipmentData.LiftHeight = 0;
  306. }
  307. equipmentData.Direction = equipmentData.Speed > 0 ? DirectionState.Forward :
  308. (equipmentData.Speed == 0f ? DirectionState.Stoped : DirectionState.Reverse);
  309. equipmentData.AddSpeedData(equipmentData.Speed);
  310. }
  311. }
  312. /// <summary>
  313. /// 客户端连接成功
  314. /// </summary>
  315. [Obfuscation(Feature = "virtualization", Exclude = false)]
  316. private void TcpServer_ClientConnected(object sender, ClientConnectedEventArgs e)
  317. {
  318. var equipment = App.Config.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  319. if (equipment == null)
  320. {
  321. LogHelper.Error($"未找到设备,IP地址:{e.IpAddress}");
  322. return;
  323. }
  324. var server = (TcpServerFrame)sender;
  325. server.SendTurnLiveStreamData(true, equipment.SerialNo, e.ClientSocket);
  326. Thread.Sleep(20);
  327. server.SendSetClockData(DateTime.Now.DateTimeToTimestamp(), equipment.SerialNo, e.ClientSocket);
  328. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  329. if (equipmentData != null)
  330. {
  331. equipmentData.IsConnect = true;
  332. equipmentData.ClientSocket = e.ClientSocket;
  333. if (equipmentData.RunningStatus != RunningStatus.SpatialNormal)
  334. {
  335. equipmentData.RunningStatus |= RunningStatus.SpatialNormal;
  336. }
  337. }
  338. }
  339. /// <summary>
  340. /// 客户端连接断开
  341. /// </summary>
  342. private void TcpServer_ClientDisconnected(object sender, ClientDisconnectedEventArgs e)
  343. {
  344. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  345. if (equipmentData != null)
  346. {
  347. equipmentData.IsConnect = false;
  348. equipmentData.ClientSocket = null;
  349. equipmentData.Speed = 0;
  350. equipmentData.AbsolutePosition = 0;
  351. equipmentData.Position = 0;
  352. equipmentData.Direction = DirectionState.Stoped;
  353. // 断线时清除挂起的预状态位,避免重连后残留影响状态判断
  354. equipmentData.ClearAllPreStatus();
  355. }
  356. }
  357. /// <summary>
  358. /// 接收检测结果
  359. /// </summary>
  360. private void TcpServer_DetectionDataReceived(object sender, DetectionDataReceivedEventArgs e)
  361. {
  362. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  363. if (equipmentData != null)
  364. {
  365. e.DetectionData.DetectionNo = equipmentData.DetectionNo;
  366. equipmentData.DetectionData = e.DetectionData;
  367. }
  368. }
  369. /// <summary>
  370. /// 接检测原始数据结果
  371. /// </summary>
  372. private void TcpServer_DetectionRawDataResultReceived(object sender, DetectionRawDataResultReceivedEventArgs e)
  373. {
  374. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  375. if (equipmentData != null)
  376. {
  377. // 处理检测原始结果数据
  378. if (e.DetectionRawResultData.Code == 0)
  379. {
  380. if (equipmentData.DetectionData != null)
  381. {
  382. equipmentData.DetectionData.RawResultData = e.DetectionRawResultData;
  383. }
  384. }
  385. else
  386. {
  387. LogHelper.Error($"获取检测原始数据失败,错误码:{e.DetectionRawResultData.Code}");
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// 接受检测结果原始数据
  393. /// </summary>
  394. [Obfuscation(Feature = "virtualization", Exclude = false)]
  395. private async void TcpServer_DetectionRawDataReceived(object sender, DetectionRawDataReceivedEventArgs e)
  396. {
  397. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  398. if (equipmentData != null)
  399. {
  400. if (equipmentData.DisableAlarm)
  401. {
  402. DebugMessageShow($"获取检测结果原始数据结束", equipmentData.IpAddress, equipmentData.SerialNo);
  403. return;
  404. }
  405. await Task.Run(() =>
  406. {
  407. if (equipmentData.DetectionData != null && equipmentData.DetectionData.RawResultData != null)
  408. {
  409. DebugMessageShow($"数据接收:{e.DetectionRawData.PacketNumber}/{e.DetectionRawData.TotalPackets}", equipmentData.IpAddress, equipmentData.SerialNo);
  410. if (e.DetectionRawData.PacketNumber == 1)
  411. {
  412. equipmentData.DetectionData.RawDataReceiving = true;
  413. equipmentData.DetectionData.RawData = new MemoryStream();
  414. equipmentData.DetectionData.RawData.Write(e.DetectionRawData.Data, 0, e.DetectionRawData.Data.Length);
  415. }
  416. else if (e.DetectionRawData.PacketNumber <= e.DetectionRawData.TotalPackets)
  417. {
  418. // 添加原始数据到检测数据中
  419. equipmentData.DetectionData.RawData.Write(e.DetectionRawData.Data, 0, e.DetectionRawData.Data.Length);
  420. // 如果是最后一包数据,处理检测数据
  421. if (e.DetectionRawData.PacketNumber == e.DetectionRawData.TotalPackets)
  422. {
  423. // 生成数据文件路径
  424. (string absolutePath, string relativePath) = DatFileHandler.GetDatFilePath(equipmentData.SerialNo);
  425. // 处理检测数据逻辑
  426. var record = new RecordDto
  427. {
  428. RopeName = equipmentData.RopeName,
  429. RopeNumber = equipmentData.RopeNumber,
  430. StartPoint = equipmentData.DetectionData.StartPoint,
  431. EndPoint = equipmentData.DetectionData.EndPoint,
  432. DetectedSpeed = equipmentData.DetectionData.DetectedSpeed,
  433. DetectionLength = equipmentData.DetectionData.DetectionLength,
  434. StartTime = equipmentData.DetectionData.StartTime.TimestampToDateTime(),
  435. EndTime = equipmentData.DetectionData.EndTime.TimestampToDateTime(),
  436. SensorCount = equipmentData.DetectionData.RawResultData.SensorCount,
  437. SamplingStep = equipmentData.DetectionData.RawResultData.SamplingStep,
  438. DataFilePath = relativePath,
  439. InUseSensors = string.Join(",", equipmentData.InUseSensor)
  440. };
  441. foreach (var damage in equipmentData.DetectionData.Damages)
  442. {
  443. var alarmCount = _alarmRepository.AddAlarm(new AlarmDataModel
  444. {
  445. DamageLevel = damage.DamageLevel,
  446. DamagePosition = damage.DamagePoint,
  447. DamageValue = damage.DamageValue,
  448. RopeNumber = equipmentData.RopeNumber
  449. }, AlarmSourceType.Detection, App.Config.DamageExtent);
  450. if (alarmCount >= App.Config.AlarmValidCount)
  451. {
  452. record.Damages.Add(new DamageDto
  453. {
  454. DamageLevel = damage.DamageLevel,
  455. DamagePoint = damage.DamagePoint,
  456. DamageValue = damage.DamageValue,
  457. });
  458. record.DamageCount++;
  459. //纠正健康度 以客户端上传的损伤数据 重新计算
  460. if ((int)record.RiskLevel < (int)damage.DamageLevel)
  461. {
  462. record.RiskLevel = (RiskLevel)damage.DamageLevel;
  463. }
  464. }
  465. }
  466. equipmentData.RiskLevel = record.RiskLevel;
  467. if (record.DamageCount > 0)
  468. {
  469. int? recordId = _recordRepository.CreateRecord(record);
  470. if (recordId.HasValue)
  471. {
  472. record.Id = recordId.Value;
  473. AddRecordToPageRecords(record);
  474. if (!DatFileHandler.CreateDatFile(absolutePath, equipmentData.DetectionData.RawData))
  475. {
  476. LogHelper.Error($"创建检测数据文件失败,路径:{absolutePath}");
  477. }
  478. DebugMessageShow($"检测数据记录成功", equipmentData.IpAddress, equipmentData.SerialNo);
  479. if ((int)record.RiskLevel >= (int)App.Config.SoundRiskLevel)
  480. {
  481. Application.Current.Dispatcher.Invoke(() =>
  482. {
  483. speech.SpeakAsync($"{equipmentData.RopeName},检测到{record.DamageCount}处损伤");
  484. });
  485. }
  486. }
  487. else
  488. {
  489. LogHelper.Error("检测数据记录失败");
  490. }
  491. }
  492. else
  493. {
  494. DebugMessageShow($"检测完成,未发现损伤,本次检测不做记录。", equipmentData.IpAddress, equipmentData.SerialNo);
  495. }
  496. equipmentData.DetectionData.RawDataReceiving = false;
  497. }
  498. }
  499. }
  500. });
  501. }
  502. }
  503. /// <summary>
  504. /// 接收报警数据
  505. /// </summary>
  506. private void TcpServer_AlarmDataReceived(object sender, AlarmDataReceivedEventArgs e)
  507. {
  508. var equipmentData = App.DataCenter.Equipments.FirstOrDefault(c => c.IpAddress == e.IpAddress);
  509. if (equipmentData != null && equipmentData.IsSpeedStable && !equipmentData.DisableAlarm)
  510. {
  511. Dispatcher.InvokeAsync(() =>
  512. {
  513. e.AlarmData.RopeNumber = equipmentData.RopeNumber;
  514. var alarmCount = _alarmRepository.AddAlarm(e.AlarmData, AlarmSourceType.RealTime, App.Config.DamageExtent);
  515. if (alarmCount >= App.Config.AlarmValidCount)
  516. {
  517. equipmentData.AddAlarm(e.AlarmData);
  518. }
  519. });
  520. }
  521. }
  522. private void TcpServer_UpgradedRequestResultReceived(object sender, UpgradedResultReceivedEventArgs e)
  523. {
  524. Dispatcher.InvokeAsync(async () =>
  525. {
  526. if (e.Code == 0)
  527. {
  528. await Task.Delay(2000);
  529. string url = $"http://192.168.1.200"; // 替换为您的网页地址
  530. Tools.OpenUrl(url);
  531. }
  532. });
  533. }
  534. public void AddRecordToPageRecords(RecordDto record)
  535. {
  536. Application.Current.Dispatcher.Invoke(() =>
  537. {
  538. if (Main_Frame.Content is Page currentPage && currentPage != null)
  539. {
  540. var simpleRecord = record.ToSimpleRecordDto();
  541. if (currentPage.Title == "RealTimePage")
  542. {
  543. if (currentPage.DataContext is RealTimeViewModel realTimeView)
  544. {
  545. realTimeView.AddRecord(simpleRecord);
  546. }
  547. }
  548. }
  549. });
  550. }
  551. private void WindowX_Loaded(object sender, RoutedEventArgs e)
  552. {
  553. AdjustViewboxStretch();
  554. NavigateToPage("Home");
  555. // 在程序启动时开启一个后台线程,每隔15秒检测一次
  556. Task.Run(async () =>
  557. {
  558. bool lastIpOk = true;
  559. bool lastPortOk = true;
  560. while (true)
  561. {
  562. bool ipOk = Tools.CheckIpAddressExists(App.Config.IpAddress);
  563. bool portOk = !Tools.CheckPortInUse(App.Config.Port);
  564. // IP异常
  565. if (!ipOk)
  566. {
  567. NoticeBox.Show($"当前在用网卡的IP地址中没有发现[{App.Config.IpAddress}],请检查网络配置。",
  568. "警告", MessageBoxIcon.Warning, true, 5000);
  569. }
  570. // IP从异常恢复正常
  571. else if (!lastIpOk && ipOk)
  572. {
  573. if (!HasConnectedDevice())
  574. {
  575. NoticeBox.Show($"IP地址[{App.Config.IpAddress}]已恢复,5秒后将自动重启程序", "提示", MessageBoxIcon.Info, true, 5000);
  576. if (HasConnectedDevice())
  577. {
  578. NoticeBox.Show($"检测到有设备处于连接状态,已取消自动重启", "提示", MessageBoxIcon.Info, true, 5000);
  579. }
  580. else
  581. {
  582. await RestartApplication();
  583. }
  584. }
  585. }
  586. // 端口异常
  587. if (!portOk)
  588. {
  589. NoticeBox.Show("当前配置的端口已被占用,请更换端口或关闭占用该端口的程序。",
  590. "警告", MessageBoxIcon.Warning, true, 5000);
  591. }
  592. // 端口从异常恢复正常
  593. else if (!lastPortOk && portOk)
  594. {
  595. if (!HasConnectedDevice())
  596. {
  597. NoticeBox.Show($"端口[{App.Config.Port}]已释放,5秒后将自动重启程序", "提示", MessageBoxIcon.Info, true, 5000);
  598. if (HasConnectedDevice())
  599. {
  600. NoticeBox.Show($"检测到有设备处于连接状态,已取消自动重启", "提示", MessageBoxIcon.Info, true, 5000);
  601. }
  602. else
  603. {
  604. await RestartApplication();
  605. }
  606. }
  607. }
  608. lastIpOk = ipOk;
  609. lastPortOk = portOk;
  610. await Task.Delay(15000); // 每15秒检测一次
  611. }
  612. });
  613. }
  614. private async Task RestartApplication(int delay = 5000)
  615. {
  616. await Task.Delay(delay);
  617. Application.Current.Dispatcher.Invoke(() =>
  618. {
  619. App.RestartApplication();
  620. });
  621. }
  622. /// <summary>
  623. /// 检查是否有设备处于连接状态
  624. /// </summary>
  625. private bool HasConnectedDevice()
  626. {
  627. return App.DataCenter.Equipments.Any(e => e.IsConnect);
  628. }
  629. public void NavigatePage(Uri uri)
  630. {
  631. Main_Frame.NavigationService.Navigate(uri);
  632. }
  633. private void NavigateToPage(object pageName)
  634. {
  635. switch (pageName)
  636. {
  637. case "Home":
  638. MainView.CurrentPage = "Home";
  639. Main_Frame.NavigationService.Navigate(new Uri($"Pages/RealTime/RealTimePage.xaml", uriKind: UriKind.Relative));
  640. break;
  641. case "Record":
  642. MainView.CurrentPage = "Record";
  643. Main_Frame.NavigationService.Navigate(new Uri($"Pages/RecordPage.xaml", uriKind: UriKind.Relative));
  644. break;
  645. }
  646. }
  647. private void Menu_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  648. {
  649. if (sender is TextBlock menuItem)
  650. {
  651. CleanNavigation(Main_Frame);
  652. NavigateToPage(menuItem?.Tag);
  653. }
  654. }
  655. private void CleanNavigation(Frame frame)
  656. {
  657. while (frame.CanGoBack)
  658. frame.RemoveBackEntry();
  659. }
  660. private void StackPanel_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  661. {
  662. if (e.ClickCount == 2)
  663. {
  664. Left = 0;
  665. Top = 0;
  666. }
  667. }
  668. private void Setting_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  669. {
  670. SettingDialog settingDialog = new SettingDialog();
  671. if (settingDialog.ShowDialog(true) == true)
  672. {
  673. if (settingDialog.IsAutoStart)
  674. {
  675. App.RestartApplication();
  676. }
  677. }
  678. }
  679. private void Window_Closing(object sender, CancelEventArgs e)
  680. {
  681. App.TcpServer?.Dispose();
  682. speech?.Dispose();
  683. }
  684. private void Minimize_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  685. {
  686. WindowState = WindowState.Minimized;
  687. }
  688. private void Close_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  689. {
  690. var result = MessageBoxX.Show(this, "退出后将无法进行实时检测,是否确认退出程序?", "警告",
  691. MessageBoxButton.YesNo,
  692. MessageBoxIcon.Warning, DefaultButton.YesOK);
  693. if (result == MessageBoxResult.Yes)
  694. {
  695. Close();
  696. }
  697. }
  698. private void SwitchToInstance_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  699. {
  700. if (sender is Border instanceBorder && instanceBorder.Tag != null)
  701. {
  702. App.SwitchToExistingInstance(instanceBorder.Tag.ToString());
  703. }
  704. }
  705. private void AdjustViewboxStretch()
  706. {
  707. var screen = System.Windows.Forms.Screen.FromHandle(
  708. new System.Windows.Interop.WindowInteropHelper(this).Handle);
  709. double aspectRatio = (double)screen.Bounds.Width / screen.Bounds.Height;
  710. RootGrid.Height = aspectRatio <= ASPECT_RATIO_THRESHOLD ? 1440 : 1080;
  711. }
  712. }
  713. }