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; namespace TeamAAS_VP.Services { 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"; /// /// 产品文件夹路径 /// public string ProductsRootPath { get; set; } /// /// 产品切换事件 /// public event Action OnProductChanged; /// /// 构造函数 /// /// public ProductService(IConfigService configService, IFeederService feederService) { _configService = configService; _feederService = feederService; ProductsRootPath = DefaultProductsSubPath; } 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()); } /// /// 获取本地所有产品列表 /// /// 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; } /// /// 保存产品清单 /// 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()); } 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)); } public ProductModel GetProduct(Guid id) { lock (_sync) { _products.TryGetValue(id, out var p); return p; } } 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); } public bool TryGetProduct(Guid id, out ProductModel product) { lock (_sync) { return _products.TryGetValue(id, out 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)); } public bool ContainsProduct(Guid id) { lock (_sync) { return _products.ContainsKey(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)); } public bool RemoveProduct(Guid id) { bool result; lock (_sync) { result= _products.Remove(id); } // 删除后可选择删除对应的文件(视需求而定) SaveProductList(); return result; } public Task RemoveProductAsync(Guid id) { var r = RemoveProduct(id); return Task.FromResult(r); } public void RemoveAllProducts() { lock (_sync) { _products.Clear(); } } // 仍保留按路径保存的版本(向后兼容) public void SaveProduct(Guid id, string filePath) { var p = GetProduct(id); if (p == null) return; SaveProduct(p, filePath); } public Task SaveProductAsync(Guid id, string filePath) { return Task.Run(() => SaveProduct(id, filePath)); } // 新增:不需要传入路径的保存,使用约定目录和文件名 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); } 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) { CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath); } else { //判断路径下是否存在toolblock if (File.Exists(prcPath)) { item1.ToolBlock = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock; } else { if (File.Exists(TemplateToolBlock)) { //保存模板 item1.ToolBlock = CogSerializer.LoadObjectFromFile(TemplateToolBlock) as CogToolBlock; CogSerializer.SaveObjectToFile(item1.ToolBlock, prcPath); } } } } } } public Task SaveProductAsync(Guid id) { return Task.Run(() => SaveProduct(id)); } public ProductModel LoadProduct(string filePath) { if (!File.Exists(filePath)) return null; var prd = FileHelper.ReadJsonFile(filePath); return prd; } 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 = CogSerializer.LoadObjectFromFile(prcPath) as CogToolBlock; } } return p; } public Task LoadProductAsync(Guid id) { return Task.Run(() => LoadProduct(id)); } 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); } public Task<(Guid id, string name)> LoadLastProductAsync() { // 可以使用 Task.FromResult,因为内部是同步且快速的文件检测/读取 return Task.Run(() => LoadLastProduct()); } 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]); } } } public ProductModel GetCurrentProduct() { lock (_sync) { if (_currentProduct == Guid.Empty) return null; _products.TryGetValue(_currentProduct, out var p); return p; } } 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; } public Task CopyProductAsync(Guid id, string newName) { return Task.Run(() => CopyProduct(id, newName)); } /// /// 永久删除产品 /// /// 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); } /// /// 永久删除产品 /// /// public Task DeleteProductAsync(Guid id) { return Task.Run(() => DeleteProduct(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); } /// /// 对指定产品进行重命名 /// /// /// /// 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)); } /// /// 根据指定的模板名称创建产品 /// /// /// /// 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)); } /// /// 增加相机时,需要对产品的相机流程进行增加 /// /// /// 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); } } /// /// 增加相机时,需要对产品的相机流程进行增加 /// /// /// /// public Task AddCameraToProductAsync(Guid cameraId, string cameraName) { return Task.Run(() => AddCameraToProduct(cameraId, cameraName)); } /// /// 删除相机时,需要对产品的相机流程进行删除 /// /// 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); } } /// /// 删除相机时,需要对产品的相机流程进行删除 /// /// /// public Task RemoveCameraFromProductAsync(Guid cameraId) { return Task.Run(() => RemoveCameraFromProduct(cameraId)); } /// /// 修改相机名称时,需要对产品的相机流程进行修改 /// /// /// 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); } } } } } /// /// 修改相机名称时,需要对产品的相机流程进行修改 /// /// /// /// public Task UpdateCameraNameInProductAsync(Guid cameraId, string newCameraName) { return Task.Run(() => UpdateCameraNameInProduct(cameraId, newCameraName)); } /// /// 增加机器人时,需要对产品的机器人点位进行增加 /// /// /// 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); } } /// /// 增加机器人时,需要对产品的机器人点位进行增加 /// /// /// /// public Task AddRobotPointToProductAsync(Guid robotId, string robotPointName) { return Task.Run(() => AddRobotPointToProduct(robotId, robotPointName)); } /// /// 删除机器人时,需要对产品的机器人点位进行删除 /// /// 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); } } /// /// 删除机器人时,需要对产品的机器人点位进行删除 /// /// /// public Task RemoveRobotPointFromProductAsync(Guid robotId) { return Task.Run(() => RemoveRobotPointFromProduct(robotId)); } /// /// 修改机器人名称时,需要对产品的机器人点位进行修改 /// /// /// 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); } } /// /// 修改机器人名称时,需要对产品的机器人点位进行修改 /// /// /// /// public Task UpdateRobotPointNameInProductAsync(Guid robotId, string newRobotPointName) { return Task.Run(() => UpdateRobotPointNameInProduct(robotId, newRobotPointName)); } /// /// 加载指定产品流程的视觉工具 /// /// /// /// 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 = CogSerializer.LoadObjectFromFile(vpppath) as CogToolBlock; } else { //如果不存在,则加载一个模板工具 if (File.Exists(TemplateToolBlock)) { procedure.ToolBlock = CogSerializer.LoadObjectFromFile(TemplateToolBlock) as CogToolBlock; //保存到指定路径 CogSerializer.SaveObjectToFile(procedure.ToolBlock, vpppath); } else { throw new FileNotFoundException("模板工具文件不存在,无法创建新的视觉工具。", TemplateToolBlock); } } } /// /// 加载指定产品流程的视觉工具 /// /// /// /// /// public Task LoadProcedureVisionToolsAsync(Guid productid, Guid cameraid, string prcname) { return Task.Run(() => { try { LoadProcedureVisionTools(productid, cameraid, prcname); return true; } catch { return false; } }); } /// /// 移除指定文件夹路径下的所有文件和文件夹,及其本身,子文件夹递归删除 /// /// 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); } } }