using Cognex.VisionPro; using Cognex.VisionPro.ToolBlock; using Newtonsoft.Json; using NPOI.SS.Formula.Functions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Documents; using Team.FFFeederService.Interfaces; using TeamAAS_VP.Core; using TeamAAS_VP.Interfaces; using TeamAAS_VP.Models; using TeamAAS_VP.Models.Product; using TeamAAS_VP.Resources.Languages; namespace TeamAAS_VP.Services { /// /// 产品管理服务。 /// 负责在内存中维护产品集合、加载/保存产品到磁盘、产品的增删改查、相机/机器人相关变更的级联更新等操作。 /// 线程安全:使用 `_sync` 对共享字典 `_products` 的访问进行保护。 /// 产品文件存放遵循约定目录:`ProductsRootPath\{ProductName}\{ProductName}.cfg`,视觉流程文件为 `.vpp`。 /// public class ProductService : IProductService { private readonly Dictionary _products = new Dictionary(); private readonly object _sync = new object(); private Guid _currentProduct = Guid.Empty; IConfigService _configService; IFeederService _feederService; // 可配置的路径与文件名 // 默认把产品放到公共应用数据目录下的 TeamAAS\Products /// /// 默认产品路径的相对子目录(相对于应用运行目录或配置指定的根)。 /// public const string DefaultProductsSubPath = "..//Products"; /// /// 模板 ToolBlock 的默认路径,用于在产品不存在视觉工具文件时进行初始化。 /// public const string TemplateToolBlock = "..//Vision Template//TemplateToolBlock.vpp"; /// /// 产品模板文件夹路径(用于通过模板创建新产品)。 /// public const string ProductTemplatePath = "..//Product Template"; /// /// 产品根目录(可配置)。默认值为 . /// 每个产品在该目录下以其 Name 为子文件夹保存其配置与视觉文件。 /// public string ProductsRootPath { get; set; } /// /// 当当前产品切换时触发的事件,参数为新的当前 实例。 /// public event Action OnProductChanged; /// /// 当前产品编号 /// public string CurrentProductCode { get; set; } /// /// 构造函数。 /// /// 系统配置服务,用于读取/保存最近打开的产品等系统配置。 /// 料斗服务,当前保存但未直接在本类中使用(保留用于扩展)。 public ProductService(IConfigService configService, IFeederService feederService) { _configService = configService; _feederService = feederService; ProductsRootPath = DefaultProductsSubPath; } /// /// 初始化服务:清空内存产品并从磁盘枚举并加载产品清单(仅读取 JSON 配置,不加载所有视觉 ToolBlock)。 /// /// 初始化是否成功(始终返回 true,除非抛出未捕获异常)。 public bool Initialize() { // 清空现有产品 RemoveAllProducts(); // 获取所有产品列表 var productList = GetAllProductList(); lock (_sync) { foreach (var (id, name, filePath) in productList) { var product = LoadProduct(filePath); if (product != null) { _products[id] = product; } } } return true; } /// /// 异步初始化服务。 /// /// 异步任务,完成时返回初始化结果。 public Task InitializeAsync() { return Task.Run(() => Initialize()); } /// /// 获取本地所有产品的元信息列表(ID、名称、配置文件路径)。 /// /// 返回一个元组集合,每项包含产品 ID、名称和对应的配置文件路径。 public IEnumerable<(Guid id,string name,string filePath)> GetAllProductList() { if (!Directory.Exists(ProductsRootPath)) { Directory.CreateDirectory(ProductsRootPath); } //在产品目录下有一个ProductList.cfg文件,里面保存了所有产品的ID和名称 string productListFilePath = Path.Combine(ProductsRootPath, "ProductList.cfg"); if (!File.Exists(productListFilePath)) { return Enumerable.Empty<(Guid id, string name, string filePath)>(); } // 读取文件内容,这是一个Json文件,里面保存了所有产品的ID和名称 Dictionary list = FileHelper.ReadJsonFile>(productListFilePath); var result = new List<(Guid id, string name, string filePath)>(); foreach (var kvp in list) { var id = kvp.Key; var name = kvp.Value; //产品路径为:ProductsRootPath//kvp.Value//kvp.Value.cfg var filePath = Path.Combine(ProductsRootPath, name, name + ".cfg"); result.Add((id, name, filePath)); } return result; } /// /// 将当前内存中的产品清单保存到磁盘(ProductList.cfg)。 /// public void SaveProductList() { if (!Directory.Exists(ProductsRootPath)) { Directory.CreateDirectory(ProductsRootPath); } //在产品目录下有一个ProductList.cfg文件,里面保存了所有产品的ID和名称 string productListFilePath = Path.Combine(ProductsRootPath, "ProductList.cfg"); Dictionary list = new Dictionary(); lock (_sync) { foreach (var kvp in _products) { list[kvp.Key] = kvp.Value.Name; } } // 保存为Json文件 FileHelper.WriteJsonFile(list, productListFilePath); } /// /// 异步保存产品清单到磁盘。 /// /// 表示异步操作的任务。 public Task SaveProductListAsync() { return Task.Run(() => SaveProductList()); } /// /// 在内存中创建并注册一个新产品,同时将其保存到磁盘。 /// /// 要创建的产品模型。若其 ID 为空则会分配新的 GUID。 /// 若名称冲突则返回 false;否则返回 true 表示创建成功。 /// 为 null 时抛出。 public bool CreateProduct(ProductModel product) { if (product == null) throw new ArgumentNullException(nameof(product)); //如果当前存在同名产品,则创建失败 lock (_sync) { if (_products.Values.Any(p => p.Name == product.Name)) { return false; } } //对产品的编号进行自增 lock (_sync) { if (_products.Count == 0) { product.NumberCode = 1; } else { product.NumberCode = _products.Values.Max(p => p.NumberCode) + 1; } } if (product.ID == Guid.Empty) product.ID = Guid.NewGuid(); lock (_sync) { _products[product.ID] = product; } //保存产品清单 SaveProductList(); // 创建后自动保存到磁盘 SaveProduct(product.ID); return true; } /// /// 异步创建产品。 /// /// 产品模型。 /// 异步任务,结果为创建是否成功。 public Task CreateProductAsync(ProductModel product) { return Task.Run(() => CreateProduct(product)); } /// /// 根据 ID 获取内存中的产品模型(同步)。 /// /// 产品 ID。 /// 对应的 ,若不存在则返回 null。 public ProductModel GetProduct(Guid id) { lock (_sync) { _products.TryGetValue(id, out var p); return p; } } /// /// 异步获取指定 ID 的产品(仅包装同步方法)。 /// /// 产品 ID。 /// 包含产品模型的任务。 public Task GetProductAsync(Guid id) { var p = GetProduct(id); return Task.FromResult(p); } /// /// 获取当前服务内存中所有产品的只读集合。 /// /// 只读的产品集合。 public IReadOnlyCollection GetAllProducts() { lock (_sync) { return _products.Values.ToList().AsReadOnly(); } } /// /// 异步获取所有产品(包装同步实现)。 /// /// 包含只读产品集合的任务。 public Task> GetAllProductsAsync() { var list = GetAllProducts(); return Task.FromResult(list); } /// /// 尝试从内存中获取指定 ID 的产品。 /// /// 产品 ID。 /// 输出参数,若找到则为对应产品,否则为 null。 /// 若找到返回 true,否则返回 false。 public bool TryGetProduct(Guid id, out ProductModel product) { lock (_sync) { return _products.TryGetValue(id, out product); } } /// /// 异步尝试获取产品。 /// /// 产品 ID。 /// 任务,结果为 (found, product) 二元组。 public Task<(bool found, ProductModel product)> TryGetProductAsync(Guid id) { ProductModel p; bool f; lock (_sync) { f = _products.TryGetValue(id, out p); } return Task.FromResult((f, p)); } /// /// 判断内存中是否包含指定 ID 的产品。 /// /// 产品 ID。 /// 存在返回 true,否则 false。 public bool ContainsProduct(Guid id) { lock (_sync) { return _products.ContainsKey(id); } } /// /// 异步判断产品是否存在(包装同步实现)。 /// /// 产品 ID。 /// 包含结果的任务。 public Task ContainsProductAsync(Guid id) { var v = ContainsProduct(id); return Task.FromResult(v); } /// /// 判断服务中是否包含指定名称的产品(同步)。 /// /// 产品的名称 /// 若包含则返回 true;否则返回 false。 public bool ContainsProductByName(string name) { lock (_sync) { return _products.Values.Any(p => p.Name == name); } } /// /// 判断服务中是否包含指定名称的产品(异步)。 /// /// 产品的名称 /// 若包含则返回 true;否则返回 false。 public Task ContainsProductByNameAsync(string name) { return Task.FromResult(ContainsProductByName(name)); } /// /// 从内存中移除产品(不删除磁盘文件),并保存产品清单。 /// /// 要移除的产品 ID。 /// 若内存中存在并移除成功返回 true,否则 false。 public bool RemoveProduct(Guid id) { bool result; lock (_sync) { result= _products.Remove(id); } // 删除后可选择删除对应的文件(视需求而定) SaveProductList(); return result; } /// /// 异步移除产品(包装同步实现)。 /// /// 产品 ID。 /// 任务,结果为移除是否成功。 public Task RemoveProductAsync(Guid id) { var r = RemoveProduct(id); return Task.FromResult(r); } /// /// 清空内存中所有产品(不删除磁盘数据)。 /// public void RemoveAllProducts() { lock (_sync) { _products.Clear(); } } // 仍保留按路径保存的版本(向后兼容) /// /// 按指定路径保存产品。 /// /// 产品 ID。 /// 保存路径(包含文件名)。 public void SaveProduct(Guid id, string filePath) { var p = GetProduct(id); if (p == null) return; SaveProduct(p, filePath); } /// /// 异步按路径保存产品(包装同步实现)。 /// /// 产品 ID。 /// 保存路径。 /// 表示异步操作的任务。 public Task SaveProductAsync(Guid id, string filePath) { return Task.Run(() => SaveProduct(id, filePath)); } // 新增:不需要传入路径的保存,使用约定目录和文件名 /// /// 将产品保存到约定目录(ProductsRootPath\\.cfg),并保存其视觉 ToolBlock 文件。 /// /// 产品 ID。 public void SaveProduct(Guid id) { // 获取产品 var p = GetProduct(id); if (p == null) return; // 获取产品文件路径,产品路径为:ProductsRootPath//p.Name//p.Name.cfg string filePath = Path.Combine(ProductsRootPath, p.Name, p.Name + ".cfg"); SaveProduct(p, filePath); } /// /// 将指定的 序列化并写入指定路径,同时为每个相机流程保存或初始化对应的 `.vpp` ToolBlock 文件。 /// /// 产品模型,不能为空。 /// 目标配置文件路径(包含文件名)。 /// 为 null 时抛出。 public void SaveProduct(ProductModel p,string filePath) { if (p == null) throw new ArgumentNullException(nameof(p)); var dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); FileHelper.WriteJsonFile(p, filePath); foreach (var item in p.CameraProcedures) { foreach (var item1 in item.ProcedureModels) { string prcPath = dir + "//" + item.Camera + "//" + item1.Name + ".vpp"; if (!Directory.Exists(Path.GetDirectoryName(prcPath))) { Directory.CreateDirectory(Path.GetDirectoryName(prcPath)); } if (item1.ToolBlock != null) { VisionProFileHelper.SaveObjectToFileSafe(item1.ToolBlock, prcPath); } else { //判断路径下是否存在toolblock if (File.Exists(prcPath)) { item1.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(prcPath); } else { if (File.Exists(TemplateToolBlock)) { //保存模板 item1.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(TemplateToolBlock); VisionProFileHelper.SaveObjectToFileSafe(item1.ToolBlock, prcPath); } } } } } } /// /// 异步按约定目录保存产品。 /// /// 产品 ID。 /// 表示异步操作的任务。 public Task SaveProductAsync(Guid id) { return Task.Run(() => SaveProduct(id)); } /// /// 从指定路径加载产品配置(仅反序列化 JSON,不加载 ToolBlock 文件)。 /// /// 产品配置文件路径。 /// 加载得到的 ,若文件不存在则返回 null。 public ProductModel LoadProduct(string filePath) { if (!File.Exists(filePath)) return null; var prd = FileHelper.ReadJsonFile(filePath); return prd; } /// /// 根据内存中已注册的产品 ID,从约定目录加载其视觉 ToolBlock 并返回产品实例。 /// /// 产品 ID(必须已在内存中注册)。 /// 加载后的 ,若未注册或找不到则返回 null。 public ProductModel LoadProduct(Guid id) { var p = GetProduct(id); if (p == null) return null; // 获取产品文件路径,产品路径为:ProductsRootPath//p.Name//p.Name.cfg string filePath = Path.Combine(ProductsRootPath, p.Name, p.Name + ".cfg"); var dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // 加载每个相机的流程ToolBlock foreach (var camera in p.CameraProcedures) { foreach (var prc in camera.ProcedureModels) { string prcPath = dir + "//" + camera.Camera + "//" + prc.Name + ".vpp"; prc.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(prcPath); } } return p; } /// /// 异步加载产品视觉流程(包装同步实现)。 /// /// 产品 ID。 /// 包含加载后产品的任务。 public Task LoadProductAsync(Guid id) { return Task.Run(() => LoadProduct(id)); } /// /// 从系统配置中读取上次打开的产品并尝试加载该产品到内存,并将其设置为当前产品。 /// /// 若成功加载并设置则返回 (id, name),否则返回 (Guid.Empty, string.Empty)。 public (Guid id, string name) LoadLastProduct() { // 获取最后打开的产品ID var sysConfig = _configService.GetSystemConfiguration(); if (sysConfig == null || sysConfig.LastOpenedProductId == Guid.Empty) { return (Guid.Empty, string.Empty); } var lastProductId = sysConfig.LastOpenedProductId; //判断是否存在产品 if (!ContainsProduct(lastProductId)) { return (Guid.Empty, string.Empty); } // 尝试从磁盘加载 var loaded = LoadProduct(lastProductId); if (loaded != null) { SetCurrentProduct(lastProductId); return (lastProductId, loaded.Name ?? string.Empty); } // 如果未能加载,返回空结果 return (Guid.Empty, string.Empty); } /// /// 异步加载最后打开的产品(包装同步实现)。 /// /// 包含 (id, name) 的任务。 public Task<(Guid id, string name)> LoadLastProductAsync() { // 可以使用 Task.FromResult,因为内部是同步且快速的文件检测/读取 return Task.Run(() => LoadLastProduct()); } /// /// 将指定产品设置为当前产品,并更新系统配置中的 LastOpenedProductId,同时触发 OnProductChanged 事件。 /// 仅当内存中存在该产品时生效。 /// /// 要设置为当前的产品 ID。 public void SetCurrentProduct(Guid id) { lock (_sync) { if (_products.ContainsKey(id)) { _currentProduct = id; _products[id].IsLoad = true; //将其他的产品设置为未加载状态 foreach (var kvp in _products) { if (kvp.Key != id) { kvp.Value.IsLoad = false; } } var sysConfig = _configService.GetSystemConfiguration(); sysConfig.LastOpenedProductId = id; _configService.SaveSystemConfiguration(sysConfig); OnCurrentProductChanged(_products[id]); } } } /// /// 获取当前产品模型(若未设置则返回 null)。 /// /// 当前产品或 null。 public ProductModel GetCurrentProduct() { lock (_sync) { if (_currentProduct == Guid.Empty) return null; _products.TryGetValue(_currentProduct, out var p); return p; } } /// /// 复制已有产品并为副本分配新的 ID 与名称,同时保存副本并返回新副本的 ID。 /// /// 源产品 ID。 /// 新产品的名称。 /// 新产品的 ID,失败时返回 Guid.Empty。 public Guid CopyProduct(Guid id, string newName) { var p = GetProduct(id); if (p == null) return Guid.Empty; var clone = p.Clone(); clone.ID = Guid.NewGuid(); clone.Name = newName; clone.DateTime = DateTime.Now; CreateProduct(clone); return clone.ID; } /// /// 异步复制产品。 /// /// 源产品 ID。 /// 新名称。 /// 包含新产品 ID 的任务。 public Task CopyProductAsync(Guid id, string newName) { return Task.Run(() => CopyProduct(id, newName)); } /// /// 永久删除产品:从内存中移除并递归删除其在磁盘上的文件夹及所有内容。 /// /// 要删除的产品 ID。 public void DeleteProduct(Guid id) { //获取产品 var p = GetProduct(id); //如果产品不存在,直接返回 if (p == null) return; //获取产品文件夹路径,产品路径为:ProductsRootPath//p.Name string productDirPath = Path.Combine(ProductsRootPath, p.Name); //移除产品 RemoveProduct(id); //删除产品文件夹及其内容 DeleteDirectoryRecursively(productDirPath); } /// /// 异步删除产品(包装同步实现)。 /// /// 产品 ID。 /// 表示异步删除操作的任务。 public Task DeleteProductAsync(Guid id) { return Task.Run(() => DeleteProduct(id)); } /// /// 对指定产品进行重命名:更新内存模型并在磁盘上重命名对应文件夹(若存在),然后保存产品清单与产品配置。 /// /// 产品 ID。 /// 新的产品名称。 public void RenameProduct(Guid id, string newName) { // 获取产品 var p = GetProduct(id); if (p == null) return; // 获取旧产品文件夹路径,产品路径为:ProductsRootPath//p.Name string oldProductDirPath = Path.Combine(ProductsRootPath, p.Name); // 更新产品名称 p.Name = newName; // 获取新产品文件夹路径 string newProductDirPath = Path.Combine(ProductsRootPath, newName); // 重命名文件夹 if (Directory.Exists(oldProductDirPath)) { Directory.Move(oldProductDirPath, newProductDirPath); } // 保存产品清单 SaveProductList(); //对产品进行保存 SaveProduct(id); } /// /// 异步重命名产品(包装同步实现)。 /// /// 产品 ID。 /// 新的名称。 /// 表示异步操作的任务。 public Task RenameProductAsync(Guid id, string newName) { return Task.Run(() => RenameProduct(id, newName)); } /// /// 更新内存中产品对象并将其保存到磁盘(若存在)。 /// /// 要更新的产品模型(不能为空)。 public void UpdateProduct(ProductModel product) { if (product == null) throw new ArgumentNullException(nameof(product)); lock (_sync) { if (_products.ContainsKey(product.ID)) { _products[product.ID] = product; } } // 更新后自动保存到磁盘 SaveProduct(product.ID); } /// /// 异步更新产品(包装同步实现)。 /// /// 产品模型。 /// 表示异步操作的任务。 public Task UpdateProductAsync(ProductModel product) { return Task.Run(() => UpdateProduct(product)); } /// /// 根据指定的模板名称创建产品并保存。模板文件位于 。 /// /// 模板名称(对应子文件夹与 cfg 文件名)。 /// 新产品名称。 /// 创建并返回的新产品模型;若模板不存在则返回 null。 public ProductModel CreateProductByTemplateName(string templateName, string productName) { // 产品模板路径为:ProductTemplatePath//templateName//templateName.cfg string templateFilePath = Path.Combine(ProductTemplatePath, templateName, templateName + ".cfg"); var templateProduct = LoadProduct(templateFilePath); if (templateProduct == null) return null; var newProduct = templateProduct.Clone(); newProduct.Name = productName; newProduct.ID= Guid.NewGuid(); CreateProduct(newProduct); return GetProduct(newProduct.ID); } /// /// 异步根据模板创建产品。 /// /// 模板名。 /// 产品名。 /// 包含新产品模型的任务。 public Task CreateProductByTemplateNameAsync(string templateName, string productName) { return Task.Run(() => CreateProductByTemplateName(templateName, productName)); } /// /// 在所有产品中增加一个相机流程(当系统新增相机时调用),并保存每个产品的配置。 /// /// 相机 ID。 /// 相机名称。 public void AddCameraToProduct(Guid cameraId, string cameraName) { //获取所有产品 var products= GetAllProducts(); if (products == null) return; //遍历所有产品,增加相机流程 foreach (var item in products) { item.AddCameraProcedure(new CameraProcedure(cameraId, cameraName)); //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); } } /// /// 异步在所有产品中增加相机流程。 /// /// 相机 ID。 /// 相机名。 /// 表示异步操作的任务。 public Task AddCameraToProductAsync(Guid cameraId, string cameraName) { return Task.Run(() => AddCameraToProduct(cameraId, cameraName)); } /// /// 在所有产品中移除指定相机对应的流程,并保存产品文件。 /// /// 要移除的相机 ID。 public void RemoveCameraFromProduct(Guid cameraId) { var products= GetAllProducts(); if (products == null) return; //遍历所有产品,删除相机流程 foreach (var item in products) { item.RemoveCameraProcedure(cameraId); //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); } } /// /// 异步在所有产品中移除相机流程。 /// /// 相机 ID。 /// 任务。 public Task RemoveCameraFromProductAsync(Guid cameraId) { return Task.Run(() => RemoveCameraFromProduct(cameraId)); } /// /// 更新所有产品中指定相机的名称,并在磁盘上重命名对应的相机文件夹(若存在)。 /// /// 相机 ID。 /// 新相机名称。 public void UpdateCameraNameInProduct(Guid cameraId, string newCameraName) { var products= GetAllProducts(); if (products == null) return; //遍历所有产品,修改相机名称 foreach (var item in products) { //旧名称 string oldCameraName = string.Empty; var cameraProcedure = item.CameraProcedures.FirstOrDefault(cp => cp.ID == cameraId); if (cameraProcedure != null) { oldCameraName = cameraProcedure.Camera; cameraProcedure.Camera = newCameraName; } //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); if (!string.IsNullOrEmpty(oldCameraName)) { //改之前相机流程文件夹路径 string cameraDirPath = Path.Combine(ProductsRootPath, item.Name, oldCameraName); //如果相机名称发生变化,重命名相机流程文件夹 if (oldCameraName != newCameraName) { string newCameraDirPath = Path.Combine(ProductsRootPath, item.Name, newCameraName); if (Directory.Exists(cameraDirPath)) { Directory.Move(cameraDirPath, newCameraDirPath); } } } } } /// /// 异步更新所有产品中的相机名称。 /// /// 相机 ID。 /// 新名称。 /// 任务。 public Task UpdateCameraNameInProductAsync(Guid cameraId, string newCameraName) { return Task.Run(() => UpdateCameraNameInProduct(cameraId, newCameraName)); } /// /// 在所有产品中增加机器人点位表条目并保存对应产品文件(当系统新增机器人或点位时调用)。 /// /// 机器人 ID。 /// 点位名称。 public void AddRobotPointToProduct(Guid robotId, string robotPointName) { //获取所有产品 var products = GetAllProducts(); if (products == null) return; //遍历所有产品,增加机器人点位表 foreach (var item in products) { item.RobotPoint.AddRobot(robotId, robotPointName); //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); } } /// /// 异步为所有产品增加机器人点位。 /// /// 机器人 ID。 /// 点位名。 /// 任务。 public Task AddRobotPointToProductAsync(Guid robotId, string robotPointName) { return Task.Run(() => AddRobotPointToProduct(robotId, robotPointName)); } /// /// 在所有产品中移除指定机器人相关的点位配置并保存产品文件。 /// /// 机器人 ID。 public void RemoveRobotPointFromProduct(Guid robotId) { var products = GetAllProducts(); if (products == null) return; //遍历所有产品,删除机器人点位表 foreach (var item in products) { item.RobotPoint.RemoveRobot(robotId); //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); } } /// /// 异步在所有产品中移除机器人点位。 /// /// 机器人 ID。 /// 任务。 public Task RemoveRobotPointFromProductAsync(Guid robotId) { return Task.Run(() => RemoveRobotPointFromProduct(robotId)); } /// /// 更新所有产品中指定机器人点位的名称并保存产品配置。 /// /// 机器人 ID。 /// 新的点位名称。 public void UpdateRobotPointNameInProduct(Guid robotId, string newRobotPointName) { var products = GetAllProducts(); if (products == null) return; //遍历所有产品,修改机器人点位名称 foreach (var item in products) { var robotPointStore = item.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robotId); if (robotPointStore != null) { robotPointStore.Name = newRobotPointName; } //单个产品的配置文件路径 string productFilePath = Path.Combine(ProductsRootPath, item.Name, item.Name + ".cfg"); //保存产品 FileHelper.WriteJsonFile(item, productFilePath); } } /// /// 异步更新机器人点位名称。 /// /// 机器人 ID。 /// 新名称。 /// 任务。 public Task UpdateRobotPointNameInProductAsync(Guid robotId, string newRobotPointName) { return Task.Run(() => UpdateRobotPointNameInProduct(robotId, newRobotPointName)); } /// /// 加载指定产品的某个相机流程的视觉工具(ToolBlock)。 /// 若视觉工具文件不存在则尝试从模板加载并保存到目标路径;若模板也不存在则抛出 。 /// /// 产品 ID。 /// 相机 ID。 /// 流程名称。 public void LoadProcedureVisionTools(Guid productid, Guid cameraid, string prcname) { //获取产品 var product= GetProduct(productid); if (product == null) return; //获取相机流程 var cameraProcedure = product.CameraProcedures.FirstOrDefault(cp => cp.ID == cameraid); if (cameraProcedure == null) return; //获取指定名称的流程 var procedure = cameraProcedure.ProcedureModels.FirstOrDefault(pm => pm.Name == prcname); if (procedure == null) return; //获取流程视觉工具路径 string vpppath= Path.Combine(ProductsRootPath, product.Name, cameraProcedure.Camera, prcname + ".vpp"); if (File.Exists(vpppath)) { procedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(vpppath); } else { //如果不存在,则加载一个模板工具 if (File.Exists(TemplateToolBlock)) { procedure.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe(TemplateToolBlock); //保存到指定路径 VisionProFileHelper.SaveObjectToFileSafe(procedure.ToolBlock, vpppath); } else { throw new FileNotFoundException(Lang.模板工具文件不存在无法创建新的视觉工具,TemplateToolBlock); } } } /// /// 异步加载指定产品流程的视觉工具,返回是否成功。 /// /// 产品 ID。 /// 相机 ID。 /// 流程名称。 /// 成功返回 true,发生异常返回 false。 public Task LoadProcedureVisionToolsAsync(Guid productid, Guid cameraid, string prcname) { return Task.Run(() => { try { LoadProcedureVisionTools(productid, cameraid, prcname); return true; } catch { return false; } }); } /// /// 获取当前产品的指定视觉流程ID的视觉流程对象 /// /// /// public ProcedureModel GetCurrentProductProcedureModelById(Guid procedureId) { var currentProduct = GetCurrentProduct(); if (currentProduct == null) return null; foreach (var cameraProcedure in currentProduct.CameraProcedures) { var procedure = cameraProcedure.ProcedureModels.FirstOrDefault(pm => pm.Id == procedureId); if (procedure != null) { return procedure; } } return null; } /// /// 递归删除指定目录及其所有子目录和文件。 /// 注意:此操作会永久删除磁盘上的文件,请谨慎调用。 /// /// 要删除的目录路径。 private void DeleteDirectoryRecursively(string dirPath) { if (Directory.Exists(dirPath)) { var dirInfo = new DirectoryInfo(dirPath); // 删除所有文件 foreach (var file in dirInfo.GetFiles()) { file.Delete(); } // 递归删除所有子目录 foreach (var dir in dirInfo.GetDirectories()) { DeleteDirectoryRecursively(dir.FullName); } // 删除当前目录 dirInfo.Delete(); } } /// /// 触发当前产品切换事件的内部方法(线程安全地调用事件)。 /// /// 新的当前产品。 private void OnCurrentProductChanged(ProductModel product) { OnProductChanged?.Invoke(product); } /// /// 释放资源,清空内存中的产品集合并抑制终结化。 /// public void Dispose() { RemoveAllProducts(); GC.SuppressFinalize(this); } } }