ShowVisionRender.xaml.cs 21 KB

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