using ProductionLineMonitor.Core.Dtos; using ProductionLineMonitor.Core.IRepositories; using ProductionLineMonitor.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; namespace ProductionLineMonitor.Application.Services.CimService { public class CimService : ICimService { private readonly IUnitOfWork _unitOfWork; public CimService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public void CreateOrUpdate(CimDto dto) { var cim = _unitOfWork.CimRepository.FirstOrDefault(x => x.Topic == dto.Topic); if (cim == null) { _unitOfWork.CimRepository.Create(new Cim() { Topic = dto.Topic, IpAddress = dto.IpAddress, User = dto.User, Time = dto.Time, PLCIsConnected = dto.PLCConnect, EAPIsConnected = dto.EAPConnect, IsConnected = true, Version = dto.Version, EAPIP = dto.EAPIP, EAPPort= dto.EAPPort, CreateTime = DateTime.Now }); _unitOfWork.SaveChanges(); } else { cim.IsConnected = true; cim.PLCIsConnected = dto.PLCConnect; cim.EAPIsConnected = dto.EAPConnect; if (cim.EAPIsConnected) { cim.IpAddress = dto.IpAddress; } cim.Topic = dto.Topic; cim.User = dto.User; cim.Time = dto.Time; cim.Version = dto.Version; cim.EAPIP= dto.EAPIP; cim.EAPPort= dto.EAPPort; cim.UpdateTime = DateTime.Now; _unitOfWork.CimRepository.Update(cim); _unitOfWork.SaveChanges(); } } public ResultDto> GetCims(bool isShowError) { if (isShowError == false) { var cims = _unitOfWork.CimRepository.GetList(); if (cims != null) foreach (var item in cims) { int index = item.Topic.LastIndexOf('#'); if (index != -1) { item.Topic = item.Topic.Substring(index + 1, item.Topic.Length - index - 1); } if (item.IpAddress != null) { index = item.IpAddress.LastIndexOf(':'); if (index != -1) { item.IpAddress = item.IpAddress[..index]; } } } return ResultDto>.Success(cims.OrderBy(o => o.Topic.Substring(0, 2))); } else { var cims = _unitOfWork.CimRepository.GetList( x => x.EAPIsConnected == false || x.PLCIsConnected == false || x.IsConnected == false).OrderBy(o => o.Topic); if (cims != null) foreach (var item in cims) { int index = item.Topic.LastIndexOf('#'); if (index != -1) { item.Topic = item.Topic.Substring(index + 1, item.Topic.Length - index - 1); } if (item.IpAddress != null) { index = item.IpAddress.LastIndexOf(':'); if (index != -1) { item.IpAddress = item.IpAddress[..index]; } } } return ResultDto>.Success(cims.OrderBy(o => o.Topic.Substring(0, 2))); } } public void UpdateMqttClientState(MqttClientStateDto dto) { var cim = _unitOfWork.CimRepository.FirstOrDefault(x => x.Topic == dto.ClientId); if (cim != null) { cim.IsConnected = dto.IsConnected; _unitOfWork.CimRepository.Update(cim); _unitOfWork.SaveChanges(); } } } }