using Abp.Auditing; using Abp.Authorization; using Abp.Collections.Extensions; using Abp.Domain.Entities; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.EntityFrameworkCore.Repositories; using Microsoft.AspNetCore.Mvc; using MongoDB.Driver.Linq; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Text; using System.Threading.Tasks; using ToolLibrary.LogHelper; using YunDa.ISAS.Application.Core; using YunDa.ISAS.Application.Core.Session; using YunDa.ISAS.Application.Core.SwaggerHelper; using YunDa.ISAS.DataTransferObject; using YunDa.ISAS.DataTransferObject.CommonDto; using YunDa.ISAS.DataTransferObject.DataMonitoring.TelemeteringConfigurationDto; using YunDa.ISAS.Entities.DataMonitoring; using YunDa.ISAS.Entities.GeneralInformation; using YunDa.ISAS.Redis.Repositories; using YunDa.ISMS.BASE.Entities.Models; using YunDa.SOMS.DataTransferObject.GeneralInformation.ProtectionDeviceInfoDto; using YunDa.SOMS.DataTransferObject.GeneralInformation.ProtectionDeviceInfoDto.HistoryData; using YunDa.SOMS.DataTransferObject.GeneralInformation.ProtectionDeviceInfoDto.SearchCondition; using YunDa.SOMS.DataTransferObject.GeneralInformation.ProtectionSettingDto; using YunDa.SOMS.DataTransferObject.MainStationMaintenanceInfo.OperationReport; using YunDa.SOMS.Entities.GeneralInformation; using static NetMQ.NetMQSelector; namespace YunDa.ISAS.Application.GeneralInformation { /// /// 保护装置履历信息管理类 /// public class ProtectionDeviceAppService : ISASAppServiceBase,IProtectionDeviceAppService { private readonly IRepository _equipmentInfoRepository; private readonly IRepository _equipmentTypeRepository; private readonly IRepository _manufacturerInfoRepository; private readonly IRepository _transformerSubstationRepository; private readonly IRepository _protectionDeviceInfoRepository; private readonly IRepository _protectionDeviceHistoryRepository; private readonly IRepository _secondaryCircuitProtectionDeviceRepository; private readonly IRepository _boardCardInfoRepository; private readonly IRepository _boardCardHistoryRepository; private readonly IRepository _imProtectDeviceRepository; private readonly IRepository _imGateWayRepository; private readonly IRepository _imPuCtgyRepository; private readonly IRepository _imEventTypeRepository; private readonly IRepository _telemeteringConfigurationRepository; private readonly IRepository _telesignalisationConfigurationRepository; private readonly IRepository _protectionDeviceGatewayRepository; private readonly IRepository _protectionDeviceTypeyRepository; private readonly IRepository _imDeviceDzRepository; private readonly IRedisRepository _imDeviceDzRedis; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IRedisRepository _bcodeAndNTP; public ProtectionDeviceAppService( IRepository protectionDeviceInfoRepository, IUnitOfWorkManager unitOfWorkManager, IRepository imProtectDeviceRepository, IRepository equipmentInfoRepository, IRepository secondaryCircuitProtectionDeviceRepository , IRepository telemeteringConfigurationRepository, IRepository telesignalisationConfigurationRepository, IRepository protectionDeviceTypeyRepository, IRepository imPuCtgyRepository, IRepository protectionDeviceGatewayRepository, IRepository imGateWayRepository, IRepository boardCardInfoRepository, IRepository boardCardHistoryRepository, IRepository protectionDeviceHistoryRepository, IRepository equipmentTypeRepository, IRepository manufacturerInfoRepository, IRepository transformerSubstationRepository, IRepository imDeviceDzRepository, IRepository imEventTypeRepository, IRedisRepository bcodeAndNTP, ISessionAppService sessionAppService ) : base(sessionAppService) { _unitOfWorkManager = unitOfWorkManager; _equipmentInfoRepository = equipmentInfoRepository; _imProtectDeviceRepository = imProtectDeviceRepository; _protectionDeviceInfoRepository = protectionDeviceInfoRepository; _protectionDeviceHistoryRepository = protectionDeviceHistoryRepository; _boardCardInfoRepository = boardCardInfoRepository; _boardCardHistoryRepository = boardCardHistoryRepository; _secondaryCircuitProtectionDeviceRepository = secondaryCircuitProtectionDeviceRepository; _imGateWayRepository = imGateWayRepository; _protectionDeviceGatewayRepository = protectionDeviceGatewayRepository; _imPuCtgyRepository = imPuCtgyRepository; _protectionDeviceTypeyRepository = protectionDeviceTypeyRepository; _equipmentTypeRepository = equipmentTypeRepository; _manufacturerInfoRepository = manufacturerInfoRepository; _transformerSubstationRepository = transformerSubstationRepository; _imDeviceDzRepository = imDeviceDzRepository; _imEventTypeRepository = imEventTypeRepository; _telemeteringConfigurationRepository = telemeteringConfigurationRepository; _telesignalisationConfigurationRepository = telesignalisationConfigurationRepository; _bcodeAndNTP = bcodeAndNTP; } public async Task> CreateOrUpdateAsync(EditProtectionDeviceInfoInput input) { RequestResult rst = new RequestResult(); try { if (input.Id.HasValue) { InsertUpdateRecord(input); } else { var entity = new ProtectionDeviceInfo(); entity.CreatorUserId = base.GetCurrentUser().Id; entity.CreationTime = DateTime.Now; // 逐字段赋值 entity.SeqNo = input.SeqNo; entity.Name = input.Name; entity.Specification = input.Specification; entity.DeviceAddress = input.DeviceAddress; entity.BaselineBoardVersion = input.BaselineBoardVersion; entity.HardwareVersion = input.HardwareVersion; entity.IsActive = input.IsActive; entity.EquipmentInfo = new EquipmentInfo(); entity.EquipmentInfo.ManufacturerInfoId = input.ManufacturerInfoId; entity.EquipmentInfo.SeqNo = input.SeqNo; entity.EquipmentInfo.Name = input.Name; entity.EquipmentInfo.InstallationDate = input.InstallationDate; entity.EquipmentInfo.ProductionDate = input.ProductionDate; entity.EquipmentInfo.FactorySerialNumber = input.FactorySerialNumber; entity.EquipmentInfo.VerificationPerson = input.VerificationPerson; entity.EquipmentInfo.VerificationDate = input.VerificationDate; entity.EquipmentInfo.VerificationRecords = input.VerificationRecords; entity.EquipmentInfo.ManufacturerInfoId = input.ManufacturerInfoId; entity.EquipmentInfo.MaintenanceRecord = input.MaintenanceRecord; var equipmentInfoId =await _equipmentInfoRepository.InsertAndGetIdAsync(entity.EquipmentInfo); entity.EquipmentInfoId = equipmentInfoId; var protectionDeviceInfo = await _protectionDeviceInfoRepository.InsertAsync(entity); // 记录历史数据 var protectionDeviceHistory = new ProtectionDeviceHistory { Name = input.Name, ProtectionDeviceInfoId = protectionDeviceInfo.Id, RecodeDate = DateTime.Now, ContentJson = "", // 原始数据 ContentNewJson = JsonConvert.SerializeObject(entity), // 新数据 EventDescription = "设备台账建立", EventRecordType = EventRecordTypeEnum.Device, IsSend = false // 默认未发送 }; // 插入历史记录 _protectionDeviceHistoryRepository.Insert(protectionDeviceHistory); } rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } private void InsertUpdateRecord(EditProtectionDeviceInfoInput input) { if (input.Id.HasValue) { var entity = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo) .FirstOrDefault(t => t.Id == input.Id); if (entity != null) { // 记录更新前的数据 var originalContent = JsonConvert.SerializeObject(entity); // 初始化事件描述 StringBuilder eventDescription = new StringBuilder("设备信息更新: "); // 比较并更新字段 if (entity.SeqNo != input.SeqNo) { eventDescription.Append("顺序号更新, "); entity.SeqNo = input.SeqNo; } if (entity.Name != input.Name) { eventDescription.Append($"设备名称更新:'{input.Name}', "); entity.Name = input.Name; } if (entity.Specification != input.Specification) { eventDescription.Append($"规格更新:'{input.Specification}', "); entity.Specification = input.Specification; } if (entity.DeviceAddress != input.DeviceAddress) { eventDescription.Append($"设备地址更新:'{input.DeviceAddress}', "); entity.DeviceAddress = input.DeviceAddress; } if (entity.BaselineBoardVersion != input.BaselineBoardVersion) { eventDescription.Append($"基板版本更新:'{input.BaselineBoardVersion}', "); entity.BaselineBoardVersion = input.BaselineBoardVersion; } if (entity.HardwareVersion != input.HardwareVersion) { eventDescription.Append($"硬件版本更新:'{input.HardwareVersion}', "); entity.HardwareVersion = input.HardwareVersion; } if (entity.IsActive != input.IsActive) { eventDescription.Append($"启用状态更新:'{input.IsActive}', "); entity.IsActive = input.IsActive; } // 设备信息赋值 if (entity.EquipmentInfo != null) { if (entity.EquipmentInfo.ManufacturerInfoId != input.ManufacturerInfoId) { eventDescription.Append($"制造商ID更新:'{input.ManufacturerInfoId}', "); entity.EquipmentInfo.ManufacturerInfoId = input.ManufacturerInfoId; } if (entity.EquipmentInfo.Name != input.Name) { eventDescription.Append($"设备名称更新:'{input.Name}', "); entity.EquipmentInfo.Name = input.Name; } if (entity.EquipmentInfo.InstallationDate != input.InstallationDate) { eventDescription.Append($"安装日期更新:'{input.InstallationDate}', "); entity.EquipmentInfo.InstallationDate = input.InstallationDate; } if (entity.EquipmentInfo.ProductionDate != input.ProductionDate) { eventDescription.Append($"生产日期更新:'{input.ProductionDate}', "); entity.EquipmentInfo.ProductionDate = input.ProductionDate; } if (entity.EquipmentInfo.FactorySerialNumber != input.FactorySerialNumber) { eventDescription.Append($"出厂序列号更新:'{input.FactorySerialNumber}', "); entity.EquipmentInfo.FactorySerialNumber = input.FactorySerialNumber; } if (entity.EquipmentInfo.VerificationPerson != input.VerificationPerson) { eventDescription.Append($"验证人更新:'{input.VerificationPerson}', "); entity.EquipmentInfo.VerificationPerson = input.VerificationPerson; } if (entity.EquipmentInfo.VerificationDate != input.VerificationDate) { eventDescription.Append($"验证日期更新:'{input.VerificationDate}', "); entity.EquipmentInfo.VerificationDate = input.VerificationDate; } if (entity.EquipmentInfo.VerificationRecords != input.VerificationRecords) { eventDescription.Append($"验证记录更新:'{input.VerificationRecords}', "); entity.EquipmentInfo.VerificationRecords = input.VerificationRecords; } if (entity.EquipmentInfo.MaintenanceRecord != input.MaintenanceRecord) { eventDescription.Append($"维修记录更新:'{input.MaintenanceRecord}', "); entity.EquipmentInfo.MaintenanceRecord = input.MaintenanceRecord; } } // 检查是否有变化并记录历史 var updatedContent = JsonConvert.SerializeObject(entity); // 如果数据发生了变化,则记录历史 if (originalContent != updatedContent) { var history = new ProtectionDeviceHistory { ProtectionDeviceInfoId = entity.Id, RecodeDate = DateTime.Now, ContentJson = originalContent, // 记录更新前的内容 ContentNewJson = updatedContent, // 记录更新后的内容 EventDescription = eventDescription.ToString().TrimEnd(','), EventRecordType = EventRecordTypeEnum.Device, // 假设更新:事件类型 Remark = "自动记录设备信息更新", IsSend = false // 如果不需要立即发送给主站 }; // 保存历史记录 _protectionDeviceHistoryRepository.Insert(history); } } } } /// /// 扫码枪输入设备信息 /// /// /// [ShowApi] [AbpAllowAnonymous] [HttpPost] public RequestEasyResult ScanDeviceQRCode(EditProtectionQrCodeDeviceInfoInput input) { RequestEasyResult rst = new RequestEasyResult(); try { var repo = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo,t=>t.ProtectionDeviceType).ToList(); var protectionDevice = repo.FirstOrDefault(t => t.Name.Contains(input.Name)); if (protectionDevice != null) { //当出厂编号不一致进行履历更新 if (protectionDevice.EquipmentInfo.FactorySerialNumber != input.SerialNumber || protectionDevice.EquipmentInfo.MaintenanceRecord!= input.MaintenanceRecord || protectionDevice.EquipmentInfo.VerificationRecords != input.VerificationRecords || protectionDevice.EquipmentInfo.VerificationDate != input.VerificationDate || protectionDevice.EquipmentInfo.VerificationPerson!= input.VerificationPerson || protectionDevice.EquipmentInfo.ProductionDate != input.ProductionDate ) { var json = JsonConvert.SerializeObject(protectionDevice); var protectionDeviceHistory = _protectionDeviceHistoryRepository.GetAll().Where(t => t.ProtectionDeviceInfoId == protectionDevice.Id).ToList(); var deviceHistory = new ProtectionDeviceHistory { ContentJson = json, CreationTime = DateTime.Now, CreatorUserId = base.GetCurrentUser().Id, Name = protectionDevice.Name, RecodeDate = DateTime.Now, ProtectionDeviceInfoId = protectionDevice.Id, SeqNo = protectionDeviceHistory.Count > 0 ? protectionDeviceHistory.Max(t => t.SeqNo) : 1 }; protectionDevice.Specification = input.Specification; protectionDevice.EquipmentInfo.FactorySerialNumber = input.SerialNumber; protectionDevice.EquipmentInfo.ProductionDate = input.ProductionDate; protectionDevice.EquipmentInfo.VerificationDate = input.VerificationDate; protectionDevice.EquipmentInfo.VerificationPerson = input.VerificationPerson; protectionDevice.EquipmentInfo.VerificationRecords = input.VerificationRecords; var newjson = JsonConvert.SerializeObject(protectionDevice); deviceHistory.ContentNewJson = newjson; // 记录变更内容 var eventDescription = new StringBuilder(); // 通过判定每个字段是否发生变化,动态生成描述 if (protectionDevice.EquipmentInfo.FactorySerialNumber != input.SerialNumber) { eventDescription.AppendLine($"更换了设备的厂商序列号: {protectionDevice.EquipmentInfo.FactorySerialNumber} -> {input.SerialNumber}"); } if (protectionDevice.EquipmentInfo.MaintenanceRecord != input.MaintenanceRecord) { eventDescription.AppendLine($"更新了设备的维修记录: {protectionDevice.EquipmentInfo.MaintenanceRecord} -> {input.MaintenanceRecord}"); } if (protectionDevice.EquipmentInfo.VerificationRecords != input.VerificationRecords) { eventDescription.AppendLine($"更改了设备的检验记录: {protectionDevice.EquipmentInfo.VerificationRecords} -> {input.VerificationRecords}"); } if (protectionDevice.EquipmentInfo.VerificationDate != input.VerificationDate) { eventDescription.AppendLine($"修改了设备的检验日期: {protectionDevice.EquipmentInfo.VerificationDate} -> {input.VerificationDate}"); } if (protectionDevice.EquipmentInfo.VerificationPerson != input.VerificationPerson) { eventDescription.AppendLine($"更新了设备的检验人员: {protectionDevice.EquipmentInfo.VerificationPerson} -> {input.VerificationPerson}"); } if (protectionDevice.EquipmentInfo.ProductionDate != input.ProductionDate) { eventDescription.AppendLine($"更改了设备的生产日期: {protectionDevice.EquipmentInfo.ProductionDate} -> {input.ProductionDate}"); } deviceHistory.Name = protectionDevice.Name; deviceHistory.EventDescription = eventDescription.ToString(); deviceHistory.EventRecordType = EventRecordTypeEnum.Device; deviceHistory.Remark = input.Remark; _protectionDeviceHistoryRepository.Insert(deviceHistory); } rst.Flag = true; } else { rst.Message = "未找到对应装置"; } } catch (Exception ex) { rst.Message = ex.Message; } return rst; } public async Task DeleteByIdAsync(Guid id) { RequestEasyResult rst = new RequestEasyResult(); return rst; } public async Task DeleteByIdsAsync(List ids) { RequestEasyResult rst = new RequestEasyResult(); return rst; } /// /// 查询保护装置信息 /// /// /// [ShowApi] [AbpAllowAnonymous] [DisableAuditing] [HttpPost] public RequestPageResult FindDatas(PageSearchCondition searchCondition) { RequestPageResult rst = new RequestPageResult(); try { var repo = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo) .WhereIf(searchCondition.SearchCondition.IsOnlyActive.HasValue, t => t.IsActive) .WhereIf(searchCondition.SearchCondition.Id.HasValue, t => t.Id == searchCondition.SearchCondition.Id.Value) .WhereIf(searchCondition.SearchCondition.TransformerSubstationId.HasValue, t => t.Id == searchCondition.SearchCondition.TransformerSubstationId.Value).ToList(); List datas = default; if (!string.IsNullOrWhiteSpace( searchCondition.SearchCondition.Name)) { repo = repo.Where(t => t.Name.Contains(searchCondition.SearchCondition.Name)).ToList(); } rst.TotalCount = repo.Count(); if (repo.Count()>0) { rst.PageSize = searchCondition.PageSize; rst.PageIndex = searchCondition.PageIndex; if ( searchCondition.PageSize>0) { var dataTemps = repo.Skip((searchCondition.PageIndex-1)* searchCondition.PageSize).Take(searchCondition.PageSize); datas = ObjectMapper.Map>(dataTemps); } else { datas = ObjectMapper.Map>(repo); } } rst.ResultData= datas; rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } /// /// 查询保护装置信息 /// /// /// [ShowApi] [AbpAllowAnonymous] [DisableAuditing] [HttpPost] public RequestPageResult FindDatasByCircuit(PageSearchCondition searchCondition) { RequestPageResult rst = new RequestPageResult(); try { var repo = _secondaryCircuitProtectionDeviceRepository.GetAllIncluding(t => t.ProtectionDevice) .Where(t=>t.SecondaryCircuitId == searchCondition.SearchCondition.SecondaryCircuitId).ToList(); List datas = default; rst.TotalCount = repo.Count(); if (repo.Count() > 0) { rst.PageSize = searchCondition.PageSize; rst.PageIndex = searchCondition.PageIndex; if (searchCondition.PageSize > 0) { var dataTemps = repo.Skip((searchCondition.PageIndex - 1) * searchCondition.PageSize).Take(searchCondition.PageSize); datas = ObjectMapper.Map>(dataTemps.Select(t=>t.ProtectionDevice)); } else { datas = ObjectMapper.Map>(repo); } } rst.ResultData = datas; rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } /// /// 查询保护装置信息 /// /// /// [ShowApi] [AbpAllowAnonymous] [DisableAuditing] [HttpGet] public RequestResult FindDataByEquipmentInfoId(Guid? equipmentInfoId) { RequestResult rst = new RequestResult(); try { var entity = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo,t=>t.EquipmentInfo.ManufacturerInfo) .FirstOrDefault(t => t.EquipmentInfoId == equipmentInfoId); if (entity!=null) { rst.ResultData = ObjectMapper.Map(entity); rst.Flag = true; } } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } /// /// 查询历史保护装置信息 /// /// /// [ShowApi] [AbpAllowAnonymous] [DisableAuditing] [HttpGet] public RequestResult> FindHistoryDataByEquipmentInfoId(Guid? equipmentInfoId) { RequestResult> rst = new RequestResult>(); try { List historys = new List(); var protectionDevice = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo) .FirstOrDefault(t => t.EquipmentInfoId == equipmentInfoId); if (protectionDevice != null) { var entitys = _protectionDeviceHistoryRepository.GetAll() .Where(t => t.ProtectionDeviceInfoId == protectionDevice.Id) .OrderByDescending(t=>t.RecodeDate) ; historys = ObjectMapper.Map>(entitys); rst.Flag = true; rst.ResultData = historys; } } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } public RequestResult GetProtectionDeviceQRcode(Guid id) { RequestResult rst = new RequestResult(); return rst; } /// /// 获取保护装置列表 /// /// /// [HttpGet] [ShowApi] [AbpAllowAnonymous] [DisableAuditing] public RequestResult> FindProtectionDeviceForSelect(Guid stationId) { var rst = new RequestResult> { Flag = false }; try { var datas = _protectionDeviceInfoRepository.GetAllIncluding() .Where(e => e.IsActive) .Where(t=>t.TransformerSubstationId == stationId) .OrderBy(x=>x.SeqNo).ThenBy(x => x.Name); rst.ResultData = datas.Select(item => new SelectModelOutput { Value = item.Id.ToString().ToLower(), Key = item.Id, Text = item.Name }).ToList(); rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "获取保护装置列表", ex); } return rst; } /// /// 只在所内有效-获取变电所装置的ip地址 /// /// [HttpGet] [ShowApi] [AbpAllowAnonymous] [UnitOfWork(false)] public RequestResult> FindProtectionDeviceCommInfo(string stationName) { RequestResult> rst = new RequestResult>(); try { Dictionary porotectionDeviceInfos = default; using (var unitOfWork = _unitOfWorkManager.Begin()) { porotectionDeviceInfos = _protectionDeviceInfoRepository.GetAllIncluding().Where(t=>t.IsActive).ToDictionary(t => t.ISMS_DeviceId); unitOfWork.Complete(); } using (var unitOfWork = _unitOfWorkManager.Begin()) { var devices = _imProtectDeviceRepository.GetAllIncluding(t => t.StatCodeNavigation, t => t.GateWay, t => t.PuctgyCodeNavigation).OrderBy(t => t.DeviceAddr); List datas = new List(); foreach (var item in devices) { if (!porotectionDeviceInfos.ContainsKey(item.Id)) { continue; } var deviceCommInfo = new ProtectionDeviceCommInfoOutput { EquipmentInfoName = porotectionDeviceInfos[item.Id].Name, EquipmentInfoId = porotectionDeviceInfos[item.Id].EquipmentInfoId, ProtectionDeviceId = porotectionDeviceInfos[item.Id].Id, DeviceAddr = item.DeviceAddr, DeviceName = item.DeviceName, GatewayIP1 = item.GateWay.GatewayIp1, GatewayIP2 = item.GateWay.GatewayIp2, GatewayIP3 = "", MaskEth1 = "255.255.255.0", MaskEth2 = "255.255.255.0", MaskEth3 = "255.255.255.0", Gateway = "192.168.61.1", Sntp1 = "192.168.61.99", Sntp2 = "192.168.61.99", IsZY = item.PuctgyCodeNavigation.PuctgyName.Contains("站域") }; datas.Add(deviceCommInfo); } rst.ResultData = datas; unitOfWork.Complete(); } rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } /// /// 根据装置id获取装置通信参数 /// /// [HttpGet] [ShowApi] [AbpAllowAnonymous] [UnitOfWork(false)] public async Task> GetProtectionDeviceCommInfo(Guid deviceId,Guid equipmentId) { RequestResult rst = new RequestResult(); try { ProtectionDeviceInfo protectionDeviceInfo = null; using (var work = _unitOfWorkManager.Begin()) { if (deviceId == default) { protectionDeviceInfo = _protectionDeviceInfoRepository.GetAll().FirstOrDefault(t=>t.EquipmentInfoId == equipmentId); } else { protectionDeviceInfo = _protectionDeviceInfoRepository.Get(deviceId); } await work.CompleteAsync(); } if (protectionDeviceInfo==null) { rst.Message = "传输id错误"; return rst; } ImProtectDevice device = null; using (var work = _unitOfWorkManager.Begin()) { device = _imProtectDeviceRepository.GetAllIncluding(t => t.StatCodeNavigation, t => t.GateWay).FirstOrDefault(t=>t.Id == protectionDeviceInfo.ISMS_DeviceId); await work.CompleteAsync(); } if (device!=null) { var deviceCommInfo = new ProtectionDeviceCommInfoOutput { DeviceAddr = device.DeviceAddr, DeviceName = device.DeviceName, GatewayIP1 = device.GateWay.GatewayIp1, GatewayIP2 = device.GateWay.GatewayIp2, GatewayIP3 = "", MaskEth1 = "", MaskEth2 = "", MaskEth3 = "", Gateway = "t192.168.61.1", Sntp1 = "192.168.61.99", Sntp2 = "192.168.61.99" }; rst.ResultData = deviceCommInfo; } rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "保护装置信息管理服务", ex); } return rst; } /// /// 从综自后台数据库迁移数据到运维数据库中(保护装置数据) /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [UnitOfWork(isTransactional: false)] public RequestEasyResult MigreteDeviceEquipementDataFromISMS() { RequestEasyResult rst = new RequestEasyResult(); try { Dictionary equipments = default; Dictionary imProtectDevices = default; Dictionary porotectionDeviceInfos = default; EquipmentType equipmentType = default; ManufacturerInfo manufacturerInfo = default; TransformerSubstation transformerSubstation = default; using (var unitOfWork = _unitOfWorkManager.Begin()) { transformerSubstation = _transformerSubstationRepository.GetAll().First(); equipments = _equipmentInfoRepository.GetAllIncluding().ToDictionary(t => t.Name); equipmentType = _equipmentTypeRepository.GetAll().FirstOrDefault(t => t.Name.Contains("保护装置")); manufacturerInfo = _manufacturerInfoRepository.GetAll().FirstOrDefault(t => t.ManufacturerName.Contains("运达")); porotectionDeviceInfos = _protectionDeviceInfoRepository.GetAllIncluding().ToDictionary(t=>t.Name); unitOfWork.Complete(); } using (var unitOfWork = _unitOfWorkManager.Begin()) { imProtectDevices = _imProtectDeviceRepository.GetAllIncluding().ToDictionary(t => t.DeviceName); unitOfWork.Complete(); } int count = 0; using (var unitOfWork = _unitOfWorkManager.Begin()) { foreach (var item in imProtectDevices.Keys) { var imProtectDevice = imProtectDevices[item]; Guid equipmentInfoId = default; if (!equipments.ContainsKey(item)) { var equipmentinfo = new EquipmentInfo { SeqNo = imProtectDevice.DeviceAddr, TransformerSubstationId = transformerSubstation.Id, CreationTime = DateTime.Now, CreatorUserId = null, IsActive = true, EquipmentTypeId = equipmentType.Id, ManufacturerInfoId = manufacturerInfo.Id, Name = item }; equipmentInfoId = _equipmentInfoRepository.InsertAndGetId(equipmentinfo); } else { equipmentInfoId = equipments[item].Id; } if (!porotectionDeviceInfos.ContainsKey(item)) { ProtectionDeviceInfo protectionDeviceInfo = new ProtectionDeviceInfo() { CanSwitchDZZone = imProtectDevice.CanSwDzzone == 1 ? true : false, CreationTime = DateTime.Now, CreatorUserId = null, SupportsDualCurrent = imProtectDevice.SupportVersion, BayName = imProtectDevice.BayName, DeviceAddress = imProtectDevice.DeviceAddr, DeviceState = imProtectDevice.DeviceState, EndOfDKJL = imProtectDevice.EndOfDkjl, EquipmentInfoId = equipmentInfoId, IsActive = true, ISMS_DeviceId = imProtectDevice.Id, Name = item, ProtectionDeviceGatewayId = null, ProtectionDeviceTypeId = null, TransformerSubstationId = transformerSubstation.Id, }; _protectionDeviceInfoRepository.Insert(protectionDeviceInfo); // 记录历史数据 var protectionDeviceHistory = new ProtectionDeviceHistory { Name = item, ProtectionDeviceInfoId = protectionDeviceInfo.Id, RecodeDate = DateTime.Now, ContentJson = "", // 原始数据 ContentNewJson = JsonConvert.SerializeObject(protectionDeviceInfo), // 新数据 EventDescription = "设备台账建立", EventRecordType = EventRecordTypeEnum.Device, IsSend = false // 默认未发送 }; // 插入历史记录 _protectionDeviceHistoryRepository.Insert(protectionDeviceHistory); } else { porotectionDeviceInfos[item].DeviceAddress = imProtectDevice.DeviceAddr; } } unitOfWork.Complete(); } rst.Flag = true; rst.Message = $"共完成{count}信息迁移"; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } /// /// 从综自后台数据库迁移数据到运维数据库中(保护装置类型数据) /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [UnitOfWork(isTransactional: false)] public RequestEasyResult MigreteImProtectionDeviceTypeDataFromISMS() { RequestEasyResult rst = new RequestEasyResult(); try { Dictionary protectionDeviceTypes = default; List imPuCtgies = default; using (var unitOfWork = _unitOfWorkManager.Begin()) { protectionDeviceTypes = _protectionDeviceTypeyRepository.GetAll().ToDictionary(t=>t.Name); unitOfWork.Complete(); } using (var unitOfWork = _unitOfWorkManager.Begin()) { imPuCtgies = _imPuCtgyRepository.GetAll().ToList(); unitOfWork.Complete(); } using (var unitOfWork = _unitOfWorkManager.Begin()) { // 提前获取已经存在的保护设备类型名称,避免每次循环都查询 var existingProtectionDeviceTypes = _protectionDeviceTypeyRepository .GetAll() .Where(t => imPuCtgies.Select(im => im.PuctgyName).Contains(t.Name)) .ToDictionary(t => t.Name, t => t); // 创建一个 ProtectionDeviceType 的集合来批量插入 var protectionDeviceTypesToInsert = new List(); foreach (var imPuCtgie in imPuCtgies) { // 检查该类型是否已经存在 if (existingProtectionDeviceTypes.ContainsKey(imPuCtgie.PuctgyName)) { continue; } // 创建新的 ProtectionDeviceType 对象 var protectionDeviceType = new ProtectionDeviceType { CanSwitchDZZone = false, CreationTime = DateTime.Now, CreatorUserId = base.GetCurrentUser().Id, DZZoneCount = imPuCtgie.DzzoneCount, IsCRCC = true, PUCtgyCode = 0, Support12YC = false, AnalogParseMode = imPuCtgie.AnalogParseMode, DZReadOnly = false, EventParseMode = imPuCtgie.EventParseMode, IsActive = true, ManufacturerInfoId = default, Model = imPuCtgie.Model, Name = imPuCtgie.PuctgyName, Generation = imPuCtgie.Generation, }; // 添加到集合中,准备批量插入 protectionDeviceTypesToInsert.Add(protectionDeviceType); } // 批量插入新记录 if (protectionDeviceTypesToInsert.Any()) { _protectionDeviceTypeyRepository.InsertRange(protectionDeviceTypesToInsert); } // 提交事务 unitOfWork.Complete(); } rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } /// /// 从综自后台数据库迁移数据到运维数据库中(保护装置网关数据) /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [UnitOfWork(isTransactional: false)] public RequestEasyResult MigreteImGatewayDataFromISMS() { RequestEasyResult rst = new RequestEasyResult(); try { Dictionary imProtectDevices = default; Dictionary porotectionDeviceInfos = default; //Dictionary imGateWays = default; using (var unitOfWork = _unitOfWorkManager.Begin()) { porotectionDeviceInfos = _protectionDeviceInfoRepository.GetAllIncluding(t=>t.EquipmentInfo).ToDictionary(t => t.Name); unitOfWork.Complete(); } using (var unitOfWork = _unitOfWorkManager.Begin()) { imProtectDevices = _imProtectDeviceRepository.GetAllIncluding(t=>t.GateWay,t=>t.PuctgyCodeNavigation).ToDictionary(t => t.DeviceName); unitOfWork.Complete(); } int count = 0; using (var unitOfWork = _unitOfWorkManager.Begin()) { foreach (var device in imProtectDevices.Keys) { var porotectionDevice = porotectionDeviceInfos[device]; var imProtectDevice = imProtectDevices[device]; if (porotectionDevice != null) { ProtectionDeviceGateway protectionDeviceGateway = new ProtectionDeviceGateway { CreationTime = DateTime.Now, CreatorUserId = base.GetCurrentUser().Id, GatewayIP1 = imProtectDevice.GateWay.GatewayIp1, GatewayIP2 = imProtectDevice.GateWay.GatewayIp2, GatewayPort1 = imProtectDevice.GateWay.GatewayPort1, GatewayPort2 = imProtectDevice.GateWay.GatewayPort2, IsActive = true, Name = imProtectDevice.GateWay.GateWayName, PhysicalAddress = imProtectDevice.GateWay.PhyAddr, Protocol = imProtectDevice.GateWay.Protocol, TransformerSubstationId = porotectionDevice.TransformerSubstationId, ProtectionDeviceInfoId = porotectionDevice.Id }; ProtectionDeviceType protectionDeviceType = new ProtectionDeviceType { CanSwitchDZZone = false, CreationTime = DateTime.Now, CreatorUserId = base.GetCurrentUser().Id, DZZoneCount = imProtectDevice.PuctgyCodeNavigation.DzzoneCount, IsCRCC = true, PUCtgyCode = imProtectDevice.PuctgyCode, Support12YC = false, AnalogParseMode = imProtectDevice.PuctgyCodeNavigation.AnalogParseMode, DZReadOnly = false, EventParseMode = imProtectDevice.PuctgyCodeNavigation.EventParseMode, IsActive = true, ManufacturerInfoId = porotectionDevice.EquipmentInfo.ManufacturerInfoId, Model = imProtectDevice.PuctgyCodeNavigation.Model, Name = imProtectDevice.PuctgyCodeNavigation.PuctgyName, Generation = imProtectDevice.PuctgyCodeNavigation.Generation, }; _protectionDeviceTypeyRepository.Insert(protectionDeviceType); _protectionDeviceGatewayRepository.Insert(protectionDeviceGateway); } } unitOfWork.Complete(); } rst.Flag = true; rst.Message = $"共完成{count}信息迁移"; } catch (Exception ex) { rst.Message = ex.Message; rst.Flag = false; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } /// /// 获取装置事件类型 /// /// /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [DisableAuditing] public RequestResult GetDeviceEventType(int deviceAddr,int eventCode) { RequestResult rst= new RequestResult(); try { var device = _imProtectDeviceRepository.GetAll().FirstOrDefault(t => t.DeviceAddr == deviceAddr); if (device!=null) { var imEvent = _imEventTypeRepository.GetAll().FirstOrDefault(t=>t.Id == eventCode&&t.PuctgyCode == device.PuctgyCode); if (imEvent!=null) { EquipmentInfoAbnormalComponent abnormalComponent = new EquipmentInfoAbnormalComponent() { ComponentName = device.DeviceName, AbnormalReason = imEvent.EvtName, HandlingMeasures ="", }; rst.ResultData = abnormalComponent; rst.Flag = true; } } } catch (Exception ex) { rst.Message = ex.Message; Log4Helper.Error(this.GetType(), "获取装置事件类型", ex); } return rst; } /// /// 获取装置状态 /// /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [DisableAuditing] [UnitOfWork(isTransactional: false)] public async Task> GetDeviceStatusAsync(Guid equipmentInfoId) { RequestResult rst = new RequestResult(); try { ProtectionDeviceInfo protectionDeviceInfo = default; using (var unitOfWork = _unitOfWorkManager.Begin()) { protectionDeviceInfo = _protectionDeviceInfoRepository.GetAllIncluding(t=>t.EquipmentInfo).FirstOrDefault(t=>t.EquipmentInfoId == equipmentInfoId); await unitOfWork.CompleteAsync(); } if (protectionDeviceInfo != null) { using (var unitOfWork = _unitOfWorkManager.Begin()) { var device = _imProtectDeviceRepository.GetAllIncluding(t=>t.GateWay).FirstOrDefault(t => t.Id == protectionDeviceInfo.ISMS_DeviceId); if (device != null) { DeviceStatus deviceStatus = new DeviceStatus() { ConnectionStatus104=0, EquipmentInfoId = equipmentInfoId, EquipmentInfoName = protectionDeviceInfo.EquipmentInfo.Name, FreeMemory = "0KB", UsedMemory ="0KB", LcdOperationPassword ="", ProtectionDeviceId = protectionDeviceInfo.Id, TotalDisk = "0M", UsedDisk ="0M", NetworkInterfaces = new List { new NetworkInterfaceStatus { IpAddress =device.GateWay.GatewayIp1, InterfaceName ="eth0", }, new NetworkInterfaceStatus { IpAddress =device.GateWay.GatewayIp2, InterfaceName ="eth1", }, new NetworkInterfaceStatus { IpAddress ="", InterfaceName ="eth2", }, } }; rst.ResultData = deviceStatus; rst.Flag = true; } await unitOfWork.CompleteAsync(); } } } catch (Exception ex) { rst.Message = ex.Message; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } /// /// 根据关键字获取保护装置的遥信遥测 /// /// /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] [DisableAuditing] public async Task>> GetTelemeteringByKeywordAsync(Guid equipmentInfoId,string keyword) { RequestResult> rst = new(); try { if (equipmentInfoId!=default&&!string.IsNullOrWhiteSpace(keyword)) { var repo =(await _telemeteringConfigurationRepository.GetAllIncludingAsync()) .Where(t => t.EquipmentInfoId == equipmentInfoId).ToList(); var data = repo.Where(t => t.Name.ToLower().Contains(keyword.ToLower())); rst.ResultData = ObjectMapper.Map>(data); rst.Flag = true; } //.Where(t=>t.Name.Contains()) } catch (Exception ex) { Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } /// /// 获取装置初始监测状态 /// /// /// [AbpAllowAnonymous] [HttpGet] [DisableAuditing] public async Task> GetDeviceCPUMonitoring(Guid equipmentInfoId) { RequestResult rst = new(); try { rst.ResultData = new DeviceCPUMonitoring { EquipmentInfoId = equipmentInfoId, CPU5V1 = 5f, CPU5V2 = 5f, CPU5V3 = 5f, CPUTemperature = 0, SurfaceTemperature = 0, Time = DateTime.Now, }; rst.Flag = true; } catch (Exception ex) { rst.Message = ex.Message; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } [AbpAllowAnonymous] [HttpGet] [DisableAuditing] public async Task> GetDeviceBCondeAndNTP(Guid equipmentInfoId) { RequestResult rst = new(); try { var device = _protectionDeviceInfoRepository.GetAll().FirstOrDefault(t => t.EquipmentInfoId == equipmentInfoId); if (device!=null) { var entity =await _bcodeAndNTP.HashSetGetOneAsync(nameof(BCodeAndNTP), device.DeviceAddress.ToString()); rst.ResultData = entity; rst.Flag = true; } } catch (Exception ex) { rst.Message = ex.Message; Log4Helper.Error(this.GetType(), "线路管理服务", ex); } return rst; } #if DEBUG /// /// 填充出厂编号 /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] public RequestEasyResult UpdateProtetionInfoForTest() { RequestEasyResult rst = new RequestEasyResult(); try { var datas = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo); Random random = new Random(); foreach (var data in datas) { data.BaselineBoardVersion = "v1.100.001"; data.Specification = "110V 1A"; data.EquipmentInfo.FactorySerialNumber = "210"+ random.Next(100000, 1000000).ToString(); // 设置出厂时间:当前日期的前一天(您可以根据需求调整时间) data.EquipmentInfo.ProductionDate = DateTime.Now.AddDays(-100); // 设置检验人员 data.EquipmentInfo.VerificationPerson = "贺严玲"; // 请替换:实际人员名称 // 设置检验日期:当前日期 data.EquipmentInfo.VerificationDate = DateTime.Now.AddDays(0).ToString("yyyy-MM-dd"); // 日期格式: "yyyy-MM-dd" // 设置检验记录内容 data.EquipmentInfo.VerificationRecords = "检验装置外观及功能,均符合要求"; } } catch (Exception ex) { throw; } return rst; } /// /// 填充出厂编号 /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] public async Task UpdateProtetionInfoForHistoryTest() { RequestEasyResult rst = new RequestEasyResult(); try { List datas; using (var unitOfWork = _unitOfWorkManager.Begin()) { datas = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo).ToList(); await unitOfWork.CompleteAsync(); } Random random = new Random(); for (int i = 0; i < 3; i++) { foreach (var data in datas) { EditProtectionQrCodeDeviceInfoInput deviceInfo = new EditProtectionQrCodeDeviceInfoInput { Name = data.Name, // 示例装置名称 SerialNumber = "210" + random.Next(100000, 1000000).ToString(), // 出厂编号设: "210" 开头 + 6 位随机数 ProductionDate = new DateTime(2023, 5, 15), // 示例生产日期 VerificationPerson = "贺严玲", // 示例检验人员 VerificationDate = DateTime.Now.AddDays(-100+i).ToString("yyyy-MM-dd"), // 检验日期设:当前日期 VerificationRecords = "检验装置外观及功能,均符合要求" // 示例检验记录 }; using (var unitOfWork = _unitOfWorkManager.Begin()) { ScanDeviceQRCode(deviceInfo); await unitOfWork.CompleteAsync(); } } } } catch (Exception ex) { throw; } return rst; } #endif /// /// 生成装置的初始历史记录 /// /// [ShowApi] [AbpAllowAnonymous] [HttpGet] public RequestEasyResult SpawnDeviceinfoHistory() { RequestEasyResult rst = new(); var protectionDevices = _protectionDeviceInfoRepository.GetAllIncluding(t => t.EquipmentInfo).ToList(); foreach (var protectionDevice in protectionDevices) { // 记录历史数据 var protectionDeviceHistory = new ProtectionDeviceHistory { Name = protectionDevice.Name, ProtectionDeviceInfoId = protectionDevice.Id, RecodeDate = protectionDevice.CreationTime, ContentJson = "", // 原始数据 ContentNewJson = JsonConvert.SerializeObject(protectionDevice), // 新数据 EventDescription = "保护设备台账建立", EventRecordType = EventRecordTypeEnum.Device, IsSend = false // 默认未发送 }; // 插入历史记录 _protectionDeviceHistoryRepository.Insert(protectionDeviceHistory); } rst.Flag = true; return rst; } } }