ProductService.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ToolBlock;
  3. using Newtonsoft.Json;
  4. using NPOI.SS.Formula.Functions;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Windows.Documents;
  13. using System.Windows.Interop;
  14. using Team.FFFeederService.Interfaces;
  15. using TeamAAS_VP.Core;
  16. using TeamAAS_VP.Events;
  17. using TeamAAS_VP.Helpers;
  18. using TeamAAS_VP.Interfaces;
  19. using TeamAAS_VP.Models;
  20. using TeamAAS_VP.Models.Product;
  21. namespace TeamAAS_VP.Services
  22. {
  23. /// <summary>
  24. /// 产品管理服务。
  25. /// 负责在内存中维护产品集合、加载/保存产品到磁盘、产品的增删改查、相机/机器人相关变更的级联更新等操作。
  26. /// 线程安全:使用 `_sync` 对共享字典 `_products` 的访问进行保护。
  27. /// 产品文件存放遵循约定目录:`ProductsRootPath\{ProductName}\{ProductName}.cfg`,视觉流程文件为 `.vpp`。
  28. /// </summary>
  29. public class ProductService : IProductService
  30. {
  31. private readonly Dictionary<Guid, ProductModel> _products = new Dictionary<Guid, ProductModel>();
  32. private readonly object _sync = new object();
  33. private Guid _currentProduct = Guid.Empty;
  34. IConfigService _configService;
  35. IFeederService _feederService;
  36. private static readonly ConcurrentDictionary<string, CogToolBlock> _vppCache = new ConcurrentDictionary<string, CogToolBlock>();
  37. // 可配置的路径与文件名
  38. // 默认把产品放到公共应用数据目录下的 TeamAAS\Products
  39. /// <summary>
  40. /// 默认产品路径的相对子目录(相对于应用运行目录或配置指定的根)。
  41. /// </summary>
  42. public const string DefaultProductsSubPath = "..//Products";
  43. /// <summary>
  44. /// 模板 ToolBlock 的默认路径,用于在产品不存在视觉工具文件时进行初始化。
  45. /// </summary>
  46. public const string TemplateToolBlock = "..//Vision Template//TemplateToolBlock.vpp";
  47. /// <summary>
  48. /// 产品模板文件夹路径,用于存放产品模板。
  49. /// </summary>
  50. public const string ProductTemplatePath = "..//Product Template";
  51. /// <summary>
  52. /// 产品根目录(可配置)。默认值为 <see cref="DefaultProductsSubPath"/>.
  53. /// 每个产品在该目录下以其 Name 为子文件夹保存其配置与视觉文件。
  54. /// </summary>
  55. public string ProductsRootPath { get; set; }
  56. /// <summary>
  57. /// 当当前产品切换时触发的事件,参数为新的当前 <see cref="ProductModel"/> 实例。
  58. /// </summary>
  59. public event Action<ProductModel> OnProductChanged;
  60. /// <summary>
  61. /// 构造函数。
  62. /// </summary>
  63. /// <param name="configService">系统配置服务,用于读取/保存最近打开的产品等系统配置。</param>
  64. /// <param name="feederService">料斗服务,当前保存但未直接在本类中使用(保留用于扩展)。</param>
  65. public ProductService(IConfigService configService, IFeederService feederService)
  66. {
  67. _configService = configService;
  68. _feederService = feederService;
  69. ProductsRootPath = DefaultProductsSubPath;
  70. }
  71. public void Clear()
  72. {
  73. _currentProduct = Guid.Empty;
  74. _vppCache.Clear();
  75. }
  76. /// <summary>
  77. /// 初始化服务:清空内存产品并从磁盘枚举并加载产品清单(仅读取 JSON 配置,不加载所有视觉 ToolBlock)。
  78. /// </summary>
  79. /// <returns>初始化是否成功(始终返回 true,除非抛出未捕获异常)。</returns>
  80. public bool Initialize()
  81. {
  82. // 清空现有产品
  83. RemoveAllProducts();
  84. // 获取所有产品列表
  85. var productList = GetAllProductList();
  86. lock (_sync)
  87. {
  88. foreach (var (id, name, filePath) in productList)
  89. {
  90. var product = LoadProduct(filePath);
  91. if (product != null)
  92. {
  93. _products[id] = product;
  94. }
  95. }
  96. }
  97. return true;
  98. }
  99. /// <summary>
  100. /// 异步初始化服务。
  101. /// </summary>
  102. /// <returns>异步任务,完成时返回初始化结果。</returns>
  103. public Task<bool> InitializeAsync()
  104. {
  105. return Task.Run(() => Initialize());
  106. }
  107. /// <summary>
  108. /// 获取本地所有产品的元信息列表(ID、名称、配置文件路径)。
  109. /// </summary>
  110. /// <returns>返回一个元组集合,每项包含产品 ID、名称和对应的配置文件路径。</returns>
  111. public IEnumerable<(Guid id, string name, string filePath)> GetAllProductList()
  112. {
  113. var root = GetProductsRootFullPath();
  114. if (!Directory.Exists(root))
  115. {
  116. Directory.CreateDirectory(root);
  117. }
  118. string productListFilePath = Path.Combine(root, "ProductList.cfg");
  119. if (!File.Exists(productListFilePath))
  120. {
  121. return Enumerable.Empty<(Guid id, string name, string filePath)>();
  122. }
  123. Dictionary<Guid, string> list = FileHelper.ReadJsonFile<Dictionary<Guid, string>>(productListFilePath);
  124. var result = new List<(Guid id, string name, string filePath)>();
  125. foreach (var kvp in list)
  126. {
  127. var id = kvp.Key;
  128. var name = kvp.Value;
  129. var filePath = Path.Combine(root, name, name + ".cfg");
  130. result.Add((id, name, filePath));
  131. }
  132. return result;
  133. }
  134. /// <summary>
  135. /// 将当前内存中的产品清单保存到磁盘(ProductList.cfg)。
  136. /// </summary>
  137. public void SaveProductList()
  138. {
  139. var root = GetProductsRootFullPath();
  140. if (!Directory.Exists(root))
  141. {
  142. Directory.CreateDirectory(root);
  143. }
  144. string productListFilePath = Path.Combine(root, "ProductList.cfg");
  145. Dictionary<Guid, string> list = new Dictionary<Guid, string>();
  146. lock (_sync)
  147. {
  148. foreach (var kvp in _products)
  149. {
  150. list[kvp.Key] = kvp.Value.Name;
  151. }
  152. }
  153. FileHelper.WriteJsonFile(list, productListFilePath);
  154. }
  155. /// <summary>
  156. /// 异步保存产品清单到磁盘。
  157. /// </summary>
  158. /// <returns>表示异步操作的任务。</returns>
  159. public Task SaveProductListAsync()
  160. {
  161. return Task.Run(() => SaveProductList());
  162. }
  163. /// <summary>
  164. /// 在内存中创建并注册一个新产品,同时将其保存到磁盘。
  165. /// </summary>
  166. /// <param name="product">要创建的产品模型。若其 ID 为空则会分配新的 GUID。</param>
  167. /// <returns>若名称冲突则返回 false;否则返回 true 表示创建成功。</returns>
  168. /// <exception cref="ArgumentNullException">当 <paramref name="product"/> 为 null 时抛出。</exception>
  169. public bool CreateProduct(ProductModel product)
  170. {
  171. if (product == null) throw new ArgumentNullException(nameof(product));
  172. //如果当前存在同名产品,则创建失败
  173. lock (_sync)
  174. {
  175. if (_products.Values.Any(p => p.Name == product.Name))
  176. {
  177. return false;
  178. }
  179. }
  180. //对产品的编号进行自增
  181. lock (_sync)
  182. {
  183. if (_products.Count == 0)
  184. {
  185. product.NumberCode = 1;
  186. }
  187. else
  188. {
  189. product.NumberCode = _products.Values.Max(p => p.NumberCode) + 1;
  190. }
  191. }
  192. if (product.ID == Guid.Empty) product.ID = Guid.NewGuid();
  193. lock (_sync)
  194. {
  195. _products[product.ID] = product;
  196. }
  197. //保存产品清单
  198. SaveProductList();
  199. // 创建后自动保存到磁盘
  200. SaveProduct(product.ID);
  201. return true;
  202. }
  203. /// <summary>
  204. /// 异步创建产品。
  205. /// </summary>
  206. /// <param name="product">产品模型。</param>
  207. /// <returns>异步任务,结果为创建是否成功。</returns>
  208. public Task<bool> CreateProductAsync(ProductModel product)
  209. {
  210. return Task.Run(() => CreateProduct(product));
  211. }
  212. /// <summary>
  213. /// 根据 ID 获取内存中的产品模型(同步)。
  214. /// </summary>
  215. /// <param name="id">产品 ID。</param>
  216. /// <returns>对应的 <see cref="ProductModel"/>,若不存在则返回 null。</returns>
  217. public ProductModel GetProduct(Guid id)
  218. {
  219. lock (_sync)
  220. {
  221. _products.TryGetValue(id, out var p);
  222. return p;
  223. }
  224. }
  225. /// <summary>
  226. /// 异步获取指定 ID 的产品(仅包装同步方法)。
  227. /// </summary>
  228. /// <param name="id">产品 ID。</param>
  229. /// <returns>包含产品模型的任务。</returns>
  230. public Task<ProductModel> GetProductAsync(Guid id)
  231. {
  232. var p = GetProduct(id);
  233. return Task.FromResult(p);
  234. }
  235. /// <summary>
  236. /// 获取当前服务内存中所有产品的只读集合。
  237. /// </summary>
  238. /// <returns>只读的产品集合。</returns>
  239. public IReadOnlyCollection<ProductModel> GetAllProducts()
  240. {
  241. lock (_sync)
  242. {
  243. return _products.Values.ToList().AsReadOnly();
  244. }
  245. }
  246. /// <summary>
  247. /// 异步获取所有产品(包装同步实现)。
  248. /// </summary>
  249. /// <returns>包含只读产品集合的任务。</returns>
  250. public Task<IReadOnlyCollection<ProductModel>> GetAllProductsAsync()
  251. {
  252. var list = GetAllProducts();
  253. return Task.FromResult(list);
  254. }
  255. /// <summary>
  256. /// 尝试从内存中获取指定 ID 的产品。
  257. /// </summary>
  258. /// <param name="id">产品 ID。</param>
  259. /// <param name="product">输出参数,若找到则为对应产品,否则为 null。</param>
  260. /// <returns>若找到返回 true,否则返回 false。</returns>
  261. public bool TryGetProduct(Guid id, out ProductModel product)
  262. {
  263. lock (_sync)
  264. {
  265. return _products.TryGetValue(id, out product);
  266. }
  267. }
  268. /// <summary>
  269. /// 异步尝试获取产品。
  270. /// </summary>
  271. /// <param name="id">产品 ID。</param>
  272. /// <returns>任务,结果为 (found, product) 二元组。</returns>
  273. public Task<(bool found, ProductModel product)> TryGetProductAsync(Guid id)
  274. {
  275. ProductModel p;
  276. bool f;
  277. lock (_sync)
  278. {
  279. f = _products.TryGetValue(id, out p);
  280. }
  281. return Task.FromResult((f, p));
  282. }
  283. /// <summary>
  284. /// 判断内存中是否包含指定 ID 的产品。
  285. /// </summary>
  286. /// <param name="id">产品 ID。</param>
  287. /// <returns>存在返回 true,否则 false。</returns>
  288. public bool ContainsProduct(Guid id)
  289. {
  290. lock (_sync)
  291. {
  292. return _products.ContainsKey(id);
  293. }
  294. }
  295. /// <summary>
  296. /// 异步判断产品是否存在(包装同步实现)。
  297. /// </summary>
  298. /// <param name="id">产品 ID。</param>
  299. /// <returns>包含结果的任务。</returns>
  300. public Task<bool> ContainsProductAsync(Guid id)
  301. {
  302. var v = ContainsProduct(id);
  303. return Task.FromResult(v);
  304. }
  305. /// <summary>
  306. /// 判断服务中是否包含指定名称的产品(同步)。
  307. /// </summary>
  308. /// <param name="name">产品的名称</param>
  309. /// <returns>若包含则返回 true;否则返回 false。</returns>
  310. public bool ContainsProductByName(string name)
  311. {
  312. lock (_sync)
  313. {
  314. return _products.Values.Any(p => p.Name == name);
  315. }
  316. }
  317. /// <summary>
  318. /// 判断服务中是否包含指定名称的产品(异步)。
  319. /// </summary>
  320. /// <param name="name">产品的名称</param>
  321. /// <returns>若包含则返回 true;否则返回 false。</returns>
  322. public Task<bool> ContainsProductByNameAsync(string name)
  323. {
  324. return Task.FromResult(ContainsProductByName(name));
  325. }
  326. /// <summary>
  327. /// 从内存中移除产品(不删除磁盘文件),并保存产品清单。
  328. /// </summary>
  329. /// <param name="id">要移除的产品 ID。</param>
  330. /// <returns>若内存中存在并移除成功返回 true,否则 false。</returns>
  331. public bool RemoveProduct(Guid id)
  332. {
  333. bool result;
  334. lock (_sync)
  335. {
  336. result = _products.Remove(id);
  337. }
  338. // 删除后可选择删除对应的文件(视需求而定)
  339. SaveProductList();
  340. return result;
  341. }
  342. /// <summary>
  343. /// 异步移除产品(包装同步实现)。
  344. /// </summary>
  345. /// <param name="id">产品 ID。</param>
  346. /// <returns>任务,结果为移除是否成功。</returns>
  347. public Task<bool> RemoveProductAsync(Guid id)
  348. {
  349. var r = RemoveProduct(id);
  350. return Task.FromResult(r);
  351. }
  352. /// <summary>
  353. /// 清空内存中所有产品(不删除磁盘数据)。
  354. /// </summary>
  355. public void RemoveAllProducts()
  356. {
  357. lock (_sync)
  358. {
  359. _products.Clear();
  360. }
  361. }
  362. // 仍保留按路径保存的版本(向后兼容)
  363. /// <summary>
  364. /// 按指定路径保存产品。
  365. /// </summary>
  366. /// <param name="id">产品 ID。</param>
  367. /// <param name="filePath">保存路径(包含文件名)。</param>
  368. public void SaveProduct(Guid id, string filePath)
  369. {
  370. var p = GetProduct(id);
  371. if (p == null) return;
  372. SaveProduct(p, filePath);
  373. }
  374. /// <summary>
  375. /// 异步按路径保存产品(包装同步实现)。
  376. /// </summary>
  377. /// <param name="id">产品 ID。</param>
  378. /// <param name="filePath">保存路径。</param>
  379. /// <returns>表示异步操作的任务。</returns>
  380. public Task SaveProductAsync(Guid id, string filePath)
  381. {
  382. return Task.Run(() => SaveProduct(id, filePath));
  383. }
  384. // 新增:不需要传入路径的保存,使用约定目录和文件名
  385. /// <summary>
  386. /// 将产品保存到约定目录(ProductsRootPath\<product.Name>\<product.Name>.cfg),并保存其视觉 ToolBlock 文件。
  387. /// </summary>
  388. /// <param name="id">产品 ID。</param>
  389. public void SaveProduct(Guid id)
  390. {
  391. // 获取产品
  392. var p = GetProduct(id);
  393. if (p == null) return;
  394. // 获取产品文件路径,产品路径为:ProductsRootPath//p.Name//p.Name.cfg
  395. string filePath = Path.Combine(ProductsRootPath, p.Name, p.Name + ".cfg");
  396. SaveProduct(p, filePath);
  397. }
  398. /// <summary>
  399. /// 将指定的 <see cref="ProductModel"/> 序列化并写入指定路径,同时为每个相机流程保存或初始化对应的 `.vpp` ToolBlock 文件。
  400. /// </summary>
  401. /// <param name="p">产品模型,不能为空。</param>
  402. /// <param name="filePath">目标配置文件路径(包含文件名)。</param>
  403. /// <exception cref="ArgumentNullException">当 <paramref name="p"/> 为 null 时抛出。</exception>
  404. public void SaveProduct(ProductModel p, string filePath)
  405. {
  406. if (p == null) throw new ArgumentNullException(nameof(p));
  407. var dir = Path.GetDirectoryName(filePath);
  408. if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
  409. FileHelper.WriteJsonFile(p, filePath);
  410. //foreach (var item in p.CameraProcedures)
  411. //{
  412. // foreach (var item1 in item.ProcedureModels)
  413. // {
  414. // string prcPath = dir + "//" + item.Camera + "//" + item1.Name + ".vpp";
  415. // var prcDir = Path.GetDirectoryName(prcPath);
  416. // if (!Directory.Exists(prcDir))
  417. // {
  418. // Directory.CreateDirectory(prcDir);
  419. // }
  420. // // 重要:先加载已存在的目标 vpp(如果存在),避免 CopyProduct 刚复制过来时仍持有旧模板/ToolBlock 引用
  421. // if (File.Exists(prcPath))
  422. // {
  423. // if (item1.ToolBlock == null)
  424. // {
  425. // item1.ToolBlock = VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(prcPath).GetAwaiter().GetResult();
  426. // }
  427. // //continue;
  428. // }
  429. // if (item1.ToolBlock != null)
  430. // {
  431. // VisionProHelper.SaveVisionProObjectAsync(item1.ToolBlock, prcPath).GetAwaiter().GetResult();
  432. // }
  433. // else if (File.Exists(TemplateToolBlock))
  434. // {
  435. // item1.ToolBlock = VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(TemplateToolBlock).GetAwaiter().GetResult();
  436. // VisionProHelper.SaveVisionProObjectAsync(item1.ToolBlock, prcPath).GetAwaiter().GetResult();
  437. // }
  438. // }
  439. //}
  440. }
  441. /// <summary>
  442. /// 异步按约定目录保存产品。
  443. /// </summary>
  444. /// <param name="id">产品 ID。</param>
  445. /// <returns>表示异步操作的任务。</returns>
  446. public Task SaveProductAsync(Guid id)
  447. {
  448. return Task.Run(() => SaveProduct(id));
  449. }
  450. /// <summary>
  451. /// 从指定路径加载产品配置(仅反序列化 JSON,不加载 ToolBlock 文件)。
  452. /// </summary>
  453. /// <param name="filePath">产品配置文件路径。</param>
  454. /// <returns>加载得到的 <see cref="ProductModel"/>,若文件不存在则返回 null。</returns>
  455. public ProductModel LoadProduct(string filePath)
  456. {
  457. if (!File.Exists(filePath)) return null;
  458. var prd = FileHelper.ReadJsonFile<ProductModel>(filePath);
  459. return prd;
  460. }
  461. /// <summary>
  462. /// 根据内存中已注册的产品 ID,从约定目录加载其视觉 ToolBlock 并返回产品实例。
  463. /// </summary>
  464. /// <param name="id">产品 ID(必须已在内存中注册)。</param>
  465. /// <returns>加载后的 <see cref="ProductModel"/>,若未注册或找不到则返回 null。</returns>
  466. public ProductModel LoadProduct(Guid id)
  467. {
  468. var p = GetProduct(id);
  469. if (p == null) return null;
  470. // 释放上一个产品的 ToolBlock 内存
  471. UnloadPreviousProduct(id);
  472. var root = GetProductsRootFullPath();
  473. string filePath = Path.Combine(root, p.Name, p.Name + ".cfg");
  474. var dir = Path.GetDirectoryName(filePath);
  475. if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
  476. // 收集所有需要加载的流程(ToolBlock 为空的)
  477. var toLoad = new List<(string Path, ProcedureModel Model)>();
  478. foreach (var camera in p.CameraProcedures)
  479. {
  480. foreach (var prc in camera.ProcedureModels)
  481. {
  482. if (prc.ToolBlock != null) continue;
  483. string prcPath = Path.Combine(dir, camera.Camera, prc.Name + ".vpp");
  484. toLoad.Add((prcPath, prc));
  485. }
  486. }
  487. if (toLoad.Count > 0)
  488. {
  489. var parallelOptions = new ParallelOptions
  490. {
  491. MaxDegreeOfParallelism = Math.Min(toLoad.Count, Environment.ProcessorCount * 2)
  492. };
  493. Parallel.ForEach(toLoad, parallelOptions, item =>
  494. {
  495. try
  496. {
  497. if (!_vppCache.TryGetValue(item.Path, out var cached))
  498. {
  499. cached = VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(item.Path).GetAwaiter().GetResult();
  500. _vppCache.TryAdd(item.Path, cached);
  501. }
  502. item.Model.ToolBlock = cached;
  503. }
  504. catch (Exception ex)
  505. {
  506. LogHelper.logerror.Error($"加载产品视觉流程时出错,路径:{item.Path}", ex);
  507. }
  508. });
  509. }
  510. return p;
  511. }
  512. /// <summary>
  513. /// 异步加载产品视觉流程(使用缓存和异常保护)。
  514. /// </summary>
  515. /// <param name="id">产品 ID。</param>
  516. /// <returns>包含加载后产品的任务。</returns>
  517. public async Task<ProductModel> LoadProductAsync(Guid id)
  518. {
  519. //return Task.Run(() => LoadProduct(id));
  520. var p = GetProduct(id);
  521. if (p == null) return null;
  522. // 释放上一个产品的 ToolBlock 内存
  523. UnloadPreviousProduct(id);
  524. var root = GetProductsRootFullPath();
  525. string filePath = Path.Combine(root, p.Name, p.Name + ".cfg");
  526. var dir = Path.GetDirectoryName(filePath);
  527. if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
  528. // 收集所有需要加载的流程(ToolBlock 为空的)
  529. var toLoad = new List<(string Path, ProcedureModel Model)>();
  530. foreach (var camera in p.CameraProcedures)
  531. {
  532. foreach (var prc in camera.ProcedureModels)
  533. {
  534. if (prc.ToolBlock != null) continue;
  535. string prcPath = Path.Combine(dir, camera.Camera, prc.Name + ".vpp");
  536. toLoad.Add((prcPath, prc));
  537. }
  538. }
  539. if (toLoad.Count > 0)
  540. {
  541. // 限制并发数量,避免同时创建过多 STA 线程
  542. var semaphore = new SemaphoreSlim(Math.Min(toLoad.Count, Environment.ProcessorCount * 2));
  543. var tasks = toLoad.Select(async item =>
  544. {
  545. await semaphore.WaitAsync();
  546. try
  547. {
  548. if (!_vppCache.TryGetValue(item.Path, out var cached))
  549. {
  550. cached = await VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(item.Path);
  551. _vppCache.TryAdd(item.Path, cached);
  552. }
  553. item.Model.ToolBlock = cached;
  554. }
  555. catch (Exception ex)
  556. {
  557. LogHelper.logerror.Error($"加载产品视觉流程时出错,路径:{item.Path}", ex);
  558. }
  559. finally
  560. {
  561. semaphore.Release();
  562. }
  563. });
  564. await Task.WhenAll(tasks);
  565. }
  566. return p;
  567. }
  568. /// <summary>
  569. /// 从系统配置中读取上次打开的产品并尝试加载该产品到内存,并将其设置为当前产品。
  570. /// </summary>
  571. /// <returns>若成功加载并设置则返回 (id, name),否则返回 (Guid.Empty, string.Empty)。</returns>
  572. public (Guid id, string name) LoadLastProduct()
  573. {
  574. // 获取最后打开的产品ID
  575. var sysConfig = _configService.GetSystemConfiguration();
  576. if (sysConfig == null || sysConfig.LastOpenedProductId == Guid.Empty)
  577. {
  578. return (Guid.Empty, string.Empty);
  579. }
  580. var lastProductId = sysConfig.LastOpenedProductId;
  581. //判断是否存在产品
  582. if (!ContainsProduct(lastProductId))
  583. {
  584. return (Guid.Empty, string.Empty);
  585. }
  586. // 尝试从磁盘加载
  587. var loaded = LoadProduct(lastProductId);
  588. if (loaded != null)
  589. {
  590. SetCurrentProduct(lastProductId);
  591. return (lastProductId, loaded.Name ?? string.Empty);
  592. }
  593. // 如果未能加载,返回空结果
  594. return (Guid.Empty, string.Empty);
  595. }
  596. /// <summary>
  597. /// 异步加载最后打开的产品(包装同步实现)。
  598. /// </summary>
  599. /// <returns>包含 (id, name) 的任务。</returns>
  600. public Task<(Guid id, string name)> LoadLastProductAsync()
  601. {
  602. // 可以使用 Task.FromResult,因为内部是同步且快速的文件检测/读取
  603. return Task.Run(() => LoadLastProduct());
  604. }
  605. /// <summary>
  606. /// 将指定产品设置为当前产品,并更新系统配置中的 LastOpenedProductId,同时触发 OnProductChanged 事件。
  607. /// 仅当内存中存在该产品时生效。
  608. /// </summary>
  609. /// <param name="id">要设置为当前的产品 ID。</param>
  610. public void SetCurrentProduct(Guid id)
  611. {
  612. lock (_sync)
  613. {
  614. if (_products.ContainsKey(id))
  615. {
  616. _currentProduct = id;
  617. _products[id].IsLoad = true;
  618. //将其他的产品设置为未加载状态
  619. foreach (var kvp in _products)
  620. {
  621. if (kvp.Key != id)
  622. {
  623. kvp.Value.IsLoad = false;
  624. }
  625. }
  626. var sysConfig = _configService.GetSystemConfiguration();
  627. sysConfig.LastOpenedProductId = id;
  628. _configService.SaveSystemConfiguration(sysConfig);
  629. OnCurrentProductChanged(_products[id]);
  630. }
  631. }
  632. }
  633. /// <summary>
  634. /// 释放上一个产品(非目标产品)所有流程的 ToolBlock,释放 VisionPro 对象占用的内存。
  635. /// </summary>
  636. private void UnloadPreviousProduct(Guid targetProductId)
  637. {
  638. lock (_sync)
  639. {
  640. if (_currentProduct == Guid.Empty || _currentProduct == targetProductId)
  641. return;
  642. if (_products.TryGetValue(_currentProduct, out var oldProduct))
  643. {
  644. UnloadProductToolBlocks(oldProduct);
  645. }
  646. }
  647. }
  648. /// <summary>
  649. /// 释放指定产品所有流程的 ToolBlock 引用,释放 VisionPro 对象占用的内存。
  650. /// </summary>
  651. private void UnloadProductToolBlocks(ProductModel product)
  652. {
  653. if (product?.CameraProcedures == null) return;
  654. foreach (var camera in product.CameraProcedures)
  655. {
  656. if (camera.ProcedureModels == null) continue;
  657. foreach (var prc in camera.ProcedureModels)
  658. {
  659. if (prc.ToolBlock != null)
  660. {
  661. prc.ToolBlock.Dispose();
  662. prc.ToolBlock = null;
  663. }
  664. }
  665. }
  666. // 清空 VPP 缓存,因为缓存的 ToolBlock 已被 Dispose
  667. _vppCache.Clear();
  668. }
  669. /// <summary>
  670. /// 获取当前产品模型(若未设置则返回 null)。
  671. /// </summary>
  672. /// <returns>当前产品或 null。</returns>
  673. public ProductModel GetCurrentProduct()
  674. {
  675. lock (_sync)
  676. {
  677. if (_currentProduct == Guid.Empty) return null;
  678. _products.TryGetValue(_currentProduct, out var p);
  679. return p;
  680. }
  681. }
  682. /// <summary>
  683. /// 复制已有产品并为副本分配新的 ID 与名称,同时保存副本及其 VPP 文件,并返回新副本的 ID。
  684. /// </summary>
  685. /// <param name="id">源产品 ID。</param>
  686. /// <param name="newName">新产品的名称。</param>
  687. /// <returns>新产品的 ID,失败时返回 Guid.Empty。</returns>
  688. public Guid CopyProduct(Guid id, string newName)
  689. {
  690. var p = GetProduct(id);
  691. if (p == null) return Guid.Empty;
  692. var clone = p.Clone();
  693. clone.ID = Guid.NewGuid();
  694. clone.Name = newName;
  695. clone.DateTime = DateTime.Now;
  696. CreateProduct(clone);
  697. try
  698. {
  699. var root = GetProductsRootFullPath();
  700. var srcDir = Path.Combine(root, p.Name);
  701. var dstDir = Path.Combine(root, clone.Name);
  702. if (Directory.Exists(srcDir) && Directory.Exists(dstDir))
  703. {
  704. CopyVppFiles(srcDir, dstDir);
  705. }
  706. // 强制为新产品的 ToolBlock 从磁盘 vpp 重新加载,避免内存中残留模板/旧对象
  707. LoadProduct(clone.ID);
  708. }
  709. catch (Exception ex)
  710. {
  711. LogHelper.WriteLogError("复制产品时发生Vpp文件错误", ex);
  712. }
  713. return clone.ID;
  714. }
  715. private static void CopyVppFiles(string sourceProductDir, string targetProductDir)
  716. {
  717. var vppFiles = Directory.GetFiles(sourceProductDir, "*.vpp", SearchOption.AllDirectories);
  718. foreach (var srcFile in vppFiles)
  719. {
  720. var relative = srcFile.Substring(sourceProductDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
  721. var dstFile = Path.Combine(targetProductDir, relative);
  722. var dstFolder = Path.GetDirectoryName(dstFile);
  723. if (!Directory.Exists(dstFolder))
  724. {
  725. Directory.CreateDirectory(dstFolder);
  726. }
  727. File.Copy(srcFile, dstFile, true);
  728. }
  729. }
  730. /// <summary>
  731. /// 异步复制产品。
  732. /// </summary>
  733. /// <param name="id">源产品 ID。</param>
  734. /// <param name="newName">新名称。</param>
  735. /// <returns>包含新产品 ID 的任务。</returns>
  736. public Task<Guid> CopyProductAsync(Guid id, string newName)
  737. {
  738. return Task.Run(() => CopyProduct(id, newName));
  739. }
  740. /// <summary>
  741. /// 永久删除产品:从内存中移除并递归删除其在磁盘上的文件夹及所有内容。
  742. /// </summary>
  743. /// <param name="id">要删除的产品 ID。</param>
  744. public void DeleteProduct(Guid id)
  745. {
  746. //获取产品
  747. var p = GetProduct(id);
  748. //如果产品不存在,直接返回
  749. if (p == null) return;
  750. //获取产品文件夹路径,产品路径为:ProductsRootPath//p.Name
  751. string productDirPath = Path.Combine(ProductsRootPath, p.Name);
  752. //移除产品
  753. RemoveProduct(id);
  754. //删除产品文件夹及其内容
  755. DeleteDirectoryRecursively(productDirPath);
  756. }
  757. /// <summary>
  758. /// 异步删除产品(包装同步实现)。
  759. /// </summary>
  760. /// <param name="id">产品 ID。</param>
  761. /// <returns>表示异步删除操作的任务。</returns>
  762. public Task DeleteProductAsync(Guid id)
  763. {
  764. return Task.Run(() => DeleteProduct(id));
  765. }
  766. /// <summary>
  767. /// 对指定产品进行重命名:更新内存模型并在磁盘上重命名对应文件夹(若存在),然后保存产品清单与产品配置。
  768. /// </summary>
  769. /// <param name="id">产品 ID。</param>
  770. /// <param name="newName">新的产品名称。</param>
  771. public void RenameProduct(Guid id, string newName)
  772. {
  773. // 获取产品
  774. var p = GetProduct(id);
  775. if (p == null) return;
  776. // 获取旧产品文件夹路径,产品路径为:ProductsRootPath//p.Name
  777. string oldProductDirPath = Path.Combine(ProductsRootPath, p.Name);
  778. // 更新产品名称
  779. p.Name = newName;
  780. // 获取新产品文件夹路径
  781. string newProductDirPath = Path.Combine(ProductsRootPath, newName);
  782. // 重命名文件夹
  783. if (Directory.Exists(oldProductDirPath))
  784. {
  785. Directory.Move(oldProductDirPath, newProductDirPath);
  786. }
  787. // 保存产品清单
  788. SaveProductList();
  789. //对产品进行保存
  790. SaveProduct(id);
  791. }
  792. /// <summary>
  793. /// 异步重命名产品(包装同步实现)。
  794. /// </summary>
  795. /// <param name="id">产品 ID。</param>
  796. /// <param name="newName">新的名称。</param>
  797. /// <returns>表示异步操作的任务。</returns>
  798. public Task RenameProductAsync(Guid id, string newName)
  799. {
  800. return Task.Run(() => RenameProduct(id, newName));
  801. }
  802. /// <summary>
  803. /// 更新内存中产品对象并将其保存到磁盘(若存在)。
  804. /// </summary>
  805. /// <param name="product">要更新的产品模型(不能为空)。</param>
  806. public void UpdateProduct(ProductModel product)
  807. {
  808. if (product == null) throw new ArgumentNullException(nameof(product));
  809. lock (_sync)
  810. {
  811. if (_products.ContainsKey(product.ID))
  812. {
  813. _products[product.ID] = product;
  814. }
  815. }
  816. // 更新后自动保存到磁盘
  817. SaveProduct(product.ID);
  818. }
  819. /// <summary>
  820. /// 异步更新产品(包装同步实现)。
  821. /// </summary>
  822. /// <param name="product">产品模型。</param>
  823. /// <returns>表示异步操作的任务。</returns>
  824. public Task UpdateProductAsync(ProductModel product)
  825. {
  826. return Task.Run(() => UpdateProduct(product));
  827. }
  828. /// <summary>
  829. /// 根据指定的模板名称创建产品并保存。模板文件位于 <see cref="ProductTemplatePath"/>。
  830. /// </summary>
  831. /// <param name="templateName">模板名称(对应子文件夹与 cfg 文件名)。</param>
  832. /// <param name="productName">新产品名称。</param>
  833. /// <returns>创建并返回的新产品模型;若模板不存在则返回 null。</returns>
  834. public ProductModel CreateProductByTemplateName(string templateName, string productName)
  835. {
  836. // 产品模板路径为:ProductTemplatePath//templateName//templateName.cfg
  837. string templateFilePath = Path.Combine(ProductTemplatePath, templateName, templateName + ".cfg");
  838. var templateProduct = LoadProduct(templateFilePath);
  839. if (templateProduct == null) return null;
  840. var newProduct = templateProduct.Clone();
  841. newProduct.Name = productName;
  842. newProduct.ID = Guid.NewGuid();
  843. CreateProduct(newProduct);
  844. return GetProduct(newProduct.ID);
  845. }
  846. /// <summary>
  847. /// 异步根据模板创建产品。
  848. /// </summary>
  849. /// <param name="templateName">模板名。</param>
  850. /// <param name="productName">产品名。</param>
  851. /// <returns>包含新产品模型的任务。</returns>
  852. public Task<ProductModel> CreateProductByTemplateNameAsync(string templateName, string productName)
  853. {
  854. return Task.Run(() => CreateProductByTemplateName(templateName, productName));
  855. }
  856. /// <summary>
  857. /// 在所有产品中增加一个相机流程(当系统新增相机时调用),并保存每个产品的配置。
  858. /// </summary>
  859. /// <param name="cameraId">相机 ID。</param>
  860. /// <param name="cameraName">相机名称。</param>
  861. public void AddCameraToProduct(Guid cameraId, string cameraName)
  862. {
  863. //获取所有产品
  864. var products = GetAllProducts();
  865. if (products == null) return;
  866. //遍历所有产品,增加相机流程
  867. foreach (var item in products)
  868. {
  869. item.AddCameraProcedure(new CameraProcedure(cameraId, cameraName));
  870. //单个产品的配置文件路径
  871. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  872. //保存产品
  873. FileHelper.WriteJsonFile(item, productFilePath);
  874. }
  875. }
  876. /// <summary>
  877. /// 异步在所有产品中增加相机流程。
  878. /// </summary>
  879. /// <param name="cameraId">相机 ID。</param>
  880. /// <param name="cameraName">相机名。</param>
  881. /// <returns>表示异步操作的任务。</returns>
  882. public Task AddCameraToProductAsync(Guid cameraId, String cameraName)
  883. {
  884. return Task.Run(() => AddCameraToProduct(cameraId, cameraName));
  885. }
  886. /// <summary>
  887. /// 在所有产品中移除指定相机对应的流程,并保存产品文件。
  888. /// </summary>
  889. /// <param name="cameraId">要移除的相机 ID。</param>
  890. public void RemoveCameraFromProduct(Guid cameraId)
  891. {
  892. var products = GetAllProducts();
  893. if (products == null) return;
  894. //遍历所有产品,删除相机流程
  895. foreach (var item in products)
  896. {
  897. item.RemoveCameraProcedure(cameraId);
  898. //单个产品的配置文件路径
  899. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  900. //保存产品
  901. FileHelper.WriteJsonFile(item, productFilePath);
  902. }
  903. }
  904. /// <summary>
  905. /// 异步在所有产品中移除相机流程。
  906. /// </summary>
  907. /// <param name="cameraId">相机 ID。</param>
  908. /// <returns>任务。</returns>
  909. public Task RemoveCameraFromProductAsync(Guid cameraId)
  910. {
  911. return Task.Run(() => RemoveCameraFromProduct(cameraId));
  912. }
  913. /// <summary>
  914. /// 更新所有产品中指定相机的名称,并在磁盘上重命名对应的相机文件夹(若存在)。
  915. /// </summary>
  916. /// <param name="cameraId">相机 ID。</param>
  917. /// <param name="newCameraName">新相机名称。</param>
  918. public void UpdateCameraNameInProduct(Guid cameraId, string newCameraName)
  919. {
  920. var products = GetAllProducts();
  921. if (products == null) return;
  922. //遍历所有产品,修改相机名称
  923. foreach (var item in products)
  924. {
  925. //旧名称
  926. string oldCameraName = string.Empty;
  927. var cameraProcedure = item.CameraProcedures.FirstOrDefault(cp => cp.ID == cameraId);
  928. if (cameraProcedure != null)
  929. {
  930. oldCameraName = cameraProcedure.Camera;
  931. cameraProcedure.Camera = newCameraName;
  932. }
  933. //单个产品的配置文件路径
  934. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  935. //保存产品
  936. FileHelper.WriteJsonFile(item, productFilePath);
  937. if (!string.IsNullOrEmpty(oldCameraName))
  938. {
  939. //改之前相机流程文件夹路径
  940. string cameraDirPath = Path.Combine(ProductsRootPath, item.Name, oldCameraName);
  941. //如果相机名称发生变化,重命名相机流程文件夹
  942. if (oldCameraName != newCameraName)
  943. {
  944. string newCameraDirPath = Path.Combine(ProductsRootPath, item.Name, newCameraName);
  945. if (Directory.Exists(cameraDirPath))
  946. {
  947. Directory.Move(cameraDirPath, newCameraDirPath);
  948. }
  949. }
  950. }
  951. }
  952. }
  953. /// <summary>
  954. /// 异步更新所有产品中的相机名称。
  955. /// </summary>
  956. /// <param name="cameraId">相机 ID。</param>
  957. /// <param name="newCameraName">新名称。</param>
  958. /// <returns>任务。</returns>
  959. public Task UpdateCameraNameInProductAsync(Guid cameraId, string newCameraName)
  960. {
  961. return Task.Run(() => UpdateCameraNameInProduct(cameraId, newCameraName));
  962. }
  963. /// <summary>
  964. /// 在所有产品中增加机器人点位表条目并保存对应产品文件(当系统新增机器人或点位时调用)。
  965. /// </summary>
  966. /// <param name="robotId">机器人 ID。</param>
  967. /// <param name="robotPointName">点位名称。</param>
  968. public void AddRobotPointToProduct(Guid robotId, string robotPointName)
  969. {
  970. //获取所有产品
  971. var products = GetAllProducts();
  972. if (products == null) return;
  973. //遍历所有产品,增加机器人点位表
  974. foreach (var item in products)
  975. {
  976. item.RobotPoint.AddRobot(robotId, robotPointName);
  977. //单个产品的配置文件路径
  978. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  979. //保存产品
  980. FileHelper.WriteJsonFile(item, productFilePath);
  981. }
  982. }
  983. /// <summary>
  984. /// 在所有产品中增加扫码枪点位表条目并保存对应产品文件(当系统新增扫码枪或点位时调用)。
  985. /// </summary>
  986. /// <param name="scannerId">扫码枪 ID。</param>
  987. /// <param name="scannerPointName">点位名称。</param>
  988. public void AddScannerPointToProduct(Guid scannerId, string scannerPointName)
  989. {
  990. //获取所有产品
  991. var products = GetAllProducts();
  992. if (products == null) return;
  993. //遍历所有产品,增加扫码枪点位表
  994. foreach (var item in products)
  995. {
  996. //item.ScannerPoint.AddScanner(scannerId, scannerPointName);
  997. //单个产品的配置文件路径
  998. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  999. //保存产品
  1000. FileHelper.WriteJsonFile(item, productFilePath);
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// 异步为所有产品增加机器人点位。
  1005. /// </summary>
  1006. /// <param name="robotId">机器人 ID。</param>
  1007. /// <param name="robotPointName">点位名。</param>
  1008. /// <returns>任务。</returns>
  1009. public Task AddRobotPointToProductAsync(Guid robotId, string robotPointName)
  1010. {
  1011. return Task.Run(() => AddRobotPointToProduct(robotId, robotPointName));
  1012. }
  1013. /// <summary>
  1014. /// 在所有产品中移除指定机器人相关的点位配置并保存产品文件。
  1015. /// </summary>
  1016. /// <param name="robotId">机器人 ID。</param>
  1017. public void RemoveRobotPointFromProduct(Guid robotId)
  1018. {
  1019. var products = GetAllProducts();
  1020. if (products == null) return;
  1021. //遍历所有产品,删除机器人点位表
  1022. foreach (var item in products)
  1023. {
  1024. item.RobotPoint.RemoveRobot(robotId);
  1025. //单个产品的配置文件路径
  1026. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  1027. //保存产品
  1028. FileHelper.WriteJsonFile(item, productFilePath);
  1029. }
  1030. }
  1031. /// <summary>
  1032. /// 在所有产品中移除指定扫码枪相关的点位配置并保存产品文件。
  1033. /// </summary>
  1034. /// <param name="scannerId">扫码枪 ID。</param>
  1035. public void RemoveScannerPointFromProduct(Guid scannerId)
  1036. {
  1037. var products = GetAllProducts();
  1038. if (products == null) return;
  1039. //遍历所有产品,删除扫码枪点位表
  1040. foreach (var item in products)
  1041. {
  1042. //item.ScannerPoint.RemoveScanner(scannerId);
  1043. //单个产品的配置文件路径
  1044. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  1045. //保存产品
  1046. FileHelper.WriteJsonFile(item, productFilePath);
  1047. }
  1048. }
  1049. /// <summary>
  1050. /// 异步在所有产品中移除机器人点位。
  1051. /// </summary>
  1052. /// <param name="robotId">机器人 ID。</param>
  1053. /// <returns>任务。</returns>
  1054. public Task RemoveRobotPointFromProductAsync(Guid robotId)
  1055. {
  1056. return Task.Run(() => RemoveRobotPointFromProduct(robotId));
  1057. }
  1058. /// <summary>
  1059. /// 更新所有产品中指定机器人点位的名称并保存产品配置。
  1060. /// </summary>
  1061. /// <param name="robotId">机器人 ID。</param>
  1062. /// <param name="newRobotPointName">新的点位名称。</param>
  1063. public void UpdateRobotPointNameInProduct(Guid robotId, string newRobotPointName)
  1064. {
  1065. var products = GetAllProducts();
  1066. if (products == null) return;
  1067. //遍历所有产品,修改机器人点位名称
  1068. foreach (var item in products)
  1069. {
  1070. var robotPointStore = item.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robotId);
  1071. if (robotPointStore != null)
  1072. {
  1073. robotPointStore.Name = newRobotPointName;
  1074. }
  1075. //单个产品的配置文件路径
  1076. string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg");
  1077. //保存产品
  1078. FileHelper.WriteJsonFile(item, productFilePath);
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// 异步更新机器人点位名称。
  1083. /// </summary>
  1084. /// <param name="robotId">机器人 ID。</param>
  1085. /// <param name="newRobotPointName">新名称。</param>
  1086. /// <returns>任务。</returns>
  1087. public Task UpdateRobotPointNameInProductAsync(Guid robotId, string newRobotPointName)
  1088. {
  1089. return Task.Run(() => UpdateRobotPointNameInProduct(robotId, newRobotPointName));
  1090. }
  1091. /// <summary>
  1092. /// 加载指定产品的某个相机流程的视觉工具(ToolBlock)。
  1093. /// 若视觉工具文件不存在则尝试从模板加载并保存到目标路径;若模板也不存在则抛出 <see cref="FileNotFoundException"/>。
  1094. /// </summary>
  1095. /// <param name="productid">产品 ID。</param>
  1096. /// <param name="cameraid">相机 ID。</param>
  1097. /// <param name="prcname">流程名称。</param>
  1098. public void LoadProcedureVisionTools(Guid productid, Guid cameraid, string prcname)
  1099. {
  1100. //获取产品
  1101. var product = GetProduct(productid);
  1102. if (product == null) return;
  1103. //获取相机流程
  1104. var cameraProcedure = product.CameraProcedures.FirstOrDefault(cp => cp.ID == cameraid);
  1105. if (cameraProcedure == null) return;
  1106. //获取指定名称的流程
  1107. var procedure = cameraProcedure.ProcedureModels.FirstOrDefault(pm => pm.Name == prcname);
  1108. if (procedure == null) return;
  1109. //获取流程视觉工具路径
  1110. var root = GetProductsRootFullPath();
  1111. string vpppath = Path.Combine(root, product.Name, cameraProcedure.Camera, prcname + ".vpp");
  1112. if (File.Exists(vpppath))
  1113. {
  1114. procedure.ToolBlock = VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(vpppath).GetAwaiter().GetResult();
  1115. }
  1116. else if (File.Exists(TemplateToolBlock))
  1117. {
  1118. procedure.ToolBlock = VisionProHelper.LoadVisionProObjectAsync<CogToolBlock>(TemplateToolBlock).GetAwaiter().GetResult();
  1119. //保存到指定路径
  1120. VisionProHelper.SaveVisionProObjectAsync(procedure.ToolBlock, vpppath).GetAwaiter().GetResult();
  1121. }
  1122. else
  1123. {
  1124. throw new FileNotFoundException("模板工具文件不存在,无法创建新的视觉工具。", TemplateToolBlock);
  1125. }
  1126. }
  1127. /// <summary>
  1128. /// 异步加载指定产品流程的视觉工具,返回是否成功。
  1129. /// </summary>
  1130. /// <param name="productid">产品 ID。</param>
  1131. /// <param name="cameraid">相机 ID。</param>
  1132. /// <param name="prcname">流程名称。</param>
  1133. /// <returns>成功返回 true,发生异常返回 false。</returns>
  1134. public Task<bool> LoadProcedureVisionToolsAsync(Guid productid, Guid cameraid, string prcname)
  1135. {
  1136. return Task.Run(() =>
  1137. {
  1138. try
  1139. {
  1140. LoadProcedureVisionTools(productid, cameraid, prcname);
  1141. return true;
  1142. }
  1143. catch
  1144. {
  1145. return false;
  1146. }
  1147. });
  1148. }
  1149. /// <summary>
  1150. /// 获取当前产品的指定视觉流程ID的视觉流程对象
  1151. /// </summary>
  1152. /// <param name="procedureId">视觉流程 ID。</param>
  1153. /// <returns>对应的 <see cref="ProcedureModel"/>,若未找到则返回 null。</returns>
  1154. public ProcedureModel GetCurrentProductProcedureModelById(Guid procedureId)
  1155. {
  1156. var currentProduct = GetCurrentProduct();
  1157. if (currentProduct == null) return null;
  1158. foreach (var cameraProcedure in currentProduct.CameraProcedures)
  1159. {
  1160. var procedure = cameraProcedure.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId);
  1161. if (procedure != null)
  1162. {
  1163. return procedure;
  1164. }
  1165. }
  1166. return null;
  1167. }
  1168. /// <summary>
  1169. /// 递归删除指定目录及其所有子目录和文件。
  1170. /// 注意:此操作会永久删除磁盘上的文件,请谨慎调用。
  1171. /// </summary>
  1172. /// <param name="dirPath">要删除的目录路径。</param>
  1173. private void DeleteDirectoryRecursively(string dirPath)
  1174. {
  1175. if (Directory.Exists(dirPath))
  1176. {
  1177. var dirInfo = new DirectoryInfo(dirPath);
  1178. // 删除所有文件
  1179. foreach (var file in dirInfo.GetFiles())
  1180. {
  1181. file.Delete();
  1182. }
  1183. // 递归删除所有子目录
  1184. foreach (var dir in dirInfo.GetDirectories())
  1185. {
  1186. DeleteDirectoryRecursively(dir.FullName);
  1187. }
  1188. // 删除当前目录
  1189. dirInfo.Delete();
  1190. }
  1191. }
  1192. /// <summary>
  1193. /// 触发当前产品切换事件的内部方法(线程安全地调用事件)。
  1194. /// </summary>
  1195. /// <param name="product">新的当前产品。</param>
  1196. private void OnCurrentProductChanged(ProductModel product)
  1197. {
  1198. OnProductChanged?.Invoke(product);
  1199. }
  1200. /// <summary>
  1201. /// 当前产品编号
  1202. /// </summary>
  1203. public string CurrentProductCode { get; set; }
  1204. /// <summary>
  1205. /// 释放资源,清空内存中的产品集合并抑制终结化。
  1206. /// </summary>
  1207. public void Dispose()
  1208. {
  1209. RemoveAllProducts();
  1210. GC.SuppressFinalize(this);
  1211. }
  1212. /// <summary>
  1213. /// 获取产品根目录的完整物理路径,统一基于应用程序基目录解析,避免当前工作目录变化导致路径漂移。
  1214. /// </summary>
  1215. /// <returns>产品根目录的完整物理路径。</returns>
  1216. private string GetProductsRootFullPath()
  1217. {
  1218. if (Path.IsPathRooted(ProductsRootPath))
  1219. {
  1220. return ProductsRootPath;
  1221. }
  1222. // 统一基于应用基目录解析,避免当前工作目录变化导致路径漂移
  1223. return Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ProductsRootPath));
  1224. }
  1225. }
  1226. }