ShowVisionRender.xaml.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ImageFile;
  3. using Prism.Events;
  4. using Prism.Ioc;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Controls;
  12. using System.Windows.Forms.Integration;
  13. using TeamAAS_VP.Core;
  14. using TeamAAS_VP.Enums;
  15. using TeamAAS_VP.Events;
  16. using TeamAAS_VP.Interfaces;
  17. using TeamAAS_VP.Models;
  18. using TeamAAS_VP.Resources.Languages;
  19. using TeamAAS_VP.ViewModels.Home;
  20. namespace TeamAAS_VP.Views.Home
  21. {
  22. /// <summary>
  23. /// Interaction logic for ShowVisionRender
  24. /// </summary>
  25. public partial class ShowVisionRender : UserControl
  26. {
  27. private ShowVisionRenderViewModel viewModel;
  28. // key=ShowRender.Id
  29. private readonly Dictionary<Guid, WindowsFormsHost> vmRenders;
  30. private readonly Dictionary<Guid, TextBlock> Titles;
  31. private readonly IEventAggregator _eventAggregator;
  32. private readonly ISystemDatabaseService _systemDatabaseService;
  33. private readonly IProductService _productService;
  34. public ShowVisionRender()
  35. {
  36. InitializeComponent();
  37. vmRenders = new Dictionary<Guid, WindowsFormsHost>();
  38. Titles = new Dictionary<Guid, TextBlock>();
  39. viewModel = DataContext as ShowVisionRenderViewModel;
  40. _eventAggregator = viewModel._eventAggregator;
  41. _systemDatabaseService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<ISystemDatabaseService>();
  42. _productService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<IProductService>();
  43. viewModel.UpdateLayout += ViewModel_UpdateLayout;
  44. _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(UpdateRenderModuleSource);
  45. _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
  46. }
  47. /// <summary>
  48. /// 更新某个工位/模块的显示内容(图像/图形/Record/保存)
  49. /// </summary>
  50. private void UpdateRenderModuleSource(ShowRender render)
  51. {
  52. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  53. {
  54. foreach (var item in vmRenders)
  55. {
  56. if (item.Value?.Child is CogRecordDisplay disp)
  57. {
  58. // 通过 Tag(产品名) 匹配当前需要更新的窗口
  59. if (disp.Tag != null && disp.Tag.ToString() == render.ProceductName)
  60. {
  61. disp.Record = null;
  62. disp.Image = render.Image;
  63. disp.StaticGraphics.Clear();
  64. if (render.Graphic != null)
  65. disp.StaticGraphics.AddList(render.Graphic, "");
  66. if (render.Record != null)
  67. disp.Record = render.Record;
  68. if (render.IsSaveImage)
  69. {
  70. // 注意:CreateContentBitmap 可能比较耗时,但你这里已经在 UI 线程里调用了;
  71. // 如果卡顿明显,建议把 bitmap 生成放到后台线程(需谨慎处理线程访问)
  72. App.Current.Dispatcher.BeginInvoke(new Action(() =>
  73. {
  74. var bmp = (Bitmap)disp.CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  75. SaveImage(
  76. render.SaveImageModel,
  77. render.SaveImagePathModel,
  78. render.SavePath,
  79. render.Image,
  80. bmp,
  81. render.Result,
  82. render.IsCompress
  83. );
  84. }));
  85. }
  86. break;
  87. }
  88. }
  89. }
  90. }));
  91. }
  92. /// <summary>
  93. /// 【核心】根据 obj.Count 自动生成 1~16 个显示格子(标题+CogRecordDisplay)
  94. /// </summary>
  95. private async void ViewModel_UpdateLayout(System.Collections.ObjectModel.ObservableCollection<Models.ShowRender> obj)
  96. {
  97. System.Windows.Media.FontFamily font = Application.Current.Resources["DefaultFont"] as System.Windows.Media.FontFamily;
  98. // 1) 清理旧控件
  99. if (vmRenders.Count > 0)
  100. {
  101. foreach (var render in vmRenders)
  102. {
  103. // WindowsFormsHost.Dispose() 会销毁 WinForms 句柄,防止资源泄漏
  104. render.Value?.Dispose();
  105. }
  106. }
  107. vmRenders.Clear();
  108. Titles.Clear();
  109. gridRender.Children.Clear();
  110. gridRender.RowDefinitions.Clear();
  111. gridRender.ColumnDefinitions.Clear();
  112. // 2) 判空
  113. if (obj == null || obj.Count == 0) return;
  114. // 3) 限制最大 16(防止越界)
  115. int count = Math.Min(obj.Count, 16);
  116. // 4) 计算行列(1~16自动铺满:尽量接近正方形;最大 4*4)
  117. // 1 -> 1*1
  118. // 2 -> 1*2
  119. // 3 -> 2*2
  120. // 4 -> 2*2
  121. // 5~6 -> 2*3
  122. // 7~9 -> 3*3(9满)
  123. // 10~12 -> 3*4(12满)
  124. // 13~16 -> 4*4(16满)
  125. GetGridSize(count, out int rows, out int cols);
  126. // 5) 创建主Grid的行列
  127. for (int r = 0; r < rows; r++)
  128. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  129. for (int c = 0; c < cols; c++)
  130. gridRender.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
  131. gridRender.ShowGridLines = true;
  132. // 6) 逐个创建子格子(每个子格子两行:标题/画面)
  133. for (int i = 0; i < count; i++)
  134. {
  135. var sr = obj[i];
  136. // (1) 创建显示控件(WindowsFormsHost + CogRecordDisplay)
  137. var host = new WindowsFormsHost()
  138. {
  139. Tag = sr.ProceductName,
  140. Child = new CogRecordDisplay()
  141. {
  142. Tag = sr.ProceductName,
  143. }
  144. };
  145. vmRenders.Add(sr.Id, host);
  146. // (2) 创建标题
  147. var title = new TextBlock()
  148. {
  149. Text = sr.ProceductName,
  150. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  151. FontWeight = FontWeights.Bold,
  152. FontFamily = font,
  153. FontSize = 12,
  154. Foreground = System.Windows.Media.Brushes.Black
  155. };
  156. Titles.Add(sr.Id, title);
  157. // (3) 子Grid(标题 + 显示)
  158. var cell = new Grid();
  159. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); // 标题
  160. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); // 图像
  161. cell.Children.Add(title);
  162. cell.Children.Add(host);
  163. Grid.SetRow(title, 0);
  164. Grid.SetColumn(title, 0);
  165. Grid.SetRow(host, 1);
  166. Grid.SetColumn(host, 0);
  167. // (4) 放到主 gridRender 中
  168. int row = i / cols;
  169. int col = i % cols;
  170. gridRender.Children.Add(cell);
  171. Grid.SetRow(cell, row);
  172. Grid.SetColumn(cell, col);
  173. }
  174. }
  175. /// <summary>
  176. /// 根据数量返回最合适的 rows/cols(最大 4*4)
  177. /// </summary>
  178. private void GetGridSize(int count, out int rows, out int cols)
  179. {
  180. // 默认值
  181. rows = 1;
  182. cols = 1;
  183. if (count <= 1) { rows = 1; cols = 1; return; }
  184. if (count <= 2) { rows = 1; cols = 2; return; }
  185. if (count <= 4) { rows = 2; cols = 2; return; }
  186. if (count <= 6) { rows = 2; cols = 3; return; }
  187. if (count <= 9) { rows = 3; cols = 3; return; }
  188. if (count <= 12) { rows = 3; cols = 4; return; }
  189. // 13~16
  190. rows = 4;
  191. cols = 4;
  192. }
  193. /// <summary>
  194. /// 统一配置 VisionPro 显示属性
  195. /// </summary>
  196. private void ConfigureCogDisplay(CogRecordDisplay disp)
  197. {
  198. disp.HorizontalScrollBar = false;
  199. disp.VerticalScrollBar = false;
  200. disp.AutoFit = true;
  201. disp.BackColor = System.Drawing.SystemColors.ActiveCaption;
  202. }
  203. /// <summary>
  204. /// 保存图像(保持你原有逻辑不变)
  205. /// </summary>
  206. private void SaveImage(ProcedureSaveImageModel saveImageModel,
  207. ProcedureSaveImagePathModel saveImagePathModel,
  208. string path,
  209. ICogImage image,
  210. Bitmap reimage,
  211. bool result,
  212. bool isCompress)
  213. {
  214. if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
  215. {
  216. _eventAggregator.GetEvent<TaskMessageNotification>()
  217. .Publish(new Models.MessageStruct() { Message = "保存图像路径为无效的路径!", level = MessageLevel.Alarm });
  218. return;
  219. }
  220. Task.Run(() =>
  221. {
  222. try
  223. {
  224. DateTime now = DateTime.Now;
  225. if (saveImageModel == ProcedureSaveImageModel.Original)
  226. {
  227. string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  228. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  229. {
  230. Originalpath = result
  231. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  232. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  233. }
  234. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  235. {
  236. if (result)
  237. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  238. else
  239. return;
  240. }
  241. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  242. {
  243. if (!result)
  244. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  245. else
  246. return;
  247. }
  248. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  249. {
  250. // 当前产品配方名(过滤非法字符)
  251. string formulaName = _productService.GetCurrentProduct().Name;
  252. foreach (char c in Path.GetInvalidFileNameChars())
  253. formulaName = formulaName.Replace(c, '_');
  254. // 产品SN(过滤非法字符)
  255. string productSN = _productService.CurrentProductCode;
  256. foreach (char c in Path.GetInvalidFileNameChars())
  257. productSN = productSN.Replace(c, '_');
  258. string resultStr = result ? "OK" : "NG";
  259. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  260. }
  261. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  262. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  263. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  264. {
  265. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  266. _cogImageFileTool.Append(image);
  267. _cogImageFileTool.Close();
  268. }
  269. }
  270. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  271. {
  272. string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  273. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  274. {
  275. Recordedpath = result
  276. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  277. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  278. }
  279. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  280. {
  281. if (result)
  282. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  283. else
  284. return;
  285. }
  286. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  287. {
  288. if (!result)
  289. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  290. else
  291. return;
  292. }
  293. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  294. {
  295. string formulaName = _productService.GetCurrentProduct().Name;
  296. foreach (char c in Path.GetInvalidFileNameChars())
  297. formulaName = formulaName.Replace(c, '_');
  298. string productSN = _productService.CurrentProductCode;
  299. foreach (char c in Path.GetInvalidFileNameChars())
  300. productSN = productSN.Replace(c, '_');
  301. string resultStr = result ? "OK" : "NG";
  302. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  303. }
  304. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  305. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  306. if (isCompress)
  307. {
  308. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  309. }
  310. else
  311. {
  312. reimage.Save(Recordedpath);
  313. reimage.Dispose();
  314. }
  315. }
  316. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  317. {
  318. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  319. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  320. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  321. {
  322. if (result)
  323. {
  324. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  325. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  326. }
  327. else
  328. {
  329. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  330. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  331. }
  332. }
  333. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  334. {
  335. if (result)
  336. {
  337. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  338. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  339. }
  340. else
  341. {
  342. return;
  343. }
  344. }
  345. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  346. {
  347. if (!result)
  348. {
  349. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  350. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  351. }
  352. else
  353. {
  354. return;
  355. }
  356. }
  357. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  358. {
  359. string formulaName = _productService.GetCurrentProduct().Name;
  360. foreach (char c in Path.GetInvalidFileNameChars())
  361. formulaName = formulaName.Replace(c, '_');
  362. string productSN = _productService.CurrentProductCode;
  363. foreach (char c in Path.GetInvalidFileNameChars())
  364. productSN = productSN.Replace(c, '_');
  365. string resultStr = result ? "OK" : "NG";
  366. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  367. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  368. }
  369. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  370. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  371. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  372. {
  373. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  374. _cogImageFileTool.Append(image);
  375. _cogImageFileTool.Close();
  376. }
  377. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  378. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  379. if (isCompress)
  380. {
  381. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  382. }
  383. else
  384. {
  385. reimage.Save(Recordedpath);
  386. reimage.Dispose();
  387. }
  388. }
  389. }
  390. catch (Exception ex)
  391. {
  392. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  393. }
  394. });
  395. }
  396. /// <summary>
  397. /// 切换产品时清空主页显示(保持你原有逻辑)
  398. /// </summary>
  399. private void ProductChanged(ProductModel product)
  400. {
  401. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  402. {
  403. foreach (var item in vmRenders)
  404. {
  405. try
  406. {
  407. if (item.Value?.Child is CogRecordDisplay disp)
  408. {
  409. if (disp.Tag != null)
  410. {
  411. disp.Image = null;
  412. disp.StaticGraphics.Clear();
  413. // 你原来 break 只清一次;这里保留你的行为
  414. break;
  415. }
  416. }
  417. }
  418. catch (Exception ex)
  419. {
  420. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  421. }
  422. }
  423. }));
  424. }
  425. }
  426. }