using JiShe.CollectBus.Common.Consts; using JiShe.CollectBus.FreeRedis; using JiShe.CollectBus.IotSystems.Protocols; using JiShe.CollectBus.Protocol.Interfaces; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Text.RegularExpressions; using Volo.Abp; using Volo.Abp.DependencyInjection; namespace JiShe.CollectBus.Protocol.Contracts.Services { public class ProtocolService : IProtocolService, ISingletonDependency { private readonly IFreeRedisProvider _freeRedisProvider; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public ProtocolService(IFreeRedisProvider freeRedisProvider, IServiceProvider serviceProvider, ILogger logger) { _freeRedisProvider = freeRedisProvider; _serviceProvider = serviceProvider; _logger= logger; } /// /// 通过仪器设备型号获取协议信息 /// /// /// /// /// public async Task FirstOrDefaultByDeviceAsync(string deviceCode, bool isSpecial = false) { var protocols = await _freeRedisProvider.Instance.HGetAllAsync(RedisConst.ProtocolKey); var keyValuePair = protocols.FirstOrDefault(a => ContainsExactPartRegex(deviceCode, a.Value.RegularExpression)); if (!keyValuePair.Key.IsNullOrWhiteSpace() || keyValuePair.Value != null) return keyValuePair.Value; if (isSpecial) throw new UserFriendlyException("The device protocol plugin does not exist!", ExceptionCode.NotFound); var hasStandardProtocolPlugin = protocols.TryGetValue("StandardProtocolPlugin", out var protocolInfo); if (!hasStandardProtocolPlugin) throw new UserFriendlyException("Standard protocol plugin does not exist!", ExceptionCode.NotFound); return protocolInfo; } /// /// 获取协议池服务 /// /// /// /// public async Task GetProtocolServiceAsync(string deviceCode, bool isSpecial = false) { try { ProtocolInfo protocolInfo= await FirstOrDefaultByDeviceAsync(deviceCode, isSpecial); if(protocolInfo==null) return null; return _serviceProvider.GetKeyedService(protocolInfo.Name); } catch (Exception ex) { _logger.LogError(ex, "获取协议失败"); return null; } } private static bool ContainsExactPartRegex(string searchPattern, string fullString) { // 构建正则表达式 - 匹配以逗号或开头为边界,以逗号或结尾为边界的部分 var pattern = $"(^|,)\\s*{Regex.Escape(searchPattern)}\\s*(,|$)"; return Regex.IsMatch(fullString, pattern, RegexOptions.IgnoreCase); } } }