MainWindow.xaml.cs 33 KB

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