PickScrewAccuracyAnalyzerViewModel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. using MaterialDesignThemes.Wpf;
  2. using Newtonsoft.Json;
  3. using Prism.Commands;
  4. using Prism.Events;
  5. using Prism.Ioc;
  6. using Prism.Mvvm;
  7. using Prism.Regions;
  8. using Prism.Services.Dialogs;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Collections.ObjectModel;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Web.UI.WebControls;
  18. using System.Windows;
  19. using System.Windows.Threading;
  20. using TeamAAS_VP.Core;
  21. using TeamAAS_VP.Core.PLCs;
  22. using TeamAAS_VP.Events;
  23. using TeamAAS_VP.Interfaces;
  24. using TeamAAS_VP.Models;
  25. using TeamAAS_VP.Models.PLC;
  26. using TeamAAS_VP.Models.Torque;
  27. using TeamAAS_VP.Resources.Languages;
  28. using TeamAAS_VP.Services;
  29. using TeamAAS_VP.ViewModels.Product;
  30. using static TeamAAS_VP.ViewModels.Product.VisionDynamicAccuracyAnalyzerViewModel;
  31. namespace TeamAAS_VP.ViewModels.Home
  32. {
  33. public class PickScrewAccuracyAnalyzerViewModel : BindableBase, IDialogAware
  34. {
  35. IRegionManager _regionManager;
  36. IEventAggregator _eventAggregator;
  37. IContainerProvider _container;
  38. IDialogService _dialogService;
  39. IRobotService _robotService;
  40. ISystemDatabaseService _systemDatabaseService;
  41. IConfigService _configService;
  42. IPlcService _plcService;
  43. TorqueService _torqueService;
  44. //测试过程中控制取消的CTS
  45. CancellationTokenSource _cts;
  46. public PickScrewAccuracyAnalyzerViewModel(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container,
  47. IDialogService dialogService, IRobotService robotService, ISystemDatabaseService systemDatabaseService,
  48. IConfigService configService, TorqueService torqueService, IPlcService plcService)
  49. {
  50. _eventAggregator = ea;
  51. _configService = configService;
  52. _container = container;
  53. _robotService = robotService;
  54. _torqueService = torqueService;
  55. _plcService = plcService;
  56. management = _container.Resolve<Management>();
  57. MessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(2));
  58. }
  59. #region 属性
  60. private SnackbarMessageQueue _MessageQueue;
  61. public SnackbarMessageQueue MessageQueue
  62. {
  63. get { return _MessageQueue; }
  64. set { SetProperty(ref _MessageQueue, value); }
  65. }
  66. private Management _management;
  67. public Management management
  68. {
  69. get { return _management; }
  70. set { SetProperty(ref _management, value); }
  71. }
  72. private int _MoveSpeed = 100;
  73. /// <summary>
  74. /// 移动速度
  75. /// </summary>
  76. public int MoveSpeed
  77. {
  78. get { return _MoveSpeed; }
  79. set { SetProperty(ref _MoveSpeed, value); }
  80. }
  81. private double _CycleTime;
  82. /// <summary>
  83. /// 单次的时长
  84. /// </summary>
  85. public double CycleTime
  86. {
  87. get { return _CycleTime; }
  88. set { SetProperty(ref _CycleTime, value); }
  89. }
  90. private int _RepeatCount = 10;
  91. /// <summary>
  92. /// 重复次数
  93. /// </summary>
  94. public int RepeatCount
  95. {
  96. get { return _RepeatCount; }
  97. set { SetProperty(ref _RepeatCount, value); }
  98. }
  99. private int _CurrentProgress;
  100. /// <summary>
  101. /// 当前进度
  102. /// </summary>
  103. public int CurrentProgress
  104. {
  105. get { return _CurrentProgress; }
  106. set { SetProperty(ref _CurrentProgress, value); }
  107. }
  108. private int _SuccessCount;
  109. /// <summary>
  110. /// 成功次数
  111. /// </summary>
  112. public int SuccessCount
  113. {
  114. get { return _SuccessCount; }
  115. set { SetProperty(ref _SuccessCount, value); }
  116. }
  117. private int _FailCount;
  118. /// <summary>
  119. /// 失败次数
  120. /// </summary>
  121. public int FailCount
  122. {
  123. get { return _FailCount; }
  124. set { SetProperty(ref _FailCount, value); }
  125. }
  126. private double _SuccessRate;
  127. /// <summary>
  128. /// 成功率
  129. /// </summary>
  130. public double SuccessRate
  131. {
  132. get { return _SuccessRate; }
  133. set { SetProperty(ref _SuccessRate, value); }
  134. }
  135. private string _Message = "等待开始...";
  136. public string Message
  137. {
  138. get { return _Message; }
  139. set { SetProperty(ref _Message, value); }
  140. }
  141. private bool _IsRunning;
  142. public bool IsRunning
  143. {
  144. get { return _IsRunning; }
  145. set { SetProperty(ref _IsRunning, value); }
  146. }
  147. private IRobot _Robot;
  148. public IRobot Robot
  149. {
  150. get { return _Robot; }
  151. set { SetProperty(ref _Robot, value); }
  152. }
  153. private ObservableCollection<PickDynamicTestResult> _TestResults;
  154. /// <summary>
  155. /// 测试结果列表
  156. /// </summary>
  157. public ObservableCollection<PickDynamicTestResult> TestResults
  158. {
  159. get { return _TestResults; }
  160. set { SetProperty(ref _TestResults, value); }
  161. }
  162. private RPoint _PointA = new RPoint();
  163. private TorqueProduceModel _Points;
  164. public TorqueProduceModel Points
  165. {
  166. get { return _Points; }
  167. set { SetProperty(ref _Points, value); }
  168. }
  169. #endregion
  170. #region 命令
  171. private DelegateCommand _StopTestCommand;
  172. public DelegateCommand StopTestCommand =>
  173. _StopTestCommand ?? (_StopTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
  174. //暂停测试命令
  175. private DelegateCommand _PauseTestCommand;
  176. public DelegateCommand PauseTestCommand =>
  177. _PauseTestCommand ?? (_PauseTestCommand = new DelegateCommand(() => { _cts?.Cancel(); }, () => IsRunning).ObservesProperty(() => IsRunning));
  178. private DelegateCommand _LoadedCommand;
  179. public DelegateCommand LoadedCommand =>
  180. _LoadedCommand ?? (_LoadedCommand = new DelegateCommand(ExecuteLoadedCommand));
  181. private DelegateCommand _StartTestCommand;
  182. public DelegateCommand StartTestCommand =>
  183. _StartTestCommand ?? (_StartTestCommand = new DelegateCommand(ExecuteStartTestCommand).ObservesProperty(() => IsRunning));
  184. private DelegateCommand _SingleTestCommand;
  185. public DelegateCommand SingleTestCommand =>
  186. _SingleTestCommand ?? (_SingleTestCommand = new DelegateCommand(ExecuteSingleTestCommand));
  187. private DelegateCommand _ExportCSVCommand;
  188. public DelegateCommand ExportCSVCommand =>
  189. _ExportCSVCommand ?? (_ExportCSVCommand = new DelegateCommand(ExecuteExportCSVCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  190. private DelegateCommand _ClearDataCommand;
  191. public DelegateCommand ClearDataCommand =>
  192. _ClearDataCommand ?? (_ClearDataCommand = new DelegateCommand(ExecuteClearDataCommand, () => !IsRunning).ObservesProperty(() => IsRunning));
  193. #endregion
  194. /// <summary>
  195. /// 保存配置
  196. /// </summary>
  197. private void SaveConfig()
  198. {
  199. try
  200. {
  201. var ConfigModel = new PickScrewAccuracyAnalyzerrConfigModel
  202. {
  203. RepeatCount = this.RepeatCount,
  204. MoveSpeed = this.MoveSpeed
  205. };
  206. FileHelper.WriteJsonFile(ConfigModel, FilePath.PickScrewAccuracyAnalyzerrConfigurationPath);
  207. }
  208. catch (Exception ex)
  209. {
  210. LogHelper.WriteLogError("保存视觉动态精度分析仪配置时出错", ex);
  211. }
  212. }
  213. private void ExecuteLoadedCommand()
  214. {
  215. try
  216. {
  217. var res = FileHelper.ReadJsonFile<PickScrewAccuracyAnalyzerrConfigModel>(FilePath.PickScrewAccuracyAnalyzerrConfigurationPath);
  218. this.RepeatCount = res.RepeatCount;
  219. this.MoveSpeed = res.MoveSpeed;
  220. }
  221. catch (Exception ex)
  222. {
  223. MessageBox.Show(ex.Message);
  224. }
  225. }
  226. private void ExecuteSingleTestCommand()
  227. {
  228. }
  229. private async void ExecuteStartTestCommand()
  230. {
  231. IsRunning = true;
  232. _cts = new CancellationTokenSource();
  233. CurrentProgress = 0;
  234. SuccessCount = 0;
  235. SuccessRate = 0;
  236. FailCount = 0;
  237. TestResults = new ObservableCollection<PickDynamicTestResult>();
  238. Message = "测试进行中...";
  239. try
  240. {
  241. PlcAddressConfig addressConfig = _configService.GetPlcAddresses();
  242. OpcUaClientPLC plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
  243. var result = System.Windows.MessageBox.Show("确定进行连续测试吗?", "提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);
  244. if (result != System.Windows.MessageBoxResult.Yes)
  245. {
  246. return;
  247. }
  248. if (Robot == null || !Robot.IsConnected)
  249. {
  250. SendTaskMessage("机器人未连接,无法示教!");
  251. return;
  252. }
  253. //为机器人设置移动速度
  254. await Robot.CalibParameAsync(new PickInfo(), MoveSpeed, 0, false, 0, 0);
  255. while (CurrentProgress < RepeatCount)
  256. {
  257. DateTime startTime = DateTime.Now;
  258. if (_cts.Token.IsCancellationRequested)
  259. {
  260. Message = "测试已取消!";
  261. break;
  262. }
  263. bool isSuccess1 = await _torqueService.Throw_Screw_Async(Robot, plc, addressConfig, Points, MoveSpeed);
  264. if (!isSuccess1)
  265. {
  266. SendTaskMessage("机器人移动到抛料点失败!");
  267. return;
  268. }
  269. if (_cts.Token.IsCancellationRequested)
  270. {
  271. Message = "测试已取消!";
  272. break;
  273. }
  274. bool isSuccess2 = await _torqueService.Pick_Screw_Async(Robot, plc, addressConfig, Points);
  275. if (isSuccess2)
  276. {
  277. SuccessCount++;
  278. CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
  279. TestResults.Add(new PickDynamicTestResult()
  280. {
  281. Index = CurrentProgress + 1,
  282. X_Position = Points.TorquePoints[1].X_Position,
  283. Y_Position = Points.TorquePoints[1].Y_Position,
  284. Z_Position = Points.TorquePoints[1].Z_Position_Start,
  285. Timestamp = DateTime.Now,
  286. CycleTime = this.CycleTime,
  287. IsPickSuccess = isSuccess2
  288. });
  289. }
  290. else
  291. {
  292. FailCount++;
  293. CycleTime = DateTime.Now.Subtract(startTime).TotalSeconds;
  294. TestResults.Add(new PickDynamicTestResult()
  295. {
  296. Index = CurrentProgress + 1,
  297. X_Position = Points.TorquePoints[1].X_Position,
  298. Y_Position = Points.TorquePoints[1].Y_Position,
  299. Z_Position = Points.TorquePoints[1].Z_Position_Start,
  300. Timestamp = DateTime.Now,
  301. CycleTime = this.CycleTime,
  302. IsPickSuccess = isSuccess2
  303. });
  304. }
  305. CurrentProgress++;
  306. SuccessRate = (double)SuccessCount / CurrentProgress * 100;
  307. SendTaskMessage($"测试进行中... {CurrentProgress}/{RepeatCount}");
  308. }
  309. if (CurrentProgress >= RepeatCount)
  310. {
  311. Message = "测试完成!";
  312. await _torqueService.Throw_Screw_Async(Robot, plc, addressConfig, Points, MoveSpeed);
  313. }
  314. }
  315. catch (Exception ex)
  316. {
  317. LogHelper.WriteLogError("取料重复测试时出错!", ex);
  318. }
  319. finally
  320. {
  321. IsRunning = false;
  322. }
  323. }
  324. public void SendTaskMessage(string msg)
  325. {
  326. App.Current.Dispatcher.Invoke(() =>
  327. {
  328. _eventAggregator.GetEvent<SnackbarMessageNotification>().Publish(new MessageParameter() { Msg =msg, Duration = 1 });
  329. });
  330. }
  331. private void ExecuteExportCSVCommand()
  332. {
  333. if (TestResults == null || TestResults.Count == 0)
  334. {
  335. SendTaskMessage("无测试数据,无法导出。");
  336. return;
  337. }
  338. try
  339. {
  340. var dlg = new Microsoft.Win32.SaveFileDialog
  341. {
  342. DefaultExt = "csv",
  343. Filter = "CSV 文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
  344. FileName = "TestResults.csv",
  345. Title = "保存测试结果为 CSV"
  346. };
  347. bool? dlgResult = dlg.ShowDialog();
  348. if (dlgResult != true)
  349. return;
  350. string path = dlg.FileName;
  351. if (File.Exists(path))
  352. {
  353. File.Delete(path);
  354. }
  355. using (StreamWriter sw = new StreamWriter(path, true))
  356. {
  357. //初始化文件,写入标题行
  358. sw.WriteLine("序号,状态,位置X,位置Y,位置Z,循环时间,时间戳");
  359. foreach (var item in TestResults)
  360. {
  361. sw.WriteLine($"{item.Index},{item.IsPickSuccess},{item.X_Position},{item.Y_Position},{item.Z_Position},{item.CycleTime},{item.Timestamp}");
  362. }
  363. }
  364. }
  365. catch (Exception ex)
  366. {
  367. MessageBox.Show("写入数据失败" + ex);
  368. }
  369. }
  370. private void ExecuteClearDataCommand()
  371. {
  372. TestResults.Clear();
  373. }
  374. #region 继承
  375. public string Title { get; set; } = "动态取料测试";
  376. public event Action<IDialogResult> RequestClose;
  377. public bool CanCloseDialog()
  378. {
  379. return true;
  380. }
  381. public void OnDialogClosed()
  382. {
  383. SaveConfig();
  384. }
  385. public void OnDialogOpened(IDialogParameters parameters)
  386. {
  387. if (parameters.ContainsKey("PickScrewPoint") && parameters.ContainsKey("Robot"))
  388. {
  389. Points = parameters.GetValue<TorqueProduceModel>("PickScrewPoint");
  390. Robot = parameters.GetValue<IRobot>("Robot");
  391. }
  392. }
  393. #endregion
  394. }
  395. }