ShowVisionRender.xaml.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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) 配置 VisionPro 显示属性
  158. //ConfigureCogDisplay((CogRecordDisplay)host.Child);
  159. // (3) 子Grid(标题 + 显示)
  160. var cell = new Grid();
  161. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); // 标题
  162. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); // 图像
  163. cell.Children.Add(title);
  164. cell.Children.Add(host);
  165. Grid.SetRow(title, 0);
  166. Grid.SetColumn(title, 0);
  167. Grid.SetRow(host, 1);
  168. Grid.SetColumn(host, 0);
  169. // (4) 放到主 gridRender 中
  170. int row = i / cols;
  171. int col = i % cols;
  172. gridRender.Children.Add(cell);
  173. Grid.SetRow(cell, row);
  174. Grid.SetColumn(cell, col);
  175. }
  176. }
  177. /// <summary>
  178. /// 根据数量返回最合适的 rows/cols(最大 4*4)
  179. /// </summary>
  180. private void GetGridSize(int count, out int rows, out int cols)
  181. {
  182. // 默认值
  183. rows = 1;
  184. cols = 1;
  185. if (count <= 1) { rows = 1; cols = 1; return; }
  186. if (count <= 2) { rows = 1; cols = 2; return; }
  187. if (count <= 4) { rows = 2; cols = 2; return; }
  188. if (count <= 6) { rows = 2; cols = 3; return; }
  189. if (count <= 9) { rows = 3; cols = 3; return; }
  190. if (count <= 12) { rows = 3; cols = 4; return; }
  191. // 13~16
  192. rows = 4;
  193. cols = 4;
  194. }
  195. /// <summary>
  196. /// 统一配置 VisionPro 显示属性
  197. /// </summary>
  198. private void ConfigureCogDisplay(CogRecordDisplay disp)
  199. {
  200. disp.HorizontalScrollBar = false;
  201. disp.VerticalScrollBar = false;
  202. disp.AutoFit = true;
  203. disp.BackColor = System.Drawing.SystemColors.ActiveCaption;
  204. }
  205. /// <summary>
  206. /// 保存图像(保持你原有逻辑不变)
  207. /// </summary>
  208. private void SaveImage(ProcedureSaveImageModel saveImageModel,
  209. ProcedureSaveImagePathModel saveImagePathModel,
  210. string path,
  211. ICogImage image,
  212. Bitmap reimage,
  213. bool result,
  214. bool isCompress)
  215. {
  216. if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
  217. {
  218. _eventAggregator.GetEvent<TaskMessageNotification>()
  219. .Publish(new Models.MessageStruct() { Message = "保存图像路径为无效的路径!", level = MessageLevel.Alarm });
  220. return;
  221. }
  222. Task.Run(() =>
  223. {
  224. try
  225. {
  226. DateTime now = DateTime.Now;
  227. if (saveImageModel == ProcedureSaveImageModel.Original)
  228. {
  229. string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  230. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  231. {
  232. Originalpath = result
  233. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  234. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  235. }
  236. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  237. {
  238. if (result)
  239. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  240. else
  241. return;
  242. }
  243. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  244. {
  245. if (!result)
  246. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  247. else
  248. return;
  249. }
  250. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  251. {
  252. // 当前产品配方名(过滤非法字符)
  253. string formulaName = _productService.GetCurrentProduct().Name;
  254. foreach (char c in Path.GetInvalidFileNameChars())
  255. formulaName = formulaName.Replace(c, '_');
  256. // 产品SN(过滤非法字符)
  257. string productSN = _productService.CurrentProductCode;
  258. foreach (char c in Path.GetInvalidFileNameChars())
  259. productSN = productSN.Replace(c, '_');
  260. string resultStr = result ? "OK" : "NG";
  261. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  262. }
  263. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  264. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  265. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  266. {
  267. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  268. _cogImageFileTool.Append(image);
  269. _cogImageFileTool.Close();
  270. }
  271. }
  272. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  273. {
  274. string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  275. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  276. {
  277. Recordedpath = result
  278. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  279. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  280. }
  281. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  282. {
  283. if (result)
  284. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  285. else
  286. return;
  287. }
  288. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  289. {
  290. if (!result)
  291. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  292. else
  293. return;
  294. }
  295. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  296. {
  297. string formulaName = _productService.GetCurrentProduct().Name;
  298. foreach (char c in Path.GetInvalidFileNameChars())
  299. formulaName = formulaName.Replace(c, '_');
  300. string productSN = _productService.CurrentProductCode;
  301. foreach (char c in Path.GetInvalidFileNameChars())
  302. productSN = productSN.Replace(c, '_');
  303. string resultStr = result ? "OK" : "NG";
  304. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  305. }
  306. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  307. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  308. if (isCompress)
  309. {
  310. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  311. }
  312. else
  313. {
  314. reimage.Save(Recordedpath);
  315. reimage.Dispose();
  316. }
  317. }
  318. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  319. {
  320. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  321. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  322. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  323. {
  324. if (result)
  325. {
  326. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  327. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  328. }
  329. else
  330. {
  331. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  332. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  333. }
  334. }
  335. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  336. {
  337. if (result)
  338. {
  339. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  340. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  341. }
  342. else
  343. {
  344. return;
  345. }
  346. }
  347. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  348. {
  349. if (!result)
  350. {
  351. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  352. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  353. }
  354. else
  355. {
  356. return;
  357. }
  358. }
  359. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  360. {
  361. string formulaName = _productService.GetCurrentProduct().Name;
  362. foreach (char c in Path.GetInvalidFileNameChars())
  363. formulaName = formulaName.Replace(c, '_');
  364. string productSN = _productService.CurrentProductCode;
  365. foreach (char c in Path.GetInvalidFileNameChars())
  366. productSN = productSN.Replace(c, '_');
  367. string resultStr = result ? "OK" : "NG";
  368. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  369. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  370. }
  371. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  372. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  373. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  374. {
  375. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  376. _cogImageFileTool.Append(image);
  377. _cogImageFileTool.Close();
  378. }
  379. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  380. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  381. if (isCompress)
  382. {
  383. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  384. }
  385. else
  386. {
  387. reimage.Save(Recordedpath);
  388. reimage.Dispose();
  389. }
  390. }
  391. }
  392. catch (Exception ex)
  393. {
  394. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  395. }
  396. });
  397. }
  398. /// <summary>
  399. /// 切换产品时清空主页显示(保持你原有逻辑)
  400. /// </summary>
  401. private void ProductChanged(ProductModel product)
  402. {
  403. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  404. {
  405. foreach (var item in vmRenders)
  406. {
  407. try
  408. {
  409. if (item.Value?.Child is CogRecordDisplay disp)
  410. {
  411. if (disp.Tag != null)
  412. {
  413. disp.Image = null;
  414. disp.StaticGraphics.Clear();
  415. // 你原来 break 只清一次;这里保留你的行为
  416. break;
  417. }
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  423. }
  424. }
  425. }));
  426. }
  427. }
  428. }