using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JiShe.CollectBus.Common.Consts; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.FreeRedis; using JiShe.CollectBus.IotSystems.Protocols; using Volo.Abp.DependencyInjection; using JiShe.CollectBus.Protocol.Contracts.Interfaces; using System.Text.RegularExpressions; using Volo.Abp; namespace JiShe.CollectBus.Protocol.Contracts.Services { public class ProtocolService : IProtocolService, ISingletonDependency { private readonly IFreeRedisProvider _freeRedisProvider; public ProtocolService(IFreeRedisProvider freeRedisProvider) { _freeRedisProvider = freeRedisProvider; } /// /// 通过仪器设备型号获取协议信息 /// /// /// /// /// 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; } private static bool ContainsExactPartRegex(string searchPattern, string fullString) { // 构建正则表达式 - 匹配以逗号或开头为边界,以逗号或结尾为边界的部分 var pattern = $"(^|,)\\s*{Regex.Escape(searchPattern)}\\s*(,|$)"; return Regex.IsMatch(fullString, pattern, RegexOptions.IgnoreCase); } } }