From 53e6bb252ab74375010fbe6877ce5ced5590e47d Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Tue, 6 May 2025 23:46:12 +0800 Subject: [PATCH 01/15] =?UTF-8?q?=E4=BF=AE=E5=A4=8D15=E5=88=86=E9=92=9F?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1Kafka=E4=B8=BB=E9=A2=98=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=EF=BC=8C=E6=96=B0=E5=A2=9E=E5=A2=9E?= =?UTF-8?q?=E9=87=8F=E6=BA=90=E7=A0=81=E5=B7=A5=E5=8E=82=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 217 ++++++++++++++---- .../Samples/SampleAppService.cs | 5 + .../BasicScheduledMeterReadingService.cs | 2 +- ...rsProvider.cs => ISourceEntityAccessor.cs} | 4 +- 4 files changed, 178 insertions(+), 50 deletions(-) rename shared/JiShe.CollectBus.Analyzers.Shared/{ISourceAnalyzersProvider.cs => ISourceEntityAccessor.cs} (92%) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 20951e5..8ec5eb9 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -14,17 +14,14 @@ namespace JiShe.CollectBus.IncrementalGenerator public class ComplexTypeSourceAnalyzers : IIncrementalGenerator { private const string AttributeFullName = "JiShe.CollectBus.Analyzers.Shared.SourceAnalyzersAttribute"; + private const string SourceEntityAccessorFactoryNamespace = "JiShe.CollectBus.Analyzers.Shared"; public void Initialize(IncrementalGeneratorInitializationContext context) { //Debugger.Launch(); - context.RegisterPostInitializationOutput(ctx => - { - ctx.AddSource("GeneratorInit.g.cs", "// Initialization Marker"); - }); - // 步骤1:筛选带有 [GenerateAccessors] 的类 + // 步骤1:筛选带有 [SourceAnalyzers] 的类 var classDeclarations = context.SyntaxProvider .CreateSyntaxProvider( predicate: static (s, _) => IsClassWithAttribute(s), @@ -35,12 +32,11 @@ namespace JiShe.CollectBus.IncrementalGenerator var compilationAndClasses = context.CompilationProvider.Combine(classDeclarations.Collect()); context.RegisterSourceOutput(compilationAndClasses, (spc, source) => - GenerateCode(source.Left, source.Right!, spc)); + GenerateCode(source.Left, source.Right!, spc)); } private static bool IsClassWithAttribute(SyntaxNode node) => node is ClassDeclarationSyntax cds && cds.AttributeLists.Count > 0; - private static ClassDeclarationSyntax GetClassDeclaration(GeneratorSyntaxContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; @@ -76,18 +72,24 @@ namespace JiShe.CollectBus.IncrementalGenerator } } + /// + /// 生成代码 + /// + /// + /// + /// private static void GenerateCode( Compilation compilation, IEnumerable classes, SourceProductionContext context) { var processedTypes = new HashSet(SymbolEqualityComparer.Default); - + if (!classes.Any()) { context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor("GEN002", "No Targets", - "No classes with [GenerateAccessors] found", "Debug", DiagnosticSeverity.Warning, true), + new DiagnosticDescriptor("GEN002", "没有目标类", + "没有找到SourceAnalyzers标记的类", "Debug", DiagnosticSeverity.Warning, true), Location.None)); } @@ -99,46 +101,66 @@ namespace JiShe.CollectBus.IncrementalGenerator if (classSymbol == null || !processedTypes.Add(classSymbol)) { context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor("GEN003", "Invalid Symbol", - $"Class symbol is null for {classDecl.Identifier.Text}", "Error", DiagnosticSeverity.Error, true), + new DiagnosticDescriptor("GEN003", "无效符号", + $"类名称为{classDecl.Identifier.Text} 符号为空", "Error", DiagnosticSeverity.Error, true), Location.None)); continue; } - context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor( - "PA001", - "Generated Accessors", - $"Generating accessors for {classSymbol.Name}", - "Performance", - DiagnosticSeverity.Info, - true), - Location.None)); + //context.ReportDiagnostic(Diagnostic.Create( + //new DiagnosticDescriptor( + // "PA001", + // "Generated Accessors", + // $"Generating accessors for {classSymbol.Name}", + // "Performance", + // DiagnosticSeverity.Info, + // true), + //Location.None)); - // 新增:输出继承链信息 - context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor("HIERARCHY", "Class Hierarchy", - $"Processing class: {classSymbol.Name}, BaseType: {classSymbol.BaseType?.Name}", - "Debug", DiagnosticSeverity.Info, true), - Location.None)); + //// 新增:输出继承链信息 + //context.ReportDiagnostic(Diagnostic.Create( + // new DiagnosticDescriptor("HIERARCHY", "Class Hierarchy", + // $"Processing class: {classSymbol.Name}, BaseType: {classSymbol.BaseType?.Name}", + // "Debug", DiagnosticSeverity.Info, true), + // Location.None)); - context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor("PA002", "Class Found", - $"Processing class: {classSymbol.Name}", "Debug", DiagnosticSeverity.Warning, true), - Location.None)); + //context.ReportDiagnostic(Diagnostic.Create( + //new DiagnosticDescriptor("PA002", "Class Found", + //$"Processing class: {classSymbol.Name}", "Debug", DiagnosticSeverity.Warning, true), + //Location.None)); var code = BuildAccessorsForType(classSymbol, compilation, processedTypes); - System.Diagnostics.Debug.WriteLine($"Generated code for {classSymbol.Name}:\n{code}"); // 调试输出 + //System.Diagnostics.Debug.WriteLine($"Generated code for {classSymbol.Name}:\n{code}"); // 调试输出 context.AddSource($"{classSymbol.Name}Extension.g.cs", code); + + + var code3 = BuildAccessorsForType2(classSymbol, compilation, processedTypes); + context.AddSource($"{classSymbol.Name}Accessor.g.cs", code3); + + //code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); + //if (classSymbol.ContainingNamespace.ToDisplayString() == "JiShe.CollectBus.IoTDB") + //{ + + //} } + + // 生成工厂注册代码 + context.AddSource("SourceEntityAccessorFactory.g.cs", BuildFactoryCode()); } + /// + /// 构建类的属性访问器代码 + /// + /// + /// + /// + /// private static string BuildAccessorsForType( - INamedTypeSymbol classSymbol, - Compilation compilation, - HashSet processedTypes) + INamedTypeSymbol classSymbol, + Compilation compilation, + HashSet processedTypes) { var code = new StringBuilder(); code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); @@ -151,25 +173,67 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($"public static class {classSymbol.Name}Extension{GetGenericParams(classSymbol)}"); code.AppendLine("{"); - //foreach (var prop in classSymbol.GetMembers().OfType()) - //{ - // if (prop.IsIndexer) continue; - - // GeneratePropertyAccessors(prop, code, compilation, processedTypes); - //} - foreach (var prop in GetAllPropertiesInHierarchy(classSymbol)) { if (prop.IsIndexer) continue; - GeneratePropertyAccessors(prop, code, compilation, processedTypes); + GeneratePropertyAccessorsForType(prop, code, compilation, processedTypes); } code.AppendLine("}"); return code.ToString(); } - //private static string GetGenericParams(INamedTypeSymbol symbol) - // => symbol.IsGenericType ? $"<{string.Join(", ", symbol.TypeParameters.Select(t => t.Name))}>" : ""; + /// + /// 构建类的属性访问器代码 + /// + /// + /// + /// + /// + private static string BuildAccessorsForType2( + INamedTypeSymbol classSymbol, + Compilation compilation, + HashSet processedTypes) + { + var code = new StringBuilder(); + code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); + code.AppendLine("// Generated code for " + classSymbol.Name); + code.AppendLine("// "); + code.AppendLine("#nullable enable"); + code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); + code.AppendLine(); + + code.AppendLine($"public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}>"); + code.AppendLine("{"); + + foreach (var prop in GetAllPropertiesInHierarchy(classSymbol)) + { + if (prop.IsIndexer) continue; + GeneratePropertyAccessorsForType(prop, code, compilation, processedTypes); + } + + code.AppendLine("}"); + + //var code3 = $@" + // public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}> + // {{ + // public object GetPropertyValue({classSymbol.Name} entity, string propName) => propName switch + // {{ + // {GeneratePropertyCases(classSymbol)} + // _ => throw new ArgumentException(""无效属性名"") + // }}; + + // {GenerateTupleSupport(classSymbol)} + // }}"; + + return code.ToString(); + } + + /// + /// 获取泛型参数 + /// + /// + /// public static string GetGenericParams(INamedTypeSymbol symbol) { if (!symbol.IsGenericType) return ""; @@ -177,13 +241,20 @@ namespace JiShe.CollectBus.IncrementalGenerator return $"<{string.Join(", ", parameters)}>"; } - private static void GeneratePropertyAccessors( + /// + /// 生成属性访问器代码 + /// + /// + /// + /// + /// + private static void GeneratePropertyAccessorsForType( IPropertySymbol prop, StringBuilder code, Compilation compilation, HashSet processedTypes) { - // 关键修复点1:安全类型转换 + // 安全类型转换 if (prop.Type is not ITypeSymbol propType) return; code.AppendLine($" // Processing property: {prop.Name}"); @@ -200,6 +271,12 @@ namespace JiShe.CollectBus.IncrementalGenerator } } + /// + /// 处理元组类型 + /// + /// + /// + /// private static void GenerateTupleAccessors(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) { var elements = tupleType.TupleElements; @@ -222,6 +299,12 @@ namespace JiShe.CollectBus.IncrementalGenerator } } + /// + /// 生成标准属性的访问器 + /// + /// + /// + /// private static void GenerateStandardAccessors(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) { var parentType = prop.ContainingType.ToDisplayString(); @@ -233,6 +316,13 @@ namespace JiShe.CollectBus.IncrementalGenerator } } + + /// + /// 处理嵌套类型 + /// + /// + /// + /// private static void ProcessNestedType(ITypeSymbol typeSymbol, Compilation compilation, HashSet processedTypes) { if (typeSymbol is not INamedTypeSymbol namedType) return; @@ -242,6 +332,11 @@ namespace JiShe.CollectBus.IncrementalGenerator var code = BuildAccessorsForType(namedType, compilation, processedTypes); } + /// + /// 处理嵌套类型 + /// + /// + /// private static bool ShouldProcessNestedType(INamedTypeSymbol symbol) { return symbol.DeclaredAccessibility == Accessibility.Public && @@ -250,5 +345,33 @@ namespace JiShe.CollectBus.IncrementalGenerator !symbol.IsImplicitlyDeclared && !symbol.Name.StartsWith("<"); } + + /// + /// 生成扩展类工厂代码 + /// + /// + private static string BuildFactoryCode() + { + return """ + using System; + using System.Collections.Concurrent; + namespace JiShe.CollectBus.Analyzers.Shared; + public static class SourceEntityAccessorFactory + { + private static readonly ConcurrentDictionary _accessors = new(); + + public static ISourceEntityAccessor GetAccessor() + { + if (!_accessors.TryGetValue(typeof(T), out var accessor)) + { + accessor = Activator.CreateInstance( + Type.GetType($"{typeof(T).Namespace}.{typeof(T).Name}Accessor")!)!; + _accessors.TryAdd(typeof(T), accessor); + } + return (ISourceEntityAccessor)accessor!; + } + } + """; + } } } \ No newline at end of file diff --git a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs index ea2415e..79f0244 100644 --- a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs +++ b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -53,6 +53,10 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS [HttpGet] public async Task UseSessionPool(long testTime) { + var dataTime = DateTime.Now; + + List values = new List() { $"{dataTime:yy}", $"{dataTime:MM}", $"{dataTime:dd}", $"{dataTime:HH}", $"{dataTime:mm}", }; + ElectricityMeterTreeModel meter = new ElectricityMeterTreeModel() { @@ -67,6 +71,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS Timestamps = testTime// DateTimeOffset.UtcNow.ToUnixTimeNanoseconds()//testTime.GetDateTimeOffset().ToUnixTimeNanoseconds(), }; //ElectricityMeterTreeModelExtension.GetCurrent() + //SourceEntityAccessorFactory.SetCurrent(meter); await _iotDBProvider.InsertAsync(meter); } diff --git a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs index 2104d28..47b8a99 100644 --- a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs +++ b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs @@ -262,7 +262,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading //_logger.LogWarning($"电表 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerAutoValveControlIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerFifteenMinuteIssuedEventName, tempTask)); }); } else if (meteryType == MeterTypeEnum.WaterMeter.ToString()) diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceAnalyzersProvider.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs similarity index 92% rename from shared/JiShe.CollectBus.Analyzers.Shared/ISourceAnalyzersProvider.cs rename to shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index 905f0ef..3395239 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceAnalyzersProvider.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace JiShe.CollectBus.Analyzers +namespace JiShe.CollectBus.Analyzers.Shared { - public interface ISourceAnalyzersProvider + public interface ISourceEntityAccessor { /// /// 获取属性值 From bca72025586daaab407c258c6c240183f17cb031 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Wed, 7 May 2025 10:15:45 +0800 Subject: [PATCH 02/15] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E5=A2=9E=E9=87=8F=E6=BA=90=E7=94=9F=E6=88=90?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 247 ++++++++++++------ .../Model/TableModelSingleMeasuringEntity.cs | 2 +- .../Model/TreeModelSingleMeasuringEntity.cs | 2 +- .../Samples/SampleAppService.cs | 2 + .../ISourceEntityAccessor.cs | 26 +- 5 files changed, 177 insertions(+), 102 deletions(-) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 8ec5eb9..3b25aa0 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -1,5 +1,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -8,7 +9,7 @@ using System.Text; namespace JiShe.CollectBus.IncrementalGenerator { /// - /// 复杂类型源生成器 + /// 复杂类型增量源生成器 /// [Generator(LanguageNames.CSharp)] public class ComplexTypeSourceAnalyzers : IIncrementalGenerator @@ -32,11 +33,11 @@ namespace JiShe.CollectBus.IncrementalGenerator var compilationAndClasses = context.CompilationProvider.Combine(classDeclarations.Collect()); context.RegisterSourceOutput(compilationAndClasses, (spc, source) => - GenerateCode(source.Left, source.Right!, spc)); + GenerateCode(source.Left, source.Right!, spc)); } private static bool IsClassWithAttribute(SyntaxNode node) => node is ClassDeclarationSyntax cds && cds.AttributeLists.Count > 0; - + private static ClassDeclarationSyntax GetClassDeclaration(GeneratorSyntaxContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; @@ -106,44 +107,14 @@ namespace JiShe.CollectBus.IncrementalGenerator Location.None)); continue; } - - //context.ReportDiagnostic(Diagnostic.Create( - //new DiagnosticDescriptor( - // "PA001", - // "Generated Accessors", - // $"Generating accessors for {classSymbol.Name}", - // "Performance", - // DiagnosticSeverity.Info, - // true), - //Location.None)); - - //// 新增:输出继承链信息 - //context.ReportDiagnostic(Diagnostic.Create( - // new DiagnosticDescriptor("HIERARCHY", "Class Hierarchy", - // $"Processing class: {classSymbol.Name}, BaseType: {classSymbol.BaseType?.Name}", - // "Debug", DiagnosticSeverity.Info, true), - // Location.None)); - - //context.ReportDiagnostic(Diagnostic.Create( - //new DiagnosticDescriptor("PA002", "Class Found", - //$"Processing class: {classSymbol.Name}", "Debug", DiagnosticSeverity.Warning, true), - //Location.None)); - - var code = BuildAccessorsForType(classSymbol, compilation, processedTypes); - - //System.Diagnostics.Debug.WriteLine($"Generated code for {classSymbol.Name}:\n{code}"); // 调试输出 + + var code = BuildAccessorsForType(classSymbol, compilation, processedTypes); context.AddSource($"{classSymbol.Name}Extension.g.cs", code); - var code3 = BuildAccessorsForType2(classSymbol, compilation, processedTypes); + var code3 = BuildAccessorsForSourceEntity(classSymbol, compilation, processedTypes); context.AddSource($"{classSymbol.Name}Accessor.g.cs", code3); - - //code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); - //if (classSymbol.ContainingNamespace.ToDisplayString() == "JiShe.CollectBus.IoTDB") - //{ - - //} } // 生成工厂注册代码 @@ -183,52 +154,6 @@ namespace JiShe.CollectBus.IncrementalGenerator return code.ToString(); } - /// - /// 构建类的属性访问器代码 - /// - /// - /// - /// - /// - private static string BuildAccessorsForType2( - INamedTypeSymbol classSymbol, - Compilation compilation, - HashSet processedTypes) - { - var code = new StringBuilder(); - code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); - code.AppendLine("// Generated code for " + classSymbol.Name); - code.AppendLine("// "); - code.AppendLine("#nullable enable"); - code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); - code.AppendLine(); - - code.AppendLine($"public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}>"); - code.AppendLine("{"); - - foreach (var prop in GetAllPropertiesInHierarchy(classSymbol)) - { - if (prop.IsIndexer) continue; - GeneratePropertyAccessorsForType(prop, code, compilation, processedTypes); - } - - code.AppendLine("}"); - - //var code3 = $@" - // public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}> - // {{ - // public object GetPropertyValue({classSymbol.Name} entity, string propName) => propName switch - // {{ - // {GeneratePropertyCases(classSymbol)} - // _ => throw new ArgumentException(""无效属性名"") - // }}; - - // {GenerateTupleSupport(classSymbol)} - // }}"; - - return code.ToString(); - } - /// /// 获取泛型参数 /// @@ -262,11 +187,11 @@ namespace JiShe.CollectBus.IncrementalGenerator // 处理元组类型 if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) { - GenerateTupleAccessors(prop, tupleType, code); + GenerateTupleAccessorsForType(prop, tupleType, code); } else if (propType is INamedTypeSymbol namedType) { - GenerateStandardAccessors(prop, namedType, code); + GenerateStandardAccessorsForType(prop, namedType, code); ProcessNestedType(namedType, compilation, processedTypes); } } @@ -277,7 +202,7 @@ namespace JiShe.CollectBus.IncrementalGenerator /// /// /// - private static void GenerateTupleAccessors(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) + private static void GenerateTupleAccessorsForType(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) { var elements = tupleType.TupleElements; var parentType = prop.ContainingType.ToDisplayString(); @@ -305,7 +230,7 @@ namespace JiShe.CollectBus.IncrementalGenerator /// /// /// - private static void GenerateStandardAccessors(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) + private static void GenerateStandardAccessorsForType(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) { var parentType = prop.ContainingType.ToDisplayString(); code.AppendLine($" public static {propType.ToDisplayString()} Get{prop.Name}({parentType} obj) => obj.{prop.Name};"); @@ -316,7 +241,7 @@ namespace JiShe.CollectBus.IncrementalGenerator } } - + /// /// 处理嵌套类型 /// @@ -373,5 +298,153 @@ namespace JiShe.CollectBus.IncrementalGenerator } """; } + + /// + /// 构建实体类的源属性访问器代码 + /// + /// + /// + /// + /// + private static string BuildAccessorsForSourceEntity( + INamedTypeSymbol classSymbol, + Compilation compilation, + HashSet processedTypes) + { + var code = new StringBuilder(); + code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); + code.AppendLine("// Generated code for " + classSymbol.Name); + code.AppendLine("// "); + code.AppendLine("#nullable enable"); + code.AppendLine("using System;"); + code.AppendLine("using JiShe.CollectBus.Analyzers.Shared;"); + code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); + code.AppendLine(); + + code.AppendLine($"public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}>"); + code.AppendLine("{"); + + GetGeneratePropertyValueForSourceEntity(GetAllPropertiesInHierarchy(classSymbol), code, compilation, classSymbol); + + SetGeneratePropertyValueForSourceEntity(GetAllPropertiesInHierarchy(classSymbol), code, compilation, classSymbol); + + code.AppendLine("}"); + + return code.ToString(); + } + + private static void GetGeneratePropertyValueForSourceEntity(IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) + { + + code.AppendLine($" public object GetPropertyValue({classSymbol.Name} targetEntity, string propertyName)"); + code.AppendLine(" {"); + code.AppendLine(" return propertyName switch"); + code.AppendLine(" {"); + + // 遍历所有属性 + foreach (var property in propList) + { + // 安全类型转换 + if (property.Type is not ITypeSymbol propType) continue; + + // 处理元组类型 + if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) + { + } + else if (propType is INamedTypeSymbol namedType) + { + // 生成属性访问的 + code.AppendLine($" \"{property.Name}\" => {classSymbol.Name}Extension.Get{property.Name}(targetEntity),"); + } + } + + + code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); + code.AppendLine(" };"); + code.AppendLine(" }"); + } + + + private static void SetGeneratePropertyValueForSourceEntity(IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) + { + code.AppendLine($" public void SetPropertyValue({classSymbol.Name} targetEntity, string propertyName, object value)"); + code.AppendLine(" {"); + code.AppendLine(" return propertyName switch"); + code.AppendLine(" {"); + + // 遍历所有属性 + foreach (var property in propList) + { + // 安全类型转换 + if (property.Type is not ITypeSymbol propType) continue; + + // 处理元组类型 + if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) + { + } + else if (propType is INamedTypeSymbol namedType) + { + // 生成属性设置赋值 + code.AppendLine($" \"{property.Name}\" => {classSymbol.Name}Extension.Set{property.Name}(targetEntity,({namedType.ToDisplayString()})value),"); + + } + } + + + code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); + code.AppendLine(" };"); + code.AppendLine(" }"); + } + + /// + /// 处理元组类型 + /// + /// + /// + /// + private static void GenerateTupleAccessorsForSourceEntity(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) + { + var elements = tupleType.TupleElements; + var parentType = prop.ContainingType.ToDisplayString(); + + for (int i = 0; i < elements.Length; i++) + { + var element = elements[i]; + if (element.Type is not ITypeSymbol elementType) continue; + + var elementName = element.CorrespondingTupleField?.Name ?? $"Item{i + 1}"; + code.AppendLine($" public static {elementType.ToDisplayString()} Get{prop.Name}_{elementName}({parentType} obj) => obj.{prop.Name}.{elementName};"); + + if (prop.SetMethod != null) + { + var assignments = elements.Select((e, idx) => + idx == i ? "value" : $"obj.{prop.Name}.{e.Name}"); + code.AppendLine($" public static void Set{prop.Name}_{elementName}({parentType} obj, {elementType.ToDisplayString()} value) => obj.{prop.Name} = ({string.Join(", ", assignments)});"); + } + } + } + + /// + /// 生成标准属性的访问器 + /// + /// + /// + /// + private static void GenerateStandardAccessorsForSourceEntity(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) + { + var parentType = prop.ContainingType.ToDisplayString(); + code.AppendLine($" public object {propType.ToDisplayString()} Get{prop.Name}({parentType} obj) => obj.{prop.Name};"); + + if (prop.SetMethod != null) + { + code.AppendLine($" public static void Set{prop.Name}({parentType} obj, {propType.ToDisplayString()} value) => obj.{prop.Name} = value;"); + } + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs index 966f226..3355a33 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs @@ -8,7 +8,7 @@ namespace JiShe.CollectBus.IoTDB.Model /// Table模型单项数据实体 /// [EntityType(EntityTypeEnum.TableModel)] - [SourceAnalyzers] + //[SourceAnalyzers] public class TableModelSingleMeasuringEntity : IoTEntity { /// diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs index 719c3c3..f59f648 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs @@ -8,7 +8,7 @@ namespace JiShe.CollectBus.IoTDB.Model /// Tree模型单项数据实体 /// [EntityType(EntityTypeEnum.TreeModel)] - [SourceAnalyzers] + //[SourceAnalyzers] public class TreeModelSingleMeasuringEntity : IoTEntity { /// diff --git a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs index 79f0244..95ed072 100644 --- a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs +++ b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -72,6 +72,8 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS }; //ElectricityMeterTreeModelExtension.GetCurrent() //SourceEntityAccessorFactory.SetCurrent(meter); + + ElectricityMeterTreeModelAccessor await _iotDBProvider.InsertAsync(meter); } diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index 3395239..2a448c1 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -22,19 +22,19 @@ namespace JiShe.CollectBus.Analyzers.Shared /// void SetPropertyValue(T entity, string propertyName, object value); - /// - /// 判断是否是元组属性 - /// - /// - /// - bool IsTupleProperty(string propertyName); + ///// + ///// 判断是否是元组属性 + ///// + ///// + ///// + //bool IsTupleProperty(string propertyName); - /// - /// 获取元组属性值 - /// - /// - /// - /// - (object Item1, object Item2) GetTupleParts(T entity, string tuplePropertyName); + ///// + ///// 获取元组属性值 + ///// + ///// + ///// + ///// + //(object Item1, object Item2) GetTupleParts(T entity, string tuplePropertyName); } } From 6b012d93037b5c251807dbe5520afaed3d277f56 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Wed, 7 May 2025 16:37:26 +0800 Subject: [PATCH 03/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E5=A2=9E=E9=87=8F=E6=BA=90=E7=A0=81=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 526 +++++++++--------- .../Model/TableModelSingleMeasuringEntity.cs | 4 +- .../Model/TreeModelSingleMeasuringEntity.cs | 4 +- .../Provider/IoTDBProvider.cs | 132 +++-- .../AnalysisData/DataStorage.cs | 4 +- .../Samples/SampleAppService.cs | 19 +- .../BasicScheduledMeterReadingService.cs | 68 +-- .../Ammeters/ElectricityMeter.cs | 2 +- .../Ammeters/ElectricityMeterTreeModel.cs | 3 + .../ISourceEntityAccessor.cs | 18 +- 10 files changed, 401 insertions(+), 379 deletions(-) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 3b25aa0..804b7c0 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -15,13 +15,11 @@ namespace JiShe.CollectBus.IncrementalGenerator public class ComplexTypeSourceAnalyzers : IIncrementalGenerator { private const string AttributeFullName = "JiShe.CollectBus.Analyzers.Shared.SourceAnalyzersAttribute"; - private const string SourceEntityAccessorFactoryNamespace = "JiShe.CollectBus.Analyzers.Shared"; public void Initialize(IncrementalGeneratorInitializationContext context) { //Debugger.Launch(); - // 步骤1:筛选带有 [SourceAnalyzers] 的类 var classDeclarations = context.SyntaxProvider .CreateSyntaxProvider( @@ -108,11 +106,6 @@ namespace JiShe.CollectBus.IncrementalGenerator continue; } - var code = BuildAccessorsForType(classSymbol, compilation, processedTypes); - - context.AddSource($"{classSymbol.Name}Extension.g.cs", code); - - var code3 = BuildAccessorsForSourceEntity(classSymbol, compilation, processedTypes); context.AddSource($"{classSymbol.Name}Accessor.g.cs", code3); } @@ -120,40 +113,7 @@ namespace JiShe.CollectBus.IncrementalGenerator // 生成工厂注册代码 context.AddSource("SourceEntityAccessorFactory.g.cs", BuildFactoryCode()); } - - /// - /// 构建类的属性访问器代码 - /// - /// - /// - /// - /// - private static string BuildAccessorsForType( - INamedTypeSymbol classSymbol, - Compilation compilation, - HashSet processedTypes) - { - var code = new StringBuilder(); - code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); - code.AppendLine("// Generated code for " + classSymbol.Name); - code.AppendLine("// "); - code.AppendLine("#nullable enable"); - code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); - code.AppendLine(); - - code.AppendLine($"public static class {classSymbol.Name}Extension{GetGenericParams(classSymbol)}"); - code.AppendLine("{"); - - foreach (var prop in GetAllPropertiesInHierarchy(classSymbol)) - { - if (prop.IsIndexer) continue; - GeneratePropertyAccessorsForType(prop, code, compilation, processedTypes); - } - - code.AppendLine("}"); - return code.ToString(); - } - + /// /// 获取泛型参数 /// @@ -165,72 +125,15 @@ namespace JiShe.CollectBus.IncrementalGenerator var parameters = symbol.TypeParameters.Select(t => t.Name); return $"<{string.Join(", ", parameters)}>"; } - - /// - /// 生成属性访问器代码 - /// - /// - /// - /// - /// - private static void GeneratePropertyAccessorsForType( - IPropertySymbol prop, - StringBuilder code, - Compilation compilation, - HashSet processedTypes) - { - // 安全类型转换 - if (prop.Type is not ITypeSymbol propType) return; - - code.AppendLine($" // Processing property: {prop.Name}"); - - // 处理元组类型 - if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) - { - GenerateTupleAccessorsForType(prop, tupleType, code); - } - else if (propType is INamedTypeSymbol namedType) - { - GenerateStandardAccessorsForType(prop, namedType, code); - ProcessNestedType(namedType, compilation, processedTypes); - } - } - - /// - /// 处理元组类型 - /// - /// - /// - /// - private static void GenerateTupleAccessorsForType(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) - { - var elements = tupleType.TupleElements; - var parentType = prop.ContainingType.ToDisplayString(); - - for (int i = 0; i < elements.Length; i++) - { - var element = elements[i]; - if (element.Type is not ITypeSymbol elementType) continue; - - var elementName = element.CorrespondingTupleField?.Name ?? $"Item{i + 1}"; - code.AppendLine($" public static {elementType.ToDisplayString()} Get{prop.Name}_{elementName}({parentType} obj) => obj.{prop.Name}.{elementName};"); - - if (prop.SetMethod != null) - { - var assignments = elements.Select((e, idx) => - idx == i ? "value" : $"obj.{prop.Name}.{e.Name}"); - code.AppendLine($" public static void Set{prop.Name}_{elementName}({parentType} obj, {elementType.ToDisplayString()} value) => obj.{prop.Name} = ({string.Join(", ", assignments)});"); - } - } - } - + + /// /// 生成标准属性的访问器 /// /// /// /// - private static void GenerateStandardAccessorsForType(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) + private static void GenerateStandardAccessors(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) { var parentType = prop.ContainingType.ToDisplayString(); code.AppendLine($" public static {propType.ToDisplayString()} Get{prop.Name}({parentType} obj) => obj.{prop.Name};"); @@ -240,211 +143,318 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($" public static void Set{prop.Name}({parentType} obj, {propType.ToDisplayString()} value) => obj.{prop.Name} = value;"); } } - + /// - /// 处理嵌套类型 + /// 构建实体访问器代码(支持泛型) /// - /// - /// - /// - private static void ProcessNestedType(ITypeSymbol typeSymbol, Compilation compilation, HashSet processedTypes) - { - if (typeSymbol is not INamedTypeSymbol namedType) return; - if (!ShouldProcessNestedType(namedType)) return; - if (!processedTypes.Add(namedType)) return; - - var code = BuildAccessorsForType(namedType, compilation, processedTypes); - } - - /// - /// 处理嵌套类型 - /// - /// - /// - private static bool ShouldProcessNestedType(INamedTypeSymbol symbol) - { - return symbol.DeclaredAccessibility == Accessibility.Public && - !symbol.IsTupleType && - !symbol.IsAnonymousType && - !symbol.IsImplicitlyDeclared && - !symbol.Name.StartsWith("<"); - } - - /// - /// 生成扩展类工厂代码 - /// - /// - private static string BuildFactoryCode() - { - return """ - using System; - using System.Collections.Concurrent; - namespace JiShe.CollectBus.Analyzers.Shared; - public static class SourceEntityAccessorFactory - { - private static readonly ConcurrentDictionary _accessors = new(); - - public static ISourceEntityAccessor GetAccessor() - { - if (!_accessors.TryGetValue(typeof(T), out var accessor)) - { - accessor = Activator.CreateInstance( - Type.GetType($"{typeof(T).Namespace}.{typeof(T).Name}Accessor")!)!; - _accessors.TryAdd(typeof(T), accessor); - } - return (ISourceEntityAccessor)accessor!; - } - } - """; - } - - /// - /// 构建实体类的源属性访问器代码 - /// - /// - /// - /// - /// private static string BuildAccessorsForSourceEntity( - INamedTypeSymbol classSymbol, - Compilation compilation, - HashSet processedTypes) + INamedTypeSymbol classSymbol, + Compilation compilation, + HashSet processedTypes) { var code = new StringBuilder(); - code.AppendLine("#pragma warning disable CS0419 // 禁用警告"); - code.AppendLine("// Generated code for " + classSymbol.Name); code.AppendLine("// "); code.AppendLine("#nullable enable"); code.AppendLine("using System;"); + code.AppendLine("using System.Collections.Generic;"); code.AppendLine("using JiShe.CollectBus.Analyzers.Shared;"); code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); code.AppendLine(); - code.AppendLine($"public sealed class {classSymbol.Name}Accessor : ISourceEntityAccessor<{classSymbol.Name}>"); - code.AppendLine("{"); - - GetGeneratePropertyValueForSourceEntity(GetAllPropertiesInHierarchy(classSymbol), code, compilation, classSymbol); + // 处理泛型类型参数 + var genericParams = classSymbol.IsGenericType + ? $"<{string.Join(", ", classSymbol.TypeParameters.Select(t => t.Name))}>" + : ""; + + code.AppendLine( + $"public sealed class {classSymbol.Name}Accessor{genericParams} " + + $": ISourceEntityAccessor<{classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>"); + + code.AppendLine("{"); + + var propList = GetAllPropertiesInHierarchy(classSymbol); + + foreach (var prop in propList) + { + // 安全类型转换 + if (prop.Type is not ITypeSymbol propType) continue; + + if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) + { + GenerateTupleAccessors(prop, tupleType, code, classSymbol); + } + else if (propType is INamedTypeSymbol namedType) + { + GenerateStandardAccessors(prop, namedType, code); + } + } + + //生成当前类属性名称集合 + GeneratePropertyListForSourceEntity(propList, code, compilation, classSymbol); + + + //生成当前类属性访问 + GetGeneratePropertyValueForSourceEntity( + propList, + code, + compilation, + classSymbol); + + //生成当前类属性设置 + SetGeneratePropertyValueForSourceEntity( + propList, + code, + compilation, + classSymbol); + - SetGeneratePropertyValueForSourceEntity(GetAllPropertiesInHierarchy(classSymbol), code, compilation, classSymbol); code.AppendLine("}"); - return code.ToString(); } - private static void GetGeneratePropertyValueForSourceEntity(IEnumerable propList, + /// + /// 生成泛型ValueTuple 元组访问器 + /// + private static void GenerateTupleAccessors( + IPropertySymbol prop, + INamedTypeSymbol tupleType, + StringBuilder code, + INamedTypeSymbol classSymbol) + { + var parentType = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var tupleElements = tupleType.TupleElements; + + for (int i = 0; i < tupleElements.Length; i++) + { + var element = tupleElements[i]; + var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementName = element.Name; + + // Getter保持不变 + code.AppendLine( + $" public static {elementType} Get{prop.Name}_{elementName}" + + $"({parentType} obj) => obj.{prop.Name}.{elementName};"); + + // Setter修复:使用元组字面量 + if (prop.SetMethod != null) + { + var valueExpressions = tupleElements.Select((e, idx) => + idx == i ? "value" : $"obj.{prop.Name}.{e.Name}" + ).ToList(); + + // 关键修复:生成正确的元组字面量表达式 + code.AppendLine( + $" public static void Set{prop.Name}_{elementName}" + + $"({parentType} obj, {elementType} value) => " + + $"obj.{prop.Name} = ({string.Join(", ", valueExpressions)});"); + } + } + } + + /// + /// 处理System.Tuple类型的访问器生成 + /// + private static void GenerateSystemTupleAccessors( + IPropertySymbol prop, + INamedTypeSymbol tupleType, + StringBuilder code, + INamedTypeSymbol classSymbol) + { + var parentType = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementTypes = tupleType.TypeArguments; + var tupleTypeName = tupleType.ToDisplayString(); + + for (int i = 0; i < elementTypes.Length; i++) + { + var elementType = elementTypes[i].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementName = $"Item{i + 1}"; + + // Getter + code.AppendLine( + $" public static {elementType} Get{prop.Name}_{elementName}" + + $"({parentType} obj) => obj.{prop.Name}.{elementName};"); + + // Setter + if (prop.SetMethod != null) + { + var assignments = elementTypes.Select((_, idx) => + idx == i ? "value" : $"obj.{prop.Name}.Item{idx + 1}" + ).ToList(); + + code.AppendLine( + $" public static void Set{prop.Name}_{elementName}" + + $"({parentType} obj, {elementType} value) => " + + $"obj.{prop.Name} = new {tupleTypeName}({string.Join(", ", assignments)});"); + } + } + } + + /// + /// 增强的工厂类实现 + /// + private static string BuildFactoryCode() + { + return """ + using System; + using System.Collections.Concurrent; + using System.Reflection; + + namespace JiShe.CollectBus.Analyzers.Shared; + + public static class SourceEntityAccessorFactory + { + private static readonly ConcurrentDictionary _accessors = new(); + + public static ISourceEntityAccessor GetAccessor() + { + return (ISourceEntityAccessor)_accessors.GetOrAdd(typeof(T), t => + { + var typeName = $"{t.Namespace}.{t.Name}Accessor"; + if (t.IsGenericType) + { + var genericArgs = t.GetGenericArguments(); + var genericDef = t.GetGenericTypeDefinition(); + typeName = $"{genericDef.Namespace}.{genericDef.Name}Accessor`{genericArgs.Length}"; + } + + var type = Type.GetType(typeName) + ?? Assembly.GetAssembly(t)?.GetType(typeName) + ?? throw new InvalidOperationException($"Accessor type {typeName} not found"); + + return t.IsGenericType + ? Activator.CreateInstance(type.MakeGenericType(t.GetGenericArguments())) + : Activator.CreateInstance(type); + }); + } + } + """; + } + + /// + /// 属性访问生成逻辑 + /// + /// 属性集合 + /// + /// + /// + private static void GetGeneratePropertyValueForSourceEntity( + IEnumerable propList, StringBuilder code, Compilation compilation, INamedTypeSymbol classSymbol) { - - code.AppendLine($" public object GetPropertyValue({classSymbol.Name} targetEntity, string propertyName)"); + code.AppendLine($" public object GetPropertyValue({classSymbol} targetEntity, string propertyName)"); + code.AppendLine(" {"); + code.AppendLine(" return propertyName switch"); code.AppendLine(" {"); - code.AppendLine(" return propertyName switch"); - code.AppendLine(" {"); - // 遍历所有属性 - foreach (var property in propList) - { - // 安全类型转换 - if (property.Type is not ITypeSymbol propType) continue; - - // 处理元组类型 - if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) - { - } - else if (propType is INamedTypeSymbol namedType) - { - // 生成属性访问的 - code.AppendLine($" \"{property.Name}\" => {classSymbol.Name}Extension.Get{property.Name}(targetEntity),"); - } - } - - - code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); - code.AppendLine(" };"); - code.AppendLine(" }"); - } - - - private static void SetGeneratePropertyValueForSourceEntity(IEnumerable propList, - StringBuilder code, - Compilation compilation, - INamedTypeSymbol classSymbol) - { - code.AppendLine($" public void SetPropertyValue({classSymbol.Name} targetEntity, string propertyName, object value)"); - code.AppendLine(" {"); - code.AppendLine(" return propertyName switch"); - code.AppendLine(" {"); - - // 遍历所有属性 - foreach (var property in propList) + foreach (var prop in propList) { - // 安全类型转换 - if (property.Type is not ITypeSymbol propType) continue; - - // 处理元组类型 - if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) - { - } - else if (propType is INamedTypeSymbol namedType) + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { - // 生成属性设置赋值 - code.AppendLine($" \"{property.Name}\" => {classSymbol.Name}Extension.Set{property.Name}(targetEntity,({namedType.ToDisplayString()})value),"); - - } + foreach (var element in tupleType.TupleElements) + { + code.AppendLine( + $" \"{prop.Name}.{element.Name}\" => " + + $"Get{prop.Name}_{element.Name}(targetEntity),"); + } + } + else + { + code.AppendLine( + $" \"{prop.Name}\" => " + + $"Get{prop.Name}(targetEntity),"); + } } - - code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); - code.AppendLine(" };"); - code.AppendLine(" }"); + code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); + code.AppendLine(" };"); + code.AppendLine(" }"); } /// - /// 处理元组类型 + /// 属性设置生成逻辑 /// - /// - /// + /// 属性集合 /// - private static void GenerateTupleAccessorsForSourceEntity(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code) + /// + /// + private static void SetGeneratePropertyValueForSourceEntity( + IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) { - var elements = tupleType.TupleElements; - var parentType = prop.ContainingType.ToDisplayString(); + code.AppendLine($" public void SetPropertyValue({classSymbol} targetEntity, string propertyName, object value)"); + code.AppendLine(" {"); + code.AppendLine(" switch (propertyName)"); + code.AppendLine(" {"); - for (int i = 0; i < elements.Length; i++) + foreach (var prop in propList) { - var element = elements[i]; - if (element.Type is not ITypeSymbol elementType) continue; - - var elementName = element.CorrespondingTupleField?.Name ?? $"Item{i + 1}"; - code.AppendLine($" public static {elementType.ToDisplayString()} Get{prop.Name}_{elementName}({parentType} obj) => obj.{prop.Name}.{elementName};"); - - if (prop.SetMethod != null) + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { - var assignments = elements.Select((e, idx) => - idx == i ? "value" : $"obj.{prop.Name}.{e.Name}"); - code.AppendLine($" public static void Set{prop.Name}_{elementName}({parentType} obj, {elementType.ToDisplayString()} value) => obj.{prop.Name} = ({string.Join(", ", assignments)});"); + foreach (var element in tupleType.TupleElements) + { + var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + code.AppendLine($" case \"{prop.Name}.{element.Name}\":"); + code.AppendLine($" Set{prop.Name}_{element.Name}("); + code.AppendLine($" targetEntity, ({elementType})value);"); + code.AppendLine(" break;"); + } + } + else if (prop.SetMethod != null) + { + var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + code.AppendLine($" case \"{prop.Name}\":"); + code.AppendLine($" Set{prop.Name}("); + code.AppendLine($" targetEntity, ({propType})value);"); + code.AppendLine(" break;"); } } + + code.AppendLine(" default:"); + code.AppendLine(" throw new ArgumentException($\"Unknown property: {propertyName}\");"); + code.AppendLine(" }"); + code.AppendLine(" }"); } /// - /// 生成标准属性的访问器 + /// 属性名称集合 /// - /// - /// + /// 属性集合 /// - private static void GenerateStandardAccessorsForSourceEntity(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code) + /// + /// + private static void GeneratePropertyListForSourceEntity( + IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) { - var parentType = prop.ContainingType.ToDisplayString(); - code.AppendLine($" public object {propType.ToDisplayString()} Get{prop.Name}({parentType} obj) => obj.{prop.Name};"); - - if (prop.SetMethod != null) + code.AppendLine(" public List PropertyList {get;} = new List()"); + code.AppendLine(" {"); + List tempPropList = new List(); + foreach (var prop in propList) { - code.AppendLine($" public static void Set{prop.Name}({parentType} obj, {propType.ToDisplayString()} value) => obj.{prop.Name} = value;"); + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) + { + foreach (var element in tupleType.TupleElements) + { + tempPropList.Add($"\"{prop.Name}.{element.Name}\""); + } + } + else + { + tempPropList.Add($"\"{prop.Name}\""); + } } + + code.Append(string.Join(",", tempPropList)); + + code.AppendLine(" };"); } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs index 3355a33..ed0fd4d 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs @@ -8,13 +8,13 @@ namespace JiShe.CollectBus.IoTDB.Model /// Table模型单项数据实体 /// [EntityType(EntityTypeEnum.TableModel)] - //[SourceAnalyzers] + [SourceAnalyzers] public class TableModelSingleMeasuringEntity : IoTEntity { /// /// 单项数据键值对 /// [SingleMeasuring(nameof(SingleColumn))] - public required Tuple SingleColumn { get; set; } + public required ValueTuple SingleColumn { get; set; } } } diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs index f59f648..c87516c 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs @@ -8,13 +8,13 @@ namespace JiShe.CollectBus.IoTDB.Model /// Tree模型单项数据实体 /// [EntityType(EntityTypeEnum.TreeModel)] - //[SourceAnalyzers] + [SourceAnalyzers] public class TreeModelSingleMeasuringEntity : IoTEntity { /// /// 单项数据键值对 /// [SingleMeasuring(nameof(SingleMeasuring))] - public required Tuple SingleMeasuring { get; set; } + public required ValueTuple SingleMeasuring { get; set; } } } diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index d867674..aebce66 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -20,6 +20,7 @@ using JiShe.CollectBus.IoTDB.Options; using Microsoft.Extensions.Logging; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; +using JiShe.CollectBus.Analyzers.Shared; namespace JiShe.CollectBus.IoTDB.Provider { @@ -176,6 +177,8 @@ namespace JiShe.CollectBus.IoTDB.Provider /// public async Task GetMetadata() where T : IoTEntity { + var accessor = SourceEntityAccessorFactory.GetAccessor(); + var columns = CollectColumnMetadata(typeof(T)); var metadata = BuildDeviceMetadata(columns); var metaData = MetadataCache.AddOrUpdate( @@ -260,6 +263,8 @@ namespace JiShe.CollectBus.IoTDB.Provider List tempColumnNames = new List(); tempColumnNames.AddRange(metadata.ColumnNames); + var accessor = SourceEntityAccessorFactory.GetAccessor(); + var entityTypeAttribute = typeof(T).GetCustomAttribute(); if (entityTypeAttribute == null) @@ -295,69 +300,74 @@ namespace JiShe.CollectBus.IoTDB.Provider foreach (var measurement in tempColumnNames) { - - PropertyInfo propertyInfo = typeof(T).GetProperty(measurement); - if (propertyInfo == null) - { - throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,没有找到{measurement}属性,属于异常情况,-101。"); - } - - var value = propertyInfo.GetValue(entity); - if (propertyInfo.IsDefined(typeof(SingleMeasuringAttribute), false) && metadata.IsSingleMeasuring == true)//表示当前对象是单测点模式 - { - if (value != null) - { - Type tupleType = value.GetType(); - Type[] tupleArgs = tupleType.GetGenericArguments(); - Type item2Type = tupleArgs[1]; // T 的实际类型 - var item1 = tupleType.GetProperty("Item1")!.GetValue(value); - var item2 = tupleType.GetProperty("Item2")!.GetValue(value); - if (item1 == null || item2 == null) - { - throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,单测点模式构建失败,没有获取测点名称或者测点值,-102。"); - } - - var indexOf = metadata.ColumnNames.IndexOf(measurement); - metadata.ColumnNames[indexOf] = (string)item1!; - - rowValues.Add(item2); - } - else - { - rowValues.Add(null); - } - - //同时如果是单测点模式,且是table模型存储,路径只能通过DevicePathBuilder.GetDeviceTableName(entity)获取 - if (_runtimeContext.UseTableSessionPool) - { - tableNameOrTreePath = DevicePathBuilder.GetDeviceTableName(entity); - } - } - else - { - - //需要根据value的类型,进行相应的值映射转换,例如datetime转换为long的时间戳值 - if (value != null) - { - Type tupleType = value.GetType(); - var tempValue = tupleType.Name.ToUpper() switch - { - "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), - _ => value - }; - - rowValues.Add(tempValue); - } - else - { - rowValues.Add(value); - } - - } - + rowValues.Add(accessor.GetPropertyValue(entity,measurement)); } - values.Add(rowValues); + //foreach (var measurement in tempColumnNames) + //{ + + // PropertyInfo propertyInfo = typeof(T).GetProperty(measurement); + // if (propertyInfo == null) + // { + // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,没有找到{measurement}属性,属于异常情况,-101。"); + // } + + // var value = propertyInfo.GetValue(entity); + // if (propertyInfo.IsDefined(typeof(SingleMeasuringAttribute), false) && metadata.IsSingleMeasuring == true)//表示当前对象是单测点模式 + // { + // if (value != null) + // { + // Type tupleType = value.GetType(); + // Type[] tupleArgs = tupleType.GetGenericArguments(); + // Type item2Type = tupleArgs[1]; // T 的实际类型 + // var item1 = tupleType.GetProperty("Item1")!.GetValue(value); + // var item2 = tupleType.GetProperty("Item2")!.GetValue(value); + // if (item1 == null || item2 == null) + // { + // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,单测点模式构建失败,没有获取测点名称或者测点值,-102。"); + // } + + // var indexOf = metadata.ColumnNames.IndexOf(measurement); + // metadata.ColumnNames[indexOf] = (string)item1!; + + // rowValues.Add(item2); + // } + // else + // { + // rowValues.Add(null); + // } + + // //同时如果是单测点模式,且是table模型存储,路径只能通过DevicePathBuilder.GetDeviceTableName(entity)获取 + // if (_runtimeContext.UseTableSessionPool) + // { + // tableNameOrTreePath = DevicePathBuilder.GetDeviceTableName(entity); + // } + // } + // else + // { + + // //需要根据value的类型,进行相应的值映射转换,例如datetime转换为long的时间戳值 + // if (value != null) + // { + // Type tupleType = value.GetType(); + // var tempValue = tupleType.Name.ToUpper() switch + // { + // "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), + // _ => value + // }; + + // rowValues.Add(tempValue); + // } + // else + // { + // rowValues.Add(value); + // } + + // } + + //} + + values.Add(rowValues); //如果指定了路径 if (!string.IsNullOrWhiteSpace(tableNameOrTreePath)) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs index 00435e0..3b3816a 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs @@ -90,7 +90,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData DeviceType = $"{data.MeterType}", ProjectId = $"{data.ProjectId}", Timestamps = data.TimeSpan!.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity).GetDateTimeOffset().ToUnixTimeMilliseconds(), - SingleMeasuring = new Tuple(data.FiledName ?? string.Empty, data.DataValue ?? default) + SingleMeasuring = (data.FiledName ?? string.Empty, data.DataValue ?? default) }; _runtimeContext.UseTableSessionPool = true; // 使用表模型池 var taskSendInfo = await _dbProvider.QueryAsync(new IoTDBQueryOptions() { TableNameOrTreePath = DevicePathBuilder.GetTableName(), Conditions = conditions, PageIndex = 0, PageSize = 1 }); @@ -193,7 +193,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData DeviceType = $"{item.MeterType}", ProjectId = $"{item.ProjectId}", Timestamps = item.TimeSpan!.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity).GetDateTimeOffset().ToUnixTimeMilliseconds(), // TODO:这里暂时格式化15分钟数据,需要进行调整 - SingleMeasuring = new Tuple(item.FiledName ?? string.Empty, item.DataValue ?? default) + SingleMeasuring = (item.FiledName ?? string.Empty, item.DataValue ?? default) }; _runtimeContext.UseTableSessionPool = true; // 使用表模型池 var taskSendInfo = await _dbProvider.QueryAsync(new IoTDBQueryOptions() { TableNameOrTreePath = DevicePathBuilder.GetTableName(), Conditions = conditions, PageIndex = 0, PageSize = 1 }); diff --git a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs index 95ed072..ef3b894 100644 --- a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs +++ b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -73,7 +73,9 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS //ElectricityMeterTreeModelExtension.GetCurrent() //SourceEntityAccessorFactory.SetCurrent(meter); - ElectricityMeterTreeModelAccessor + //ElectricityMeterTreeModelAccessor. + //TableModelSingleMeasuringEntityExtension + //TableModelSingleMeasuringEntityAccessor.GetSystemName(meter); await _iotDBProvider.InsertAsync(meter); } @@ -172,6 +174,8 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS [HttpGet] public async Task TestTreeModelSingleMeasuringEntity(string measuring, string value, DateTime time) { + time = DateTime.Now; + var meter = new TreeModelSingleMeasuringEntity() { SystemName = "energy", @@ -179,7 +183,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS DeviceType = "1", ProjectId = "10059", Timestamps = time.GetDateTimeOffset().ToUnixTimeMilliseconds(), - SingleMeasuring = new Tuple(measuring, value) + SingleMeasuring = (measuring, value) }; await _iotDBProvider.InsertAsync(meter); } @@ -192,6 +196,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS [HttpGet] public async Task TestTreeModelSingleMeasuringEntity2(string measuring, int value, DateTime time) { + time = DateTime.Now; var meter = new TreeModelSingleMeasuringEntity() { SystemName = "energy", @@ -199,7 +204,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS DeviceType = "Ammeter", ProjectId = "10059", Timestamps = time.GetDateTimeOffset().ToUnixTimeMilliseconds(), - SingleMeasuring = new Tuple(measuring, value) + SingleMeasuring = (measuring, value) }; await _iotDBProvider.InsertAsync(meter); } @@ -212,6 +217,8 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS [HttpGet] public async Task TestTableModelSingleMeasuringEntity(string measuring, string value, DateTime time) { + time = DateTime.Now; + var meter = new TableModelSingleMeasuringEntity() { SystemName = "energy", @@ -219,7 +226,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS DeviceType = "Ammeter", ProjectId = "10059", Timestamps = time.GetDateTimeOffset().ToUnixTimeMilliseconds(), - SingleColumn = new Tuple(measuring, value) + SingleColumn = (measuring, value) }; _dbContext.UseTableSessionPool = true; await _iotDBProvider.InsertAsync(meter); @@ -233,6 +240,8 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS [HttpGet] public async Task TestTableModelSingleMeasuringEntity2(string measuring, int value, DateTime time) { + time = DateTime.Now; + var meter = new TableModelSingleMeasuringEntity() { SystemName = "energy", @@ -240,7 +249,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS DeviceType = "Ammeter", ProjectId = "10059", Timestamps = time.GetDateTimeOffset().ToUnixTimeMilliseconds(), - SingleColumn = new Tuple(measuring, value) + SingleColumn = (measuring, value) }; _dbContext.UseTableSessionPool = true; await _iotDBProvider.InsertAsync(meter); diff --git a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs index 47b8a99..e75ad84 100644 --- a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs +++ b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs @@ -336,47 +336,47 @@ namespace JiShe.CollectBus.ScheduledMeterReading //此处代码不要删除 #if DEBUG - var timeDensity = "15"; - var serverTagName = "JiSheCollectBus2"; - var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; - var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; - var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + //var timeDensity = "15"; + //var serverTagName = "JiSheCollectBus2"; + //var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + //var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + //var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; List meterInfos = new List(); - List focusAddressDataLista = new List(); - var timer1 = Stopwatch.StartNew(); + //List focusAddressDataLista = new List(); + //var timer1 = Stopwatch.StartNew(); - var allIds = new HashSet(); - decimal? score = null; - string member = null; + //var allIds = new HashSet(); + //decimal? score = null; + //string member = null; - while (true) - { - var page = await _redisDataCacheService.GetAllPagedData( - redisCacheMeterInfoHashKeyTemp, - redisCacheMeterInfoZSetScoresIndexKeyTemp, - pageSize: 1000, - lastScore: score, - lastMember: member); + //while (true) + //{ + // var page = await _redisDataCacheService.GetAllPagedData( + // redisCacheMeterInfoHashKeyTemp, + // redisCacheMeterInfoZSetScoresIndexKeyTemp, + // pageSize: 1000, + // lastScore: score, + // lastMember: member); - meterInfos.AddRange(page.Items); - focusAddressDataLista.AddRange(page.Items.Select(d => $"{d.MeterId}")); - foreach (var item in page.Items) - { - if (!allIds.Add(item.MemberId)) - { - _logger.LogError($"{item.MemberId}Duplicate data found!"); - } - } - if (!page.HasNext) break; - score = page.NextScore; - member = page.NextMember; - } + // meterInfos.AddRange(page.Items); + // focusAddressDataLista.AddRange(page.Items.Select(d => $"{d.MeterId}")); + // foreach (var item in page.Items) + // { + // if (!allIds.Add(item.MemberId)) + // { + // _logger.LogError($"{item.MemberId}Duplicate data found!"); + // } + // } + // if (!page.HasNext) break; + // score = page.NextScore; + // member = page.NextMember; + //} - timer1.Stop(); - _logger.LogError($"电表初始化读取数据总共花费时间{timer1.ElapsedMilliseconds}毫秒"); - DeviceGroupBalanceControl.InitializeCache(focusAddressDataLista, _kafkaOptions.NumPartitions); + //timer1.Stop(); + //_logger.LogError($"电表初始化读取数据总共花费时间{timer1.ElapsedMilliseconds}毫秒"); + //DeviceGroupBalanceControl.InitializeCache(focusAddressDataLista, _kafkaOptions.NumPartitions); return; #else var meterInfos = await GetAmmeterInfoList(gatherCode); diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs index 9ba3c94..c04a554 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs @@ -6,7 +6,7 @@ using JiShe.CollectBus.IoTDB.Model; namespace JiShe.CollectBus.Ammeters { [EntityType(EntityTypeEnum.TableModel)] - [SourceAnalyzers] + //[SourceAnalyzers] public class ElectricityMeter : IoTEntity { [ATTRIBUTEColumn] diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs index 1f11198..38d3ee6 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs @@ -2,6 +2,7 @@ using JiShe.CollectBus.IoTDB.Attribute; using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; +using System; namespace JiShe.CollectBus.Ammeters { @@ -35,5 +36,7 @@ namespace JiShe.CollectBus.Ammeters [FIELDColumn] public double? Currentd { get; set; } + + public Tuple TupleData { get; set;} } } diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index 2a448c1..baff180 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -22,19 +22,9 @@ namespace JiShe.CollectBus.Analyzers.Shared /// void SetPropertyValue(T entity, string propertyName, object value); - ///// - ///// 判断是否是元组属性 - ///// - ///// - ///// - //bool IsTupleProperty(string propertyName); - - ///// - ///// 获取元组属性值 - ///// - ///// - ///// - ///// - //(object Item1, object Item2) GetTupleParts(T entity, string tuplePropertyName); + /// + /// 属性名称集合 + /// + List PropertyList { get; } } } From ff517664fe1091c8011f0432f11192722c654be4 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Wed, 7 May 2025 17:20:10 +0800 Subject: [PATCH 04/15] =?UTF-8?q?=E5=A4=8D=E6=9D=82=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=A2=9E=E9=87=8F=E6=BA=90=E7=94=9F=E6=88=90=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 46 +++++++---- ...TableModelSingleMeasuringEntityAccessor.cs | 77 +++++++++++++++++++ .../Provider/IoTDBProvider.cs | 9 ++- 3 files changed, 113 insertions(+), 19 deletions(-) create mode 100644 modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 804b7c0..195175a 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -162,13 +162,19 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); code.AppendLine(); - // 处理泛型类型参数 + // 处理泛型类型名称 + var accessibility = classSymbol.DeclaredAccessibility switch + { + Accessibility.Public => "public", + _ => "internal" + }; + var genericParams = classSymbol.IsGenericType ? $"<{string.Join(", ", classSymbol.TypeParameters.Select(t => t.Name))}>" : ""; code.AppendLine( - $"public sealed class {classSymbol.Name}Accessor{genericParams} " + + $"{accessibility} sealed class {classSymbol.Name}Accessor{genericParams} " + // 保留泛型参数 $": ISourceEntityAccessor<{classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>"); code.AppendLine("{"); @@ -306,26 +312,32 @@ namespace JiShe.CollectBus.IncrementalGenerator public static class SourceEntityAccessorFactory { private static readonly ConcurrentDictionary _accessors = new(); - + public static ISourceEntityAccessor GetAccessor() { return (ISourceEntityAccessor)_accessors.GetOrAdd(typeof(T), t => { - var typeName = $"{t.Namespace}.{t.Name}Accessor"; - if (t.IsGenericType) - { - var genericArgs = t.GetGenericArguments(); - var genericDef = t.GetGenericTypeDefinition(); - typeName = $"{genericDef.Namespace}.{genericDef.Name}Accessor`{genericArgs.Length}"; - } - - var type = Type.GetType(typeName) - ?? Assembly.GetAssembly(t)?.GetType(typeName) + // 获取泛型类型定义信息(如果是泛型类型) + var isGeneric = t.IsGenericType; + var genericTypeDef = isGeneric ? t.GetGenericTypeDefinition() : null; + var arity = isGeneric ? genericTypeDef!.GetGenericArguments().Length : 0; + + // 构建访问器类名 + var typeName = isGeneric + ? $"{t.Namespace}.{genericTypeDef!.Name.Split('`')[0]}Accessor`{arity}" + : $"{t.Namespace}.{t.Name}Accessor"; + + // 尝试从当前程序集加载 + var accessorType = Assembly.GetAssembly(t)!.GetType(typeName) ?? throw new InvalidOperationException($"Accessor type {typeName} not found"); - - return t.IsGenericType - ? Activator.CreateInstance(type.MakeGenericType(t.GetGenericArguments())) - : Activator.CreateInstance(type); + + // 处理泛型参数 + if (isGeneric && accessorType.IsGenericTypeDefinition) + { + accessorType = accessorType.MakeGenericType(t.GetGenericArguments()); + } + + return Activator.CreateInstance(accessorType)!; }); } } diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs new file mode 100644 index 0000000..9c9c773 --- /dev/null +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs @@ -0,0 +1,77 @@ +// +#nullable enable +using System; +using System.Collections.Generic; +using JiShe.CollectBus.Analyzers.Shared; +namespace JiShe.CollectBus.IoTDB.Model; + +public sealed class TableModelSingleMeasuringEntityAccessor3 : ISourceEntityAccessor> +{ + public static string GetSingleColumn_Item1(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj) => obj.SingleColumn.Item1; + public static void SetSingleColumn_Item1(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj, string value) => obj.SingleColumn = (value, obj.SingleColumn.Item2); + public static T GetSingleColumn_Item2(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj) => obj.SingleColumn.Item2; + public static void SetSingleColumn_Item2(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj, T value) => obj.SingleColumn = (obj.SingleColumn.Item1, value); + public static string GetSystemName(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.SystemName; + public static void SetSystemName(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.SystemName = value; + public static string GetProjectId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.ProjectId; + public static void SetProjectId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.ProjectId = value; + public static string GetDeviceType(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.DeviceType; + public static void SetDeviceType(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.DeviceType = value; + public static string GetDeviceId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.DeviceId; + public static void SetDeviceId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.DeviceId = value; + public static long GetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.Timestamps; + public static void SetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, long value) => obj.Timestamps = value; + public List PropertyList { get; } = new List() + { +"SingleColumn.Item1","SingleColumn.Item2","SystemName","ProjectId","DeviceType","DeviceId","Timestamps" }; + public object GetPropertyValue(JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity targetEntity, string propertyName) + { + return propertyName switch + { + "SingleColumn.Item1" => GetSingleColumn_Item1(targetEntity), + "SingleColumn.Item2" => GetSingleColumn_Item2(targetEntity), + "SystemName" => GetSystemName(targetEntity), + "ProjectId" => GetProjectId(targetEntity), + "DeviceType" => GetDeviceType(targetEntity), + "DeviceId" => GetDeviceId(targetEntity), + "Timestamps" => GetTimestamps(targetEntity), + _ => throw new ArgumentException($"Unknown property: {propertyName}") + }; + } + public void SetPropertyValue(JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity targetEntity, string propertyName, object value) + { + switch (propertyName) + { + case "SingleColumn.Item1": + SetSingleColumn_Item1( + targetEntity, (string)value); + break; + case "SingleColumn.Item2": + SetSingleColumn_Item2( + targetEntity, (T)value); + break; + case "SystemName": + SetSystemName( + targetEntity, (string)value); + break; + case "ProjectId": + SetProjectId( + targetEntity, (string)value); + break; + case "DeviceType": + SetDeviceType( + targetEntity, (string)value); + break; + case "DeviceId": + SetDeviceId( + targetEntity, (string)value); + break; + case "Timestamps": + SetTimestamps( + targetEntity, (long)value); + break; + default: + throw new ArgumentException($"Unknown property: {propertyName}"); + } + } +} diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index aebce66..704363c 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -566,6 +566,8 @@ namespace JiShe.CollectBus.IoTDB.Provider //metadata.ColumnNames.Insert(0, "Timestamps"); //metadata.DataTypes.Insert(0, TSDataType.TIMESTAMP); + var accessor = SourceEntityAccessorFactory.GetAccessor(); + while (dataSet.HasNext() && results.Count < pageSize) { var record = dataSet.Next(); @@ -588,11 +590,14 @@ namespace JiShe.CollectBus.IoTDB.Provider if (measurement.ToLower().EndsWith("time")) { - typeof(T).GetProperty(measurement)?.SetValue(entity, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); + //typeof(T).GetProperty(measurement)?.SetValue(entity, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); + + accessor.SetPropertyValue(entity, measurement, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); } else { - typeof(T).GetProperty(measurement)?.SetValue(entity, tempValue); + accessor.SetPropertyValue(entity, measurement, tempValue); + //typeof(T).GetProperty(measurement)?.SetValue(entity, tempValue); } } From c47ee9446900e4f2c76baa3ec64fc522c6a35220 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Wed, 7 May 2025 17:27:37 +0800 Subject: [PATCH 05/15] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 51 +++++++++++++++++-- ...TableModelSingleMeasuringEntityAccessor.cs | 2 +- .../ISourceEntityAccessor.cs | 8 ++- 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 195175a..ea0ef13 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -157,6 +157,7 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine("// "); code.AppendLine("#nullable enable"); code.AppendLine("using System;"); + code.AppendLine("using System.Reflection;"); code.AppendLine("using System.Collections.Generic;"); code.AppendLine("using JiShe.CollectBus.Analyzers.Shared;"); code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};"); @@ -198,7 +199,14 @@ namespace JiShe.CollectBus.IncrementalGenerator //生成当前类属性名称集合 GeneratePropertyListForSourceEntity(propList, code, compilation, classSymbol); - + + //生成当前类属性信息集合 + GeneratePropertyInfoListForSourceEntity( + propList, + code, + compilation, + classSymbol); + //生成当前类属性访问 GetGeneratePropertyValueForSourceEntity( @@ -213,9 +221,7 @@ namespace JiShe.CollectBus.IncrementalGenerator code, compilation, classSymbol); - - - + code.AppendLine("}"); return code.ToString(); } @@ -468,5 +474,42 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine(" };"); } + + + /// + /// 生成当前类属性信息集合 + /// + /// 属性集合 + /// + /// + /// + private static void GeneratePropertyInfoListForSourceEntity( + IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) + { + code.AppendLine(" public List PropertyList {get;} = new List()"); + code.AppendLine(" {"); + List tempPropList = new List(); + foreach (var prop in propList) + { + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) + { + foreach (var element in tupleType.TupleElements) + { + tempPropList.Add($"\"{prop.Name}.{element.Name}\""); + } + } + else + { + tempPropList.Add($"\"{prop.Name}\""); + } + } + + code.Append(string.Join(",", tempPropList)); + + code.AppendLine(" };"); + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs index 9c9c773..e0bedd4 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs @@ -21,7 +21,7 @@ public sealed class TableModelSingleMeasuringEntityAccessor3 : ISourceEntityA public static void SetDeviceId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.DeviceId = value; public static long GetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.Timestamps; public static void SetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, long value) => obj.Timestamps = value; - public List PropertyList { get; } = new List() + public List PropertyNameList { get; } = new List() { "SingleColumn.Item1","SingleColumn.Item2","SystemName","ProjectId","DeviceType","DeviceId","Timestamps" }; public object GetPropertyValue(JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity targetEntity, string propertyName) diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index baff180..5e67826 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using System.Text; namespace JiShe.CollectBus.Analyzers.Shared @@ -25,6 +26,11 @@ namespace JiShe.CollectBus.Analyzers.Shared /// /// 属性名称集合 /// - List PropertyList { get; } + List PropertyNameList { get; } + + /// + /// 属性信息集合 + /// + List PropertyInfoList { get; } } } From f71ce3bacb65b20da327a280fcab856da8596d30 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 08:43:37 +0800 Subject: [PATCH 06/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=A2=9E=E9=87=8F?= =?UTF-8?q?=E6=BA=90=E7=A0=81=E7=94=9F=E6=88=90=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 44 +++++++---- ...TableModelSingleMeasuringEntityAccessor.cs | 77 ------------------- .../T37612012ProtocolPlugin.cs | 16 ++-- .../DataChannels/DataChannelManageService.cs | 14 ++-- .../BasicScheduledMeterReadingService.cs | 68 ++++++++-------- 5 files changed, 78 insertions(+), 141 deletions(-) delete mode 100644 modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index ea0ef13..3b82bf2 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -452,7 +452,7 @@ namespace JiShe.CollectBus.IncrementalGenerator Compilation compilation, INamedTypeSymbol classSymbol) { - code.AppendLine(" public List PropertyList {get;} = new List()"); + code.AppendLine(" public List PropertyNameList {get;} = new List()"); code.AppendLine(" {"); List tempPropList = new List(); foreach (var prop in propList) @@ -477,39 +477,53 @@ namespace JiShe.CollectBus.IncrementalGenerator /// - /// 生成当前类属性信息集合 + /// 生成当前类属性信息集合(支持嵌套元组) /// - /// 属性集合 - /// - /// - /// private static void GeneratePropertyInfoListForSourceEntity( IEnumerable propList, StringBuilder code, Compilation compilation, INamedTypeSymbol classSymbol) { - code.AppendLine(" public List PropertyList {get;} = new List()"); + code.AppendLine(" public List PropertyInfoList { get; } = new List"); code.AppendLine(" {"); - List tempPropList = new List(); + + var initializerLines = new List(); + foreach (var prop in propList) { + // 主属性 + AddPropertyInitializer(classSymbol, prop, initializerLines); + + // 处理元组嵌套属性 if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) { - tempPropList.Add($"\"{prop.Name}.{element.Name}\""); + // 生成形如:typeof(ValueTuple).GetProperty("Item1") + var tupleTypeName = tupleType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + initializerLines.Add( + $"typeof({tupleTypeName}).GetProperty(\"{element.Name}\") ?? " + + $"throw new InvalidOperationException(\"Tuple element {element.Name} not found\")"); } } - else - { - tempPropList.Add($"\"{prop.Name}\""); - } } - code.Append(string.Join(",", tempPropList)); - + code.AppendLine(string.Join(",\n", initializerLines)); code.AppendLine(" };"); } + + private static void AddPropertyInitializer( + INamedTypeSymbol classSymbol, + IPropertySymbol prop, + List initializerLines) + { + var classType = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + initializerLines.Add( + $"typeof({classType}).GetProperty(\"{prop.Name}\", " + + "System.Reflection.BindingFlags.Public | " + + "System.Reflection.BindingFlags.Instance) ?? " + + $"throw new InvalidOperationException(\"Property {prop.Name} not found\")"); + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs deleted file mode 100644 index e0bedd4..0000000 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntityAccessor.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -#nullable enable -using System; -using System.Collections.Generic; -using JiShe.CollectBus.Analyzers.Shared; -namespace JiShe.CollectBus.IoTDB.Model; - -public sealed class TableModelSingleMeasuringEntityAccessor3 : ISourceEntityAccessor> -{ - public static string GetSingleColumn_Item1(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj) => obj.SingleColumn.Item1; - public static void SetSingleColumn_Item1(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj, string value) => obj.SingleColumn = (value, obj.SingleColumn.Item2); - public static T GetSingleColumn_Item2(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj) => obj.SingleColumn.Item2; - public static void SetSingleColumn_Item2(global::JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity obj, T value) => obj.SingleColumn = (obj.SingleColumn.Item1, value); - public static string GetSystemName(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.SystemName; - public static void SetSystemName(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.SystemName = value; - public static string GetProjectId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.ProjectId; - public static void SetProjectId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.ProjectId = value; - public static string GetDeviceType(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.DeviceType; - public static void SetDeviceType(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.DeviceType = value; - public static string GetDeviceId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.DeviceId; - public static void SetDeviceId(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, string value) => obj.DeviceId = value; - public static long GetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj) => obj.Timestamps; - public static void SetTimestamps(JiShe.CollectBus.IoTDB.Model.IoTEntity obj, long value) => obj.Timestamps = value; - public List PropertyNameList { get; } = new List() - { -"SingleColumn.Item1","SingleColumn.Item2","SystemName","ProjectId","DeviceType","DeviceId","Timestamps" }; - public object GetPropertyValue(JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity targetEntity, string propertyName) - { - return propertyName switch - { - "SingleColumn.Item1" => GetSingleColumn_Item1(targetEntity), - "SingleColumn.Item2" => GetSingleColumn_Item2(targetEntity), - "SystemName" => GetSystemName(targetEntity), - "ProjectId" => GetProjectId(targetEntity), - "DeviceType" => GetDeviceType(targetEntity), - "DeviceId" => GetDeviceId(targetEntity), - "Timestamps" => GetTimestamps(targetEntity), - _ => throw new ArgumentException($"Unknown property: {propertyName}") - }; - } - public void SetPropertyValue(JiShe.CollectBus.IoTDB.Model.TableModelSingleMeasuringEntity targetEntity, string propertyName, object value) - { - switch (propertyName) - { - case "SingleColumn.Item1": - SetSingleColumn_Item1( - targetEntity, (string)value); - break; - case "SingleColumn.Item2": - SetSingleColumn_Item2( - targetEntity, (T)value); - break; - case "SystemName": - SetSystemName( - targetEntity, (string)value); - break; - case "ProjectId": - SetProjectId( - targetEntity, (string)value); - break; - case "DeviceType": - SetDeviceType( - targetEntity, (string)value); - break; - case "DeviceId": - SetDeviceId( - targetEntity, (string)value); - break; - case "Timestamps": - SetTimestamps( - targetEntity, (long)value); - break; - default: - throw new ArgumentException($"Unknown property: {propertyName}"); - } - } -} diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/T37612012ProtocolPlugin.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/T37612012ProtocolPlugin.cs index a469147..73ecd15 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/T37612012ProtocolPlugin.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/T37612012ProtocolPlugin.cs @@ -715,10 +715,10 @@ namespace JiShe.CollectBus.Protocol.T37612012 /// public virtual List Generate_DataUnit(DataTimeMark timeMark) { - List values = new List - { - SplitDataTime(timeMark.DataTime)//数据时间 - }; + List values = new List(); + + values.AddRange(SplitDataTime(timeMark.DataTime));//数据时间 + if (timeMark.Density > 0) values.Add(timeMark.Density.HexToDecStr().PadLeft(2, '0'));//密度 if (timeMark.Point > 0) @@ -727,13 +727,13 @@ namespace JiShe.CollectBus.Protocol.T37612012 } - private string SplitDataTime(DateTime dataTime) + private List SplitDataTime(DateTime dataTime) { //2101060815 - List values = new List() { $"{dataTime}:YY", $"{dataTime}:MM", $"{dataTime}:dd", $"{dataTime}:HH", $"{dataTime}:mm", }; - + List values = new List() { $"{dataTime:yy}", $"{dataTime:MM}", $"{dataTime:dd}", $"{dataTime:HH}", $"{dataTime:mm}", }; values.Reverse(); - return string.Join("", values); + return values; + //return string.Join("", values); } #endregion diff --git a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs index c129194..17ae182 100644 --- a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs +++ b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs @@ -125,13 +125,13 @@ namespace JiShe.CollectBus.DataChannels // 批量写入数据库 await _dbProvider.BatchInsertAsync(metadata, records); - // 限流推送Kafka - await DeviceGroupBalanceControl.ProcessWithThrottleAsync( - items: records, - deviceIdSelector: data => data.DeviceId, - processor: async (data, groupIndex) => - await KafkaProducerIssuedMessageAction(topicName, data, groupIndex) - ); + //// 限流推送Kafka + //await DeviceGroupBalanceControl.ProcessWithThrottleAsync( + // items: records, + // deviceIdSelector: data => data.DeviceId, + // processor: async (data, groupIndex) => + // await KafkaProducerIssuedMessageAction(topicName, data, groupIndex) + //); } catch (Exception ex) { diff --git a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs index e75ad84..47b8a99 100644 --- a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs +++ b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs @@ -336,47 +336,47 @@ namespace JiShe.CollectBus.ScheduledMeterReading //此处代码不要删除 #if DEBUG - //var timeDensity = "15"; - //var serverTagName = "JiSheCollectBus2"; - //var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; - //var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; - //var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + var timeDensity = "15"; + var serverTagName = "JiSheCollectBus2"; + var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; + var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, serverTagName, MeterTypeEnum.Ammeter, timeDensity)}"; List meterInfos = new List(); - //List focusAddressDataLista = new List(); - //var timer1 = Stopwatch.StartNew(); + List focusAddressDataLista = new List(); + var timer1 = Stopwatch.StartNew(); - //var allIds = new HashSet(); - //decimal? score = null; - //string member = null; + var allIds = new HashSet(); + decimal? score = null; + string member = null; - //while (true) - //{ - // var page = await _redisDataCacheService.GetAllPagedData( - // redisCacheMeterInfoHashKeyTemp, - // redisCacheMeterInfoZSetScoresIndexKeyTemp, - // pageSize: 1000, - // lastScore: score, - // lastMember: member); + while (true) + { + var page = await _redisDataCacheService.GetAllPagedData( + redisCacheMeterInfoHashKeyTemp, + redisCacheMeterInfoZSetScoresIndexKeyTemp, + pageSize: 1000, + lastScore: score, + lastMember: member); - // meterInfos.AddRange(page.Items); - // focusAddressDataLista.AddRange(page.Items.Select(d => $"{d.MeterId}")); - // foreach (var item in page.Items) - // { - // if (!allIds.Add(item.MemberId)) - // { - // _logger.LogError($"{item.MemberId}Duplicate data found!"); - // } - // } - // if (!page.HasNext) break; - // score = page.NextScore; - // member = page.NextMember; - //} + meterInfos.AddRange(page.Items); + focusAddressDataLista.AddRange(page.Items.Select(d => $"{d.MeterId}")); + foreach (var item in page.Items) + { + if (!allIds.Add(item.MemberId)) + { + _logger.LogError($"{item.MemberId}Duplicate data found!"); + } + } + if (!page.HasNext) break; + score = page.NextScore; + member = page.NextMember; + } - //timer1.Stop(); - //_logger.LogError($"电表初始化读取数据总共花费时间{timer1.ElapsedMilliseconds}毫秒"); - //DeviceGroupBalanceControl.InitializeCache(focusAddressDataLista, _kafkaOptions.NumPartitions); + timer1.Stop(); + _logger.LogError($"电表初始化读取数据总共花费时间{timer1.ElapsedMilliseconds}毫秒"); + DeviceGroupBalanceControl.InitializeCache(focusAddressDataLista, _kafkaOptions.NumPartitions); return; #else var meterInfos = await GetAmmeterInfoList(gatherCode); From edecbc386e178815b359675b761f24b152fd68dc Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 10:28:23 +0800 Subject: [PATCH 07/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E9=80=9A=E9=81=93=E6=95=B0=E6=8D=AE=E5=A4=84=E7=90=86=EF=BC=8C?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=95=B0=E6=8D=AE=E4=B8=A2=E5=A4=B1=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 9 ++- .../Provider/IoTDBProvider.cs | 31 ++++++--- .../DataChannels/IDataChannelManageService.cs | 5 +- .../CollectBusApplicationModule.cs | 2 +- .../DataChannels/DataChannelManage.cs | 2 +- .../DataChannels/DataChannelManageService.cs | 67 ++++++++++++------- .../Samples/SampleAppService.cs | 3 +- .../BasicScheduledMeterReadingService.cs | 24 ++++--- .../EntityMemberInfo.cs | 32 +++++++++ 9 files changed, 121 insertions(+), 54 deletions(-) create mode 100644 shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 3b82bf2..befb833 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -490,21 +490,20 @@ namespace JiShe.CollectBus.IncrementalGenerator var initializerLines = new List(); + foreach (var prop in propList) { - // 主属性 AddPropertyInitializer(classSymbol, prop, initializerLines); - // 处理元组嵌套属性 if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) { - // 生成形如:typeof(ValueTuple).GetProperty("Item1") + //使用GetField代替GetProperty var tupleTypeName = tupleType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); initializerLines.Add( - $"typeof({tupleTypeName}).GetProperty(\"{element.Name}\") ?? " + - $"throw new InvalidOperationException(\"Tuple element {element.Name} not found\")"); + $"typeof({tupleTypeName}).GetField(\"{element.Name}\") ?? " + + $"throw new InvalidOperationException(\"Tuple field {element.Name} not found\")"); } } } diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index 704363c..83040fe 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -179,14 +179,14 @@ namespace JiShe.CollectBus.IoTDB.Provider { var accessor = SourceEntityAccessorFactory.GetAccessor(); - var columns = CollectColumnMetadata(typeof(T)); + var columns = CollectColumnMetadata(accessor); var metadata = BuildDeviceMetadata(columns); var metaData = MetadataCache.AddOrUpdate( typeof(T), addValueFactory: t => metadata, // 如果键不存在,用此值添加 updateValueFactory: (t, existingValue) => { - var columns = CollectColumnMetadata(t); + var columns = CollectColumnMetadata(accessor); var metadata = BuildDeviceMetadata(columns); //对现有值 existingValue 进行修改,返回新值 @@ -300,7 +300,23 @@ namespace JiShe.CollectBus.IoTDB.Provider foreach (var measurement in tempColumnNames) { - rowValues.Add(accessor.GetPropertyValue(entity,measurement)); + var value = accessor.GetPropertyValue(entity, measurement); + + if (value != null) + { + Type tupleType = value.GetType(); + var tempValue = tupleType.Name.ToUpper() switch + { + "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), + _ => value + }; + + rowValues.Add(tempValue); + } + else + { + rowValues.Add(value); + } } //foreach (var measurement in tempColumnNames) @@ -613,15 +629,14 @@ namespace JiShe.CollectBus.IoTDB.Provider /// /// 获取设备元数据的列 /// - /// + /// /// - private List CollectColumnMetadata(Type type) + private List CollectColumnMetadata(ISourceEntityAccessor accessor) { var columns = new List(); - - foreach (var prop in type.GetProperties()) + + foreach (var prop in accessor.PropertyInfoList) { - string typeName = string.Empty; Type declaredType = prop.PropertyType; diff --git a/services/JiShe.CollectBus.Application.Contracts/DataChannels/IDataChannelManageService.cs b/services/JiShe.CollectBus.Application.Contracts/DataChannels/IDataChannelManageService.cs index 2b1d8b7..a126910 100644 --- a/services/JiShe.CollectBus.Application.Contracts/DataChannels/IDataChannelManageService.cs +++ b/services/JiShe.CollectBus.Application.Contracts/DataChannels/IDataChannelManageService.cs @@ -21,14 +21,13 @@ namespace JiShe.CollectBus.DataChannels /// 定时任务数据通道写入 /// /// - Task ScheduledMeterTaskWriterAsync(ChannelWriter>> _telemetryPacketInfoWriter, Tuple> dataItems); + Task ScheduledMeterTaskWriterAsync(ChannelWriter>> _telemetryPacketInfoWriter, ValueTuple> dataItems); /// /// 定时任务数据入库和Kafka推送通道 /// /// - Task ScheduledMeterTaskReadingAsync(ChannelReader>> _telemetryPacketInfoReader, - CancellationToken cancellationToken); + Task ScheduledMeterTaskReadingAsync(ChannelReader>> _telemetryPacketInfoReader ); #endregion } } diff --git a/services/JiShe.CollectBus.Application/CollectBusApplicationModule.cs b/services/JiShe.CollectBus.Application/CollectBusApplicationModule.cs index 592d7e5..ed86fd7 100644 --- a/services/JiShe.CollectBus.Application/CollectBusApplicationModule.cs +++ b/services/JiShe.CollectBus.Application/CollectBusApplicationModule.cs @@ -81,7 +81,7 @@ public class CollectBusApplicationModule : AbpModule //}).ConfigureAwait(false); //下发任务通道构建 - DataChannelManage.TaskDataChannel = Channel.CreateUnbounded>>(); + DataChannelManage.TaskDataChannel = Channel.CreateUnbounded>>(); //默认初始化表计信息 var dbContext = context.ServiceProvider.GetRequiredService(); diff --git a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManage.cs b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManage.cs index e1f3979..6a8eeed 100644 --- a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManage.cs +++ b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManage.cs @@ -13,6 +13,6 @@ namespace JiShe.CollectBus.DataChannels /// /// 下发任务通道 /// - public static Channel>> TaskDataChannel; + public static Channel>> TaskDataChannel; } } diff --git a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs index 26208a2..d6f9e04 100644 --- a/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs +++ b/services/JiShe.CollectBus.Application/DataChannels/DataChannelManageService.cs @@ -50,7 +50,7 @@ namespace JiShe.CollectBus.DataChannels /// 定时任务数据通道写入 /// /// - public async Task ScheduledMeterTaskWriterAsync(ChannelWriter>> _telemetryPacketInfoWriter, Tuple> dataItems) + public async Task ScheduledMeterTaskWriterAsync(ChannelWriter>> _telemetryPacketInfoWriter, ValueTuple> dataItems) { await _telemetryPacketInfoWriter.WriteAsync(dataItems); } @@ -61,47 +61,62 @@ namespace JiShe.CollectBus.DataChannels /// 定时任务数据入库和Kafka推送通道 /// public async Task ScheduledMeterTaskReadingAsync( - ChannelReader>> telemetryPacketInfoReader, - CancellationToken cancellationToken = default) + ChannelReader>> telemetryPacketInfoReader) { - const int BatchSize = 20000; // 修正批次大小 + const int BatchSize = 20000; const int EmptyWaitMilliseconds = 1000; var timeout = TimeSpan.FromSeconds(5); + var timer = Stopwatch.StartNew(); + long timeoutMilliseconds = 0; var metadata = await _dbProvider.GetMetadata(); try { - while (!cancellationToken.IsCancellationRequested) + while (true) { - var batchStopwatch = Stopwatch.StartNew(); - var batch = new List>>(); + var batch = new List>>(); + var canRead = telemetryPacketInfoReader.Count; + if (canRead <= 0) + { + if (timeoutMilliseconds > 0) + { + _logger.LogError($"{nameof(ScheduledMeterTaskReadingAsync)} 通道处理数据耗时{timeoutMilliseconds}毫秒"); + } + timeoutMilliseconds = 0; + //无消息时短等待1秒 + await Task.Delay(EmptyWaitMilliseconds); + continue; + } + + timer.Restart(); + var startTime = DateTime.Now; try { // 异步批量读取数据 - while (batch.Count < BatchSize && batchStopwatch.Elapsed < timeout) + while (batch != null && batch.Count < BatchSize && (DateTime.Now - startTime) < timeout) { - while (telemetryPacketInfoReader.TryRead(out var data)) + try { - batch.Add(data); - if (batch.Count >= BatchSize) break; + if (telemetryPacketInfoReader.TryRead(out var dataItem)) + { + batch.Add(dataItem); + } + } + catch (Exception) + { + throw; } - - if (batch.Count >= BatchSize) break; - - // 无更多数据时等待 - if (!await telemetryPacketInfoReader.WaitToReadAsync(cancellationToken)) - break; } } - catch (OperationCanceledException) + catch (Exception) { - break; + throw; } if (batch.Count == 0) { - await Task.Delay(EmptyWaitMilliseconds, cancellationToken); + await Task.Delay(EmptyWaitMilliseconds); continue; } @@ -135,12 +150,16 @@ namespace JiShe.CollectBus.DataChannels } catch (Exception ex) { - _logger.LogError(ex, "处理主题 {TopicName} 数据时发生异常", topicName); + _logger.LogError(ex, "数据通道处理主题 {TopicName} 数据时发生异常", topicName); } } - _logger.LogInformation("处理完成批次: {Count} 条, 耗时: {Elapsed}ms", - batch.Count, batchStopwatch.ElapsedMilliseconds); + batch.Clear(); + timer.Stop(); + + timeoutMilliseconds = timeoutMilliseconds + timer.ElapsedMilliseconds; + + startTime = DateTime.Now; } } catch (Exception ex) @@ -179,7 +198,7 @@ namespace JiShe.CollectBus.DataChannels } } } - + } } diff --git a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs index ef3b894..17c8a6e 100644 --- a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs +++ b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -175,7 +175,8 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS public async Task TestTreeModelSingleMeasuringEntity(string measuring, string value, DateTime time) { time = DateTime.Now; - + //System.Reflection.PropertyInfo; + //System.Reflection.FieldInfo var meter = new TreeModelSingleMeasuringEntity() { SystemName = "energy", diff --git a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs index 47b8a99..32a1d7c 100644 --- a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs +++ b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs @@ -160,7 +160,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"电表自动校时 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); }); } else if (string.Equals(currentTimeStr, _applicationOptions.AutomaticTerminalVersionTime, StringComparison.CurrentCultureIgnoreCase))//集中器版本号读取 @@ -177,7 +177,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"集中器 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); }); } else if (string.Equals(currentTimeStr, _applicationOptions.AutomaticTelematicsModuleTime, StringComparison.CurrentCultureIgnoreCase))//SIM卡读取 @@ -194,7 +194,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"集中器 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); }); } else if (string.Equals(currentTimeStr, _applicationOptions.AutomaticTelematicsModuleTime, StringComparison.CurrentCultureIgnoreCase))//月冻结 @@ -211,7 +211,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"电表 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); }); } else if (string.Equals(currentTimeStr, _applicationOptions.AutomaticDayFreezeTime, StringComparison.CurrentCultureIgnoreCase))//日冻结 @@ -228,7 +228,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"电表 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerOtherIssuedEventName, tempTask)); }); } else @@ -262,7 +262,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading //_logger.LogWarning($"电表 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerFifteenMinuteIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerFifteenMinuteIssuedEventName, tempTask)); }); } else if (meteryType == MeterTypeEnum.WaterMeter.ToString()) @@ -281,7 +281,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"水表 {data.Name} 任务数据构建失败:{data.Serialize()}"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.WatermeterSubscriberWorkerAutoReadingIssuedEventName, tempTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.WatermeterSubscriberWorkerAutoReadingIssuedEventName, tempTask)); }); } else @@ -307,7 +307,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading _logger.LogWarning($"{nameof(AmmeterScheduledAutoValveControl)}电表定时阀控没有可操作的任务"); return; } - _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, Tuple.Create(ProtocolConst.AmmeterSubscriberWorkerAutoValveControlIssuedEventName, autoValveControlTask)); + _ = _dataChannelManage.ScheduledMeterTaskWriterAsync(DataChannelManage.TaskDataChannel.Writer, (ProtocolConst.AmmeterSubscriberWorkerAutoValveControlIssuedEventName, autoValveControlTask)); } #region 电表采集处理 @@ -329,10 +329,12 @@ namespace JiShe.CollectBus.ScheduledMeterReading /// public virtual async Task InitAmmeterCacheData(string gatherCode = "") { - // 创建取消令牌源 - var cts = new CancellationTokenSource(); + return; - _ = _dataChannelManage.ScheduledMeterTaskReadingAsync(DataChannelManage.TaskDataChannel.Reader, cts.Token); + // 创建取消令牌源 + //var cts = new CancellationTokenSource(); + + _ = _dataChannelManage.ScheduledMeterTaskReadingAsync(DataChannelManage.TaskDataChannel.Reader ); //此处代码不要删除 #if DEBUG diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs new file mode 100644 index 0000000..a45f4c2 --- /dev/null +++ b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace JiShe.CollectBus.Analyzers.Shared +{ + /// + /// 实体成员信息 + /// + public sealed class EntityMemberInfo + { + public string Path { get; set; } + public Type Type { get; set; } + private readonly Func _getter; + private readonly Action _setter; + + public EntityMemberInfo( + string path, + Type type, + Func getter, + Action setter) + { + Path = path; + Type = type; + _getter = getter; + _setter = setter; + } + + public object GetValue(object entity) => _getter(entity); + public void SetValue(object entity, object value) => _setter(entity, value); + } +} From db7384ae74a4e61acf4266395339bb70f787e1e8 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 11:17:43 +0800 Subject: [PATCH 08/15] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=A2=9E=E9=87=8F?= =?UTF-8?q?=E6=BA=90=E7=A0=81=E7=94=9F=E6=88=90=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 164 ++++++++---------- .../Provider/IoTDBProvider.cs | 34 ++-- .../Samples/SampleAppService.cs | 2 +- .../Ammeters/ElectricityMeterTreeModel.cs | 4 +- .../ISourceEntityAccessor.cs | 2 +- 5 files changed, 96 insertions(+), 110 deletions(-) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index befb833..2f943d8 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -2,6 +2,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; @@ -105,7 +106,7 @@ namespace JiShe.CollectBus.IncrementalGenerator Location.None)); continue; } - + var code3 = BuildAccessorsForSourceEntity(classSymbol, compilation, processedTypes); context.AddSource($"{classSymbol.Name}Accessor.g.cs", code3); } @@ -113,7 +114,7 @@ namespace JiShe.CollectBus.IncrementalGenerator // 生成工厂注册代码 context.AddSource("SourceEntityAccessorFactory.g.cs", BuildFactoryCode()); } - + /// /// 获取泛型参数 /// @@ -125,8 +126,8 @@ namespace JiShe.CollectBus.IncrementalGenerator var parameters = symbol.TypeParameters.Select(t => t.Name); return $"<{string.Join(", ", parameters)}>"; } - - + + /// /// 生成标准属性的访问器 /// @@ -143,7 +144,7 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($" public static void Set{prop.Name}({parentType} obj, {propType.ToDisplayString()} value) => obj.{prop.Name} = value;"); } } - + /// /// 构建实体访问器代码(支持泛型) @@ -179,21 +180,22 @@ namespace JiShe.CollectBus.IncrementalGenerator $": ISourceEntityAccessor<{classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>"); code.AppendLine("{"); - + var propList = GetAllPropertiesInHierarchy(classSymbol); foreach (var prop in propList) { // 安全类型转换 if (prop.Type is not ITypeSymbol propType) continue; + + if (propType is INamedTypeSymbol namedType) + { + GenerateStandardAccessors(prop, namedType, code); + } if (propType is INamedTypeSymbol { IsTupleType: true } tupleType) { - GenerateTupleAccessors(prop, tupleType, code, classSymbol); - } - else if (propType is INamedTypeSymbol namedType) - { - GenerateStandardAccessors(prop, namedType, code); + GenerateTupleAccessors(prop, tupleType, code); } } @@ -201,70 +203,57 @@ namespace JiShe.CollectBus.IncrementalGenerator GeneratePropertyListForSourceEntity(propList, code, compilation, classSymbol); //生成当前类属性信息集合 - GeneratePropertyInfoListForSourceEntity( - propList, - code, - compilation, - classSymbol); + GenerateEntityMemberInfoList(propList, code, compilation, classSymbol); //生成当前类属性访问 - GetGeneratePropertyValueForSourceEntity( - propList, - code, - compilation, - classSymbol); + GetGeneratePropertyValueForSourceEntity(propList, code, compilation, classSymbol); //生成当前类属性设置 - SetGeneratePropertyValueForSourceEntity( - propList, - code, - compilation, - classSymbol); - + SetGeneratePropertyValueForSourceEntity(propList, code, compilation, classSymbol); + code.AppendLine("}"); return code.ToString(); } - /// - /// 生成泛型ValueTuple 元组访问器 - /// private static void GenerateTupleAccessors( - IPropertySymbol prop, - INamedTypeSymbol tupleType, - StringBuilder code, - INamedTypeSymbol classSymbol) + IPropertySymbol prop, + INamedTypeSymbol tupleType, + StringBuilder code) { - var parentType = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var parentType = prop.ContainingType.ToDisplayString(); var tupleElements = tupleType.TupleElements; for (int i = 0; i < tupleElements.Length; i++) { var element = tupleElements[i]; - var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementType = element.Type.ToDisplayString(); var elementName = element.Name; - // Getter保持不变 - code.AppendLine( - $" public static {elementType} Get{prop.Name}_{elementName}" + - $"({parentType} obj) => obj.{prop.Name}.{elementName};"); + // Getter + code.AppendLine($"public static {elementType} Get{prop.Name}_{elementName}({parentType} obj) => obj.{prop.Name}.{elementName};"); - // Setter修复:使用元组字面量 + // Setter if (prop.SetMethod != null) { - var valueExpressions = tupleElements.Select((e, idx) => - idx == i ? "value" : $"obj.{prop.Name}.{e.Name}" - ).ToList(); - - // 关键修复:生成正确的元组字面量表达式 - code.AppendLine( - $" public static void Set{prop.Name}_{elementName}" + - $"({parentType} obj, {elementType} value) => " + - $"obj.{prop.Name} = ({string.Join(", ", valueExpressions)});"); + code.AppendLine($"public static void Set{prop.Name}_{elementName}({parentType} obj, {elementType} value) => obj.{prop.Name} = ({string.Join(", ", GetTupleElements(prop.Name, tupleElements, i))});"); } } } + private static IEnumerable GetTupleElements( + string propName, + ImmutableArray elements, + int targetIndex) + { + for (int i = 0; i < elements.Length; i++) + { + yield return i == targetIndex + ? "value" + : $"obj.{propName}.{elements[i].Name}"; + } + } + /// /// 处理System.Tuple类型的访问器生成 /// @@ -370,6 +359,10 @@ namespace JiShe.CollectBus.IncrementalGenerator foreach (var prop in propList) { + code.AppendLine( + $" \"{prop.Name}\" => " + + $"Get{prop.Name}(targetEntity),"); + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) @@ -379,12 +372,7 @@ namespace JiShe.CollectBus.IncrementalGenerator $"Get{prop.Name}_{element.Name}(targetEntity),"); } } - else - { - code.AppendLine( - $" \"{prop.Name}\" => " + - $"Get{prop.Name}(targetEntity),"); - } + } code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); @@ -412,6 +400,12 @@ namespace JiShe.CollectBus.IncrementalGenerator foreach (var prop in propList) { + var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + code.AppendLine($" case \"{prop.Name}\":"); + code.AppendLine($" Set{prop.Name}("); + code.AppendLine($" targetEntity, ({propType})value);"); + code.AppendLine(" break;"); + if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) @@ -422,15 +416,7 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($" targetEntity, ({elementType})value);"); code.AppendLine(" break;"); } - } - else if (prop.SetMethod != null) - { - var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - code.AppendLine($" case \"{prop.Name}\":"); - code.AppendLine($" Set{prop.Name}("); - code.AppendLine($" targetEntity, ({propType})value);"); - code.AppendLine(" break;"); - } + } } code.AppendLine(" default:"); @@ -458,7 +444,7 @@ namespace JiShe.CollectBus.IncrementalGenerator foreach (var prop in propList) { if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) - { + { foreach (var element in tupleType.TupleElements) { tempPropList.Add($"\"{prop.Name}.{element.Name}\""); @@ -477,52 +463,52 @@ namespace JiShe.CollectBus.IncrementalGenerator /// - /// 生成当前类属性信息集合(支持嵌套元组) + /// 生成当前类属性信息集合 /// - private static void GeneratePropertyInfoListForSourceEntity( + private static void GenerateEntityMemberInfoList( IEnumerable propList, StringBuilder code, Compilation compilation, INamedTypeSymbol classSymbol) { - code.AppendLine(" public List PropertyInfoList { get; } = new List"); + code.AppendLine(" public List MemberList { get; } = new()"); code.AppendLine(" {"); var initializerLines = new List(); - + var index = 0; foreach (var prop in propList) { - AddPropertyInitializer(classSymbol, prop, initializerLines); + var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var parentType = prop.ContainingType.ToDisplayString(); + // 主属性 + initializerLines.Add( + $"new EntityMemberInfo(" + + $"\"{prop.Name}\", " + + $"typeof({parentType}), " + + $"(e) => Get{prop.Name}(({parentType})e), " + + $"(e, v) => Set{prop.Name}(({parentType})e, ({propType})v))"); + // 元组元素 if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) { - //使用GetField代替GetProperty - var tupleTypeName = tupleType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var elementName = element.Name; + initializerLines.Add( - $"typeof({tupleTypeName}).GetField(\"{element.Name}\") ?? " + - $"throw new InvalidOperationException(\"Tuple field {element.Name} not found\")"); + $"new EntityMemberInfo(" + + $"\"{prop.Name}.{elementName}\", " + + $"typeof({elementType}), " + + $"(e) => Get{prop.Name}_{elementName}(({parentType})e), " + + $"(e, v) => Set{prop.Name}_{elementName}(({parentType})e, ({elementType})v))"); } } } code.AppendLine(string.Join(",\n", initializerLines)); code.AppendLine(" };"); - } - - private static void AddPropertyInitializer( - INamedTypeSymbol classSymbol, - IPropertySymbol prop, - List initializerLines) - { - var classType = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - initializerLines.Add( - $"typeof({classType}).GetProperty(\"{prop.Name}\", " + - "System.Reflection.BindingFlags.Public | " + - "System.Reflection.BindingFlags.Instance) ?? " + - $"throw new InvalidOperationException(\"Property {prop.Name} not found\")"); - } + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index 83040fe..0047122 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -635,11 +635,11 @@ namespace JiShe.CollectBus.IoTDB.Provider { var columns = new List(); - foreach (var prop in accessor.PropertyInfoList) + foreach (var prop in accessor.MemberList) { string typeName = string.Empty; - Type declaredType = prop.PropertyType; + Type declaredType = prop.Type; // 处理可空类型 if (declaredType.IsGenericType && declaredType.GetGenericTypeDefinition() == typeof(Nullable<>)) { @@ -652,25 +652,25 @@ namespace JiShe.CollectBus.IoTDB.Provider } //先获取Tag标签和属性标签 - ColumnInfo? column = prop.GetCustomAttribute() is not null ? new ColumnInfo( - name: prop.Name, + ColumnInfo? column = declaredType.GetCustomAttribute() is not null ? new ColumnInfo( + name: prop.Path, category: ColumnCategory.TAG, dataType: GetDataTypeFromTypeName(typeName), false - ) : prop.GetCustomAttribute() is not null ? new ColumnInfo( - prop.Name, + ) : declaredType.GetCustomAttribute() is not null ? new ColumnInfo( + prop.Path, ColumnCategory.ATTRIBUTE, GetDataTypeFromTypeName(typeName), false - ) : prop.GetCustomAttribute() is not null ? new ColumnInfo( - prop.Name, + ) : declaredType.GetCustomAttribute() is not null ? new ColumnInfo( + prop.Path, ColumnCategory.FIELD, GetDataTypeFromTypeName(typeName), false) : null; //最先检查是不是单侧点模式 - SingleMeasuringAttribute singleMeasuringAttribute = prop.GetCustomAttribute(); + SingleMeasuringAttribute singleMeasuringAttribute = declaredType.GetCustomAttribute(); if (singleMeasuringAttribute != null && column == null) { @@ -679,15 +679,15 @@ namespace JiShe.CollectBus.IoTDB.Provider //只有一个Filed字段。 //MeasuringName 默认为 SingleMeasuringAttribute.FieldName,以便于在获取对应的Value的时候重置为 Item1 的值。 - Type tupleType = prop.PropertyType; - Type[] tupleArgs = tupleType.GetGenericArguments(); + //Type tupleType = prop.PropertyType; + //Type[] tupleArgs = tupleType.GetGenericArguments(); - column = new ColumnInfo( - singleMeasuringAttribute.FieldName, - ColumnCategory.FIELD, - GetDataTypeFromTypeName(tupleArgs[1].Name), - true - ); + //column = new ColumnInfo( + // singleMeasuringAttribute.FieldName, + // ColumnCategory.FIELD, + // GetDataTypeFromTypeName(tupleArgs[1].Name), + // true + //); } if (column.HasValue) diff --git a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs index 17c8a6e..e395160 100644 --- a/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs +++ b/services/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -75,7 +75,7 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS //ElectricityMeterTreeModelAccessor. //TableModelSingleMeasuringEntityExtension - //TableModelSingleMeasuringEntityAccessor.GetSystemName(meter); + //TableModelSingleMeasuringEntityAccessor.GetSystemName(meter); await _iotDBProvider.InsertAsync(meter); } diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs index 38d3ee6..982c144 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs @@ -32,11 +32,11 @@ namespace JiShe.CollectBus.Ammeters public double Current { get; set; } [FIELDColumn] - public double Power => Voltage * Current; + public double Power { get; set; } [FIELDColumn] public double? Currentd { get; set; } - public Tuple TupleData { get; set;} + public ValueTuple TupleData { get; set; } } } diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index 5e67826..79df535 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -31,6 +31,6 @@ namespace JiShe.CollectBus.Analyzers.Shared /// /// 属性信息集合 /// - List PropertyInfoList { get; } + List MemberList { get; } } } From c03207aa21a93db445d6e5e57394e83524e108f3 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 14:42:13 +0800 Subject: [PATCH 09/15] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=A2=9E=E9=87=8F?= =?UTF-8?q?=E6=BA=90=E7=A0=81=E7=94=9F=E6=88=90=E5=99=A8=E5=92=8CIoTDB?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 135 +++++++++++-- .../ATTRIBUTEColumnAttribute.cs | 2 +- .../EntityTypeAttribute.cs | 2 +- .../FIELDColumnAttribute.cs | 2 +- .../SingleMeasuringAttribute.cs | 2 +- .../TAGColumnAttribute.cs | 2 +- .../TableNameOrTreePathAttribute.cs | 2 +- .../JiShe.CollectBus.IoTDB/Model/IoTEntity.cs | 2 +- .../Model/TableModelSingleMeasuringEntity.cs | 2 +- .../Model/TreeModelSingleMeasuringEntity.cs | 2 +- .../Provider/IoTDBProvider.cs | 185 ++++++++++-------- .../Ammeters/ElectricityMeter.cs | 6 +- .../Ammeters/ElectricityMeterTreeModel.cs | 2 +- .../MeterReadingTelemetryPacketInfo.cs | 2 +- .../EntityMemberInfo.cs | 45 +++-- .../ISourceEntityAccessor.cs | 5 + 16 files changed, 276 insertions(+), 122 deletions(-) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/ATTRIBUTEColumnAttribute.cs (83%) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/EntityTypeAttribute.cs (90%) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/FIELDColumnAttribute.cs (82%) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/SingleMeasuringAttribute.cs (91%) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/TAGColumnAttribute.cs (82%) rename modules/JiShe.CollectBus.IoTDB/{Attribute => Attributes}/TableNameOrTreePathAttribute.cs (92%) diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 2f943d8..15179af 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -183,6 +183,9 @@ namespace JiShe.CollectBus.IncrementalGenerator var propList = GetAllPropertiesInHierarchy(classSymbol); + //类名称 + code.AppendLine($" public string EntityName {{get;}} = \"{classSymbol.Name}\";"); + foreach (var prop in propList) { // 安全类型转换 @@ -216,6 +219,12 @@ namespace JiShe.CollectBus.IncrementalGenerator return code.ToString(); } + /// + /// 生成ValueTuple元组属性访问器 + /// + /// + /// + /// private static void GenerateTupleAccessors( IPropertySymbol prop, INamedTypeSymbol tupleType, @@ -291,7 +300,7 @@ namespace JiShe.CollectBus.IncrementalGenerator } } } - + /// /// 增强的工厂类实现 /// @@ -466,30 +475,48 @@ namespace JiShe.CollectBus.IncrementalGenerator /// 生成当前类属性信息集合 /// private static void GenerateEntityMemberInfoList( - IEnumerable propList, - StringBuilder code, - Compilation compilation, - INamedTypeSymbol classSymbol) + IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) { - code.AppendLine(" public List MemberList { get; } = new()"); + code.AppendLine(" public List MemberList { get; } = new()"); code.AppendLine(" {"); var initializerLines = new List(); - var index = 0; foreach (var prop in propList) { var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); var parentType = prop.ContainingType.ToDisplayString(); - // 主属性 - initializerLines.Add( + + // 处理主属性 + var propAttributes = prop.GetAttributes() + .Where(a => !IsCompilerGeneratedAttribute(a)) + .ToList(); + + var attributeInitializers = propAttributes + .Select(GenerateAttributeInitializer) + .Where(s => !string.IsNullOrEmpty(s)); + + var mainMember = new StringBuilder(); + mainMember.Append( $"new EntityMemberInfo(" + $"\"{prop.Name}\", " + - $"typeof({parentType}), " + + $"typeof({propType}), " + $"(e) => Get{prop.Name}(({parentType})e), " + $"(e, v) => Set{prop.Name}(({parentType})e, ({propType})v))"); - // 元组元素 + if (attributeInitializers.Any()) + { + mainMember.AppendLine(); + mainMember.Append(" { CustomAttributes = new List"); + mainMember.Append($" {{ {string.Join(", ", attributeInitializers)} }} }}"); + } + + initializerLines.Add(mainMember.ToString()); + + // 处理元组元素(假设不需要处理元组元素的特性) if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) @@ -509,6 +536,90 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine(string.Join(",\n", initializerLines)); code.AppendLine(" };"); - } + } + + + private static string GenerateAttributeInitializer(AttributeData attribute) + { + if (attribute.AttributeClass == null) + return string.Empty; + + var attributeClass = attribute.AttributeClass.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var args = attribute.ConstructorArguments; + var namedArgs = attribute.NamedArguments; + + var parameters = new List(); + foreach (var arg in args) + { + parameters.Add(ConvertTypedConstantToCode(arg)); + } + + var constructorArgs = string.Join(", ", parameters); + + var initializer = new StringBuilder(); + initializer.Append($"new {attributeClass}({constructorArgs})"); + + if (namedArgs.Any()) + { + initializer.Append(" { "); + var namedArgsList = namedArgs.Select(n => $"{n.Key} = {ConvertTypedConstantToCode(n.Value)}"); + initializer.Append(string.Join(", ", namedArgsList)); + initializer.Append(" }"); + } + + return initializer.ToString(); + } + + private static string ConvertTypedConstantToCode(TypedConstant constant) + { + if (constant.IsNull) + return "null"; + + switch (constant.Kind) + { + case TypedConstantKind.Array: + var elements = constant.Values.Select(ConvertTypedConstantToCode); + return $"new[] {{ {string.Join(", ", elements)} }}"; + case TypedConstantKind.Type: + var typeSymbol = (ITypeSymbol)constant.Value!; + return $"typeof({typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)})"; + case TypedConstantKind.Enum: + return ConvertEnumTypedConstant(constant); + default: + return ConvertPrimitiveConstant(constant); + } + } + + private static string ConvertEnumTypedConstant(TypedConstant constant) + { + var enumType = constant.Type!; + var enumValue = constant.Value!; + var enumTypeName = enumType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + + foreach (var member in enumType.GetMembers().OfType()) + { + if (member.ConstantValue != null && member.ConstantValue.Equals(enumValue)) + return $"{enumTypeName}.{member.Name}"; + } + + return $"({enumTypeName})({enumValue})"; + } + + private static string ConvertPrimitiveConstant(TypedConstant constant) + { + var value = constant.Value!; + return value switch + { + string s => $"\"{s}\"", + char c => $"'{c}'", + bool b => b ? "true" : "false", + _ => value.ToString() + }; + } + + private static bool IsCompilerGeneratedAttribute(AttributeData attribute) + { + return attribute.AttributeClass?.ToDisplayString() == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"; + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/ATTRIBUTEColumnAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/ATTRIBUTEColumnAttribute.cs similarity index 83% rename from modules/JiShe.CollectBus.IoTDB/Attribute/ATTRIBUTEColumnAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/ATTRIBUTEColumnAttribute.cs index d188c36..7ef13f3 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/ATTRIBUTEColumnAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/ATTRIBUTEColumnAttribute.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// Column分类标记特性(ATTRIBUTE字段),也就是属性字段 diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/EntityTypeAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs similarity index 90% rename from modules/JiShe.CollectBus.IoTDB/Attribute/EntityTypeAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs index 3610c00..89a4e38 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/EntityTypeAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs @@ -1,6 +1,6 @@ using JiShe.CollectBus.IoTDB.Enums; -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// IoTDB实体类型特性 diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/FIELDColumnAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/FIELDColumnAttribute.cs similarity index 82% rename from modules/JiShe.CollectBus.IoTDB/Attribute/FIELDColumnAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/FIELDColumnAttribute.cs index 7cabdf4..43d699f 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/FIELDColumnAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/FIELDColumnAttribute.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// Column分类标记特性(FIELD字段),数据列字段 diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/SingleMeasuringAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/SingleMeasuringAttribute.cs similarity index 91% rename from modules/JiShe.CollectBus.IoTDB/Attribute/SingleMeasuringAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/SingleMeasuringAttribute.cs index 5f0ca07..481bfa2 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/SingleMeasuringAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/SingleMeasuringAttribute.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// 用于标识当前实体为单侧点模式,单侧点模式只有一个Filed标识字段,类型是Tuple,Item1=>测点名称,Item2=>测点值,泛型 diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/TAGColumnAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/TAGColumnAttribute.cs similarity index 82% rename from modules/JiShe.CollectBus.IoTDB/Attribute/TAGColumnAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/TAGColumnAttribute.cs index 6f40a47..48a3830 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/TAGColumnAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/TAGColumnAttribute.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// Column分类标记特性(TAG字段),标签字段 diff --git a/modules/JiShe.CollectBus.IoTDB/Attribute/TableNameOrTreePathAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs similarity index 92% rename from modules/JiShe.CollectBus.IoTDB/Attribute/TableNameOrTreePathAttribute.cs rename to modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs index 1b4f4f0..ba0ca12 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attribute/TableNameOrTreePathAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs @@ -1,6 +1,6 @@ using JiShe.CollectBus.IoTDB.Enums; -namespace JiShe.CollectBus.IoTDB.Attribute +namespace JiShe.CollectBus.IoTDB.Attributes { /// /// IoTDB实体存储路径或表名称,一般用于已经明确的存储路径或表名称,例如日志存储 diff --git a/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs index 48bc248..40403ed 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs @@ -1,5 +1,5 @@ using JiShe.CollectBus.Common.Attributes; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; namespace JiShe.CollectBus.IoTDB.Model { diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs index ed0fd4d..a5c98cf 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs @@ -1,5 +1,5 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Enums; namespace JiShe.CollectBus.IoTDB.Model diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs index c87516c..6244cdf 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs @@ -1,5 +1,5 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Enums; namespace JiShe.CollectBus.IoTDB.Model diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index 0047122..c88403f 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -12,7 +12,7 @@ using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Context; using JiShe.CollectBus.IoTDB.Interface; using JiShe.CollectBus.IoTDB.Model; @@ -213,7 +213,7 @@ namespace JiShe.CollectBus.IoTDB.Provider var query = await BuildQuerySQL(options); var sessionDataSet = await CurrentSession.ExecuteQueryStatementAsync(query); - + _logger.LogWarning($"{nameof(QueryAsync)} 主题的任务 {options.TableNameOrTreePath} 路径批次{options.PageIndex}任务数据读取完成,共消耗{stopwatch2.ElapsedMilliseconds}毫秒。"); var result = new BusPagedResult { @@ -319,71 +319,71 @@ namespace JiShe.CollectBus.IoTDB.Provider } } - //foreach (var measurement in tempColumnNames) - //{ + //foreach (var measurement in tempColumnNames) + //{ - // PropertyInfo propertyInfo = typeof(T).GetProperty(measurement); - // if (propertyInfo == null) - // { - // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,没有找到{measurement}属性,属于异常情况,-101。"); - // } + // PropertyInfo propertyInfo = typeof(T).GetProperty(measurement); + // if (propertyInfo == null) + // { + // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,没有找到{measurement}属性,属于异常情况,-101。"); + // } - // var value = propertyInfo.GetValue(entity); - // if (propertyInfo.IsDefined(typeof(SingleMeasuringAttribute), false) && metadata.IsSingleMeasuring == true)//表示当前对象是单测点模式 - // { - // if (value != null) - // { - // Type tupleType = value.GetType(); - // Type[] tupleArgs = tupleType.GetGenericArguments(); - // Type item2Type = tupleArgs[1]; // T 的实际类型 - // var item1 = tupleType.GetProperty("Item1")!.GetValue(value); - // var item2 = tupleType.GetProperty("Item2")!.GetValue(value); - // if (item1 == null || item2 == null) - // { - // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,单测点模式构建失败,没有获取测点名称或者测点值,-102。"); - // } + // var value = propertyInfo.GetValue(entity); + // if (propertyInfo.IsDefined(typeof(SingleMeasuringAttribute), false) && metadata.IsSingleMeasuring == true)//表示当前对象是单测点模式 + // { + // if (value != null) + // { + // Type tupleType = value.GetType(); + // Type[] tupleArgs = tupleType.GetGenericArguments(); + // Type item2Type = tupleArgs[1]; // T 的实际类型 + // var item1 = tupleType.GetProperty("Item1")!.GetValue(value); + // var item2 = tupleType.GetProperty("Item2")!.GetValue(value); + // if (item1 == null || item2 == null) + // { + // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,单测点模式构建失败,没有获取测点名称或者测点值,-102。"); + // } - // var indexOf = metadata.ColumnNames.IndexOf(measurement); - // metadata.ColumnNames[indexOf] = (string)item1!; + // var indexOf = metadata.ColumnNames.IndexOf(measurement); + // metadata.ColumnNames[indexOf] = (string)item1!; - // rowValues.Add(item2); - // } - // else - // { - // rowValues.Add(null); - // } + // rowValues.Add(item2); + // } + // else + // { + // rowValues.Add(null); + // } - // //同时如果是单测点模式,且是table模型存储,路径只能通过DevicePathBuilder.GetDeviceTableName(entity)获取 - // if (_runtimeContext.UseTableSessionPool) - // { - // tableNameOrTreePath = DevicePathBuilder.GetDeviceTableName(entity); - // } - // } - // else - // { + // //同时如果是单测点模式,且是table模型存储,路径只能通过DevicePathBuilder.GetDeviceTableName(entity)获取 + // if (_runtimeContext.UseTableSessionPool) + // { + // tableNameOrTreePath = DevicePathBuilder.GetDeviceTableName(entity); + // } + // } + // else + // { - // //需要根据value的类型,进行相应的值映射转换,例如datetime转换为long的时间戳值 - // if (value != null) - // { - // Type tupleType = value.GetType(); - // var tempValue = tupleType.Name.ToUpper() switch - // { - // "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), - // _ => value - // }; + // //需要根据value的类型,进行相应的值映射转换,例如datetime转换为long的时间戳值 + // if (value != null) + // { + // Type tupleType = value.GetType(); + // var tempValue = tupleType.Name.ToUpper() switch + // { + // "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), + // _ => value + // }; - // rowValues.Add(tempValue); - // } - // else - // { - // rowValues.Add(value); - // } + // rowValues.Add(tempValue); + // } + // else + // { + // rowValues.Add(value); + // } - // } + // } - //} + //} - values.Add(rowValues); + values.Add(rowValues); //如果指定了路径 if (!string.IsNullOrWhiteSpace(tableNameOrTreePath)) @@ -634,44 +634,57 @@ namespace JiShe.CollectBus.IoTDB.Provider private List CollectColumnMetadata(ISourceEntityAccessor accessor) { var columns = new List(); - - foreach (var prop in accessor.MemberList) - { - string typeName = string.Empty; - Type declaredType = prop.Type; + foreach (var member in accessor.MemberList) + { + //元组的子项字段详情不处理。 + if (member.NameOrPath.Contains(".Item")) + { + continue; + } + + string declaredTypeName = string.Empty; + + Type declaredType = member.DeclaredType;//属性的类型,如string,int等 + // 处理可空类型 if (declaredType.IsGenericType && declaredType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type underlyingType = Nullable.GetUnderlyingType(declaredType); - typeName = underlyingType.Name; + declaredTypeName = underlyingType.Name; } else { - typeName = declaredType.Name; + declaredTypeName = member.NameOrPath; } + + var tagAttr = member.CustomAttributes?.OfType().FirstOrDefault(); + var attrColumn = member.CustomAttributes?.OfType().FirstOrDefault(); + var fieldColumn = member.CustomAttributes?.OfType().FirstOrDefault(); + + //判断是否是单测数据 + var singleMeasuringAttribute = member.CustomAttributes?.OfType().FirstOrDefault(); + //先获取Tag标签和属性标签 - ColumnInfo? column = declaredType.GetCustomAttribute() is not null ? new ColumnInfo( - name: prop.Path, + ColumnInfo? column = tagAttr != null ? new ColumnInfo( + name: member.NameOrPath, category: ColumnCategory.TAG, - dataType: GetDataTypeFromTypeName(typeName), + dataType: GetDataTypeFromTypeName(declaredTypeName), false - ) : declaredType.GetCustomAttribute() is not null ? new ColumnInfo( - prop.Path, + ) : attrColumn != null ? new ColumnInfo( + member.NameOrPath, ColumnCategory.ATTRIBUTE, - GetDataTypeFromTypeName(typeName), + GetDataTypeFromTypeName(declaredTypeName), false - ) : declaredType.GetCustomAttribute() is not null ? new ColumnInfo( - prop.Path, + ) : fieldColumn != null ? new ColumnInfo( + member.NameOrPath, ColumnCategory.FIELD, - GetDataTypeFromTypeName(typeName), + GetDataTypeFromTypeName(declaredTypeName), false) : null; - //最先检查是不是单侧点模式 - SingleMeasuringAttribute singleMeasuringAttribute = declaredType.GetCustomAttribute(); - + //检查是不是单侧点模式 if (singleMeasuringAttribute != null && column == null) { //warning: 单侧点模式注意事项 @@ -679,15 +692,19 @@ namespace JiShe.CollectBus.IoTDB.Provider //只有一个Filed字段。 //MeasuringName 默认为 SingleMeasuringAttribute.FieldName,以便于在获取对应的Value的时候重置为 Item1 的值。 - //Type tupleType = prop.PropertyType; - //Type[] tupleArgs = tupleType.GetGenericArguments(); + Type tupleType = accessor.MemberList.Where(d => d.NameOrPath == $"{member.NameOrPath}.Item2").FirstOrDefault()?.DeclaredType; - //column = new ColumnInfo( - // singleMeasuringAttribute.FieldName, - // ColumnCategory.FIELD, - // GetDataTypeFromTypeName(tupleArgs[1].Name), - // true - //); + if (tupleType == null) + { + throw new Exception($"{nameof(CollectColumnMetadata)} {accessor.EntityName} {member.NameOrPath} 属性解析异常"); + } + + column = new ColumnInfo( + member.NameOrPath, + ColumnCategory.FIELD, + GetDataTypeFromTypeName(tupleType.Name), + true + ); } if (column.HasValue) diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs index c04a554..ca1d0db 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs @@ -1,12 +1,12 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; namespace JiShe.CollectBus.Ammeters { [EntityType(EntityTypeEnum.TableModel)] - //[SourceAnalyzers] + [SourceAnalyzers] public class ElectricityMeter : IoTEntity { [ATTRIBUTEColumn] @@ -31,7 +31,7 @@ namespace JiShe.CollectBus.Ammeters public double Current { get; set; } [FIELDColumn] - public double Power => Voltage * Current; + public double Power { get; set; } [FIELDColumn] public double? Currentd { get; set; } diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs index 982c144..5fb6010 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs @@ -1,5 +1,5 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; using System; diff --git a/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs b/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs index 4b61e99..1d361be 100644 --- a/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs +++ b/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs @@ -1,5 +1,5 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attribute; +using JiShe.CollectBus.IoTDB.Attributes; using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; using System; diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs index a45f4c2..28520be 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs @@ -9,24 +9,45 @@ namespace JiShe.CollectBus.Analyzers.Shared /// public sealed class EntityMemberInfo { - public string Path { get; set; } - public Type Type { get; set; } - private readonly Func _getter; - private readonly Action _setter; + /// + /// 名称或者路径 + /// + public string NameOrPath { get; set; } + + /// + /// 声明的类型 + /// + public Type DeclaredType { get; set; } + + /// + /// 获取值 + /// + public Func Getter { get; } + + /// + /// 设置值 + /// + public Action Setter { get; } + + /// + /// 自定义Attribute集合 + /// + public List CustomAttributes { get; set; } + public EntityMemberInfo( - string path, - Type type, + string nameOrPath, + Type declaredType, Func getter, Action setter) { - Path = path; - Type = type; - _getter = getter; - _setter = setter; + NameOrPath = nameOrPath; + this.DeclaredType = declaredType; + Getter = getter; + Setter = setter; } - public object GetValue(object entity) => _getter(entity); - public void SetValue(object entity, object value) => _setter(entity, value); + public object GetValue(object entity) => Getter(entity); + public void SetValue(object entity, object value) => Setter(entity, value); } } diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index 79df535..a6256ab 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -7,6 +7,11 @@ namespace JiShe.CollectBus.Analyzers.Shared { public interface ISourceEntityAccessor { + /// + /// 实体类名称 + /// + string EntityName { get; } + /// /// 获取属性值 /// From 3488b0012a16fa23c156bc535c7fd51f35c01ded Mon Sep 17 00:00:00 2001 From: zenghongyao <873884283@qq.com> Date: Thu, 8 May 2025 15:12:37 +0800 Subject: [PATCH 10/15] =?UTF-8?q?=E8=A7=A3=E6=9E=90=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E4=BF=9D=E5=AD=98NULL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AFN_0CH/AFN12_F129_Analysis.cs | 30 ++++-- .../AFN_0CH/AFN12_F130_Analysis.cs | 27 ++++-- .../AFN_0CH/AFN12_F131_Analysis.cs | 29 ++++-- .../AFN_0CH/AFN12_F132_Analysis.cs | 32 +++++-- .../AFN_0CH/AFN12_F145_Analysis.cs | 26 ++++-- .../AFN_0CH/AFN12_F149_Analysis.cs | 15 +-- .../AFN_0CH/AFN12_F188_Analysis.cs | 20 ++-- .../AFN_0CH/AFN12_F25_Analysis.cs | 22 +++-- .../AFN_0CH/AFN12_F49_Analysis.cs | 23 +++-- .../AFN_0DH/AFN13_F100_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F101_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F102_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F103_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F104_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F105_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F106_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F107_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F108_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F11_Analysis.cs | 38 ++++---- .../AFN_0DH/AFN13_F145_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F146_Analysis.cs | 9 +- .../AFN_0DH/AFN13_F147_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F148_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F161_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F162_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F163_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F164_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F165_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F166_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F167_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F168_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F177_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F178_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F179_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F180_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F181_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F182_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F183_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F184_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F189_Analysis.cs | 12 +-- .../AFN_0DH/AFN13_F190_Analysis.cs | 44 ++++----- .../AFN_0DH/AFN13_F193_Analysis.cs | 37 ++++---- .../AFN_0DH/AFN13_F195_Analysis.cs | 37 ++++---- .../AFN_0DH/AFN13_F19_Analysis.cs | 37 ++++---- .../AnalysisData/AFN_0DH/AFN13_F3_Analysis.cs | 91 +++++++++---------- .../AnalysisData/AFN_0DH/AFN13_F4_Analysis.cs | 33 ++++--- .../AFN_0DH/AFN13_F81_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F82_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F83_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F84_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F85_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F86_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F87_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F88_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F89_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F90_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F91_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F92_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F93_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F94_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F95_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F97_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F98_Analysis.cs | 6 +- .../AFN_0DH/AFN13_F99_Analysis.cs | 6 +- .../AFN_10H/AFN16_F97_Analysis.cs | 21 +++-- .../AnalysisData/DataStorage.cs | 2 +- .../Protocol3761Extensions.cs | 82 ++++++++++------- .../Protocol3761/Dto/AnalysisBaseDto.cs | 8 +- .../Extensions/StringExtensions.cs | 4 +- .../Pages/Monitor.cshtml | 1 - 70 files changed, 520 insertions(+), 436 deletions(-) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F129_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F129_Analysis.cs index 4eb05ad..a7538ca 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F129_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F129_Analysis.cs @@ -33,7 +33,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); ArgumentNullException.ThrowIfNull(input.A.A3?.D1_D7); - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -48,7 +48,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH TimeDensity = 0 }; List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - List> list = GenerateFinalResult(2, datas, "正向有功电能示值", input.AFN_FC.AFN, input.DT.Fn); + List> list = GenerateFinalResult(2, datas, "正向有功电能示值", input.AFN_FC.AFN, input.DT.Fn); unitDataAnalysis.Data= list; result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); @@ -90,22 +90,32 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH } #endregion - public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) + public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - - decimal value = 0; + AnalysisBaseDto meter = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) + { + meter.ErrorCodeMsg= errorCode.Item2; meter.ValidData = false; + } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + meter.DataValue = value; + } meter.DataType = $"{afn.ToString().PadLeft(2, '0')}_{fn}_{i - index}"; - meter.TimeSpan = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"); + string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"; + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) + { + meter.TimeSpan = readingDate; + } meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; list.Add(meter); diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs index cce2df4..d67d8d1 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs @@ -31,8 +31,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - List> list = GenerateFinalResult(2, datas, "正向无功电能示值", input.AFN_FC.AFN, input.DT.Fn); - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + List> list = GenerateFinalResult(2, datas, "正向无功电能示值", input.AFN_FC.AFN, input.DT.Fn); + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -78,21 +78,30 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH } return values; } - public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) + public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto meter = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) + { + meter.ErrorCodeMsg = errorCode.Item2; meter.ValidData = false; + } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + meter.DataValue = value; + } meter.DataType = $"{afn.ToString().PadLeft(2, '0')}_{fn}_{i - index}"; - meter.TimeSpan = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"); + string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00" + if(DateTime.TryParse(timeSpan, out DateTime readingDate)) + meter.TimeSpan = readingDate; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; list.Add(meter); diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F131_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F131_Analysis.cs index 4cbb5b5..9b57ea1 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F131_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F131_Analysis.cs @@ -6,6 +6,8 @@ using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH { @@ -30,8 +32,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - List> list = GenerateFinalResult(2, datas, "反向有功总电能示值", input.AFN_FC.AFN, input.DT.Fn); - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + List> list = GenerateFinalResult(2, datas, "反向有功总电能示值", input.AFN_FC.AFN, input.DT.Fn); + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -78,21 +80,30 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH } return values; } - public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) + public List> GenerateFinalResult(int index, List data, string filedDesc = "", int afn = 0, int fn = 0) { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto meter = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) + { + meter.ErrorCodeMsg = errorCode.Item2; meter.ValidData = false; + } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + meter.DataValue = value; + } meter.DataType = $"{afn.ToString().PadLeft(2, '0')}_{fn}_{i - index}"; - meter.TimeSpan = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"); + string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"; + if(DateTime.TryParse(timeSpan, out DateTime readTime)) + meter.TimeSpan = readTime; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; list.Add(meter); diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F132_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F132_Analysis.cs index 59096de..70db824 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F132_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F132_Analysis.cs @@ -7,6 +7,7 @@ using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH { @@ -34,9 +35,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - - List> list = GenerateFinalResult(2, datas, "反向无功电能示值", dataType); - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + List> list = GenerateFinalResult(2, datas, "反向无功电能示值", dataType); + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -82,21 +82,33 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH } return values; } - public List> GenerateFinalResult(int index, List data, string dataType, string filedDesc = "") + public List> GenerateFinalResult(int index, List data, string dataType, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto meter = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) + { + meter.ErrorCodeMsg = errorCode.Item2; meter.ValidData = false; + } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + meter.DataValue = value; + } + meter.DataType = $"{dataType}_{i - index}"; - meter.TimeSpan = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"); + string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"; + if (DateTime.TryParse(timeSpan,out DateTime readingDate)) + { + meter.TimeSpan = readingDate; + } meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; list.Add(meter); diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F145_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F145_Analysis.cs index e0d143b..ecbaef0 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F145_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F145_Analysis.cs @@ -35,8 +35,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - AnalysisBaseDto data = GenerateFinalResult(datas, "当月正向有功最大需量及发生时间", dataType); - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + AnalysisBaseDto data = GenerateFinalResult(datas, "当月正向有功最大需量及发生时间", dataType); + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -96,19 +96,25 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH return values; } - public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc,string dataType) + public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc,string dataType) { - AnalysisBaseDto dto = new AnalysisBaseDto(); - - decimal value = 0; + AnalysisBaseDto dto = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[2].CheckErrorCode(); if (errorCode != null) + { + dto.ErrorCodeMsg = errorCode.Item2; dto.ValidData = false; + } else - decimal.TryParse(data[2], out value); - - dto.DataValue = value; - string timeSpan = $"{DateTime.Now.Year}-{data[3].Substring(0, 2)}-{data[3].Substring(2, 2)} {data[3].Substring(4, 2)}:{data[3].Substring(6, 2)}:00";//$"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)}"; + { + if(decimal.TryParse(data[2], out decimal value)) + dto.DataValue = value; + } + + string timeSpan = $"{DateTime.Now.Year}-{data[3].Substring(0, 2)}-{data[3].Substring(2, 2)} {data[3].Substring(4, 2)}:{data[3].Substring(6, 2)}:00"; if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { dto.TimeSpan = readingDate; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F149_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F149_Analysis.cs index 53b0e23..671e625 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F149_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F149_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH List datas = await AnalysisDataUnit(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - AnalysisBaseDto data = GenerateFinalResult(datas, dataType,"上月(上一结算日)正向有功最大需量及发生时间"); + AnalysisBaseDto data = GenerateFinalResult(datas, dataType,"上月(上一结算日)正向有功最大需量及发生时间"); // 查询电表信息 AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.DeviceType.ToString(), "15"); if (ammeterInfo != null) @@ -48,7 +48,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH data.DatabaseBusiID=ammeterInfo.DatabaseBusiID; data.DeviceAddress= ammeterInfo.AmmerterAddress; } - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -63,7 +63,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH DensityUnit = DensityUnit.Second, TimeDensity = 0 }; - await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -110,10 +110,12 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH } return values; } - public AnalysisBaseDto GenerateFinalResult(List data,string dataType, string filedDesc = "") + public AnalysisBaseDto GenerateFinalResult(List data,string dataType, string filedDesc = "") { - AnalysisBaseDto dto = new AnalysisBaseDto(); - + AnalysisBaseDto dto = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCodeInfo = data[2].CheckErrorCode(); if (errorCodeInfo != null) { @@ -133,7 +135,6 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH else { string timeSpan = $"{DateTime.Now.Year}-{data[3].Substring(0, 2)}-{data[3].Substring(2, 2)} {data[3].Substring(4, 2)}:{data[3].Substring(6, 2)}:00"; - //TODO:时间标 if (!DateTime.TryParse(timeSpan, out DateTime dataTime)) dto.ValidData = false; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F188_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F188_Analysis.cs index 5758459..e48cdc4 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F188_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F188_Analysis.cs @@ -6,6 +6,7 @@ using JiShe.CollectBus.Protocol.Dto; using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH { @@ -34,8 +35,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH ArgumentNullException.ThrowIfNull(input.AFN_FC.AFN); ArgumentNullException.ThrowIfNull(input.DT.Fn); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - AnalysisBaseDto data = GenerateFinalResult(input.UnitData.HexMessageList, dataType); - UnitDataAnalysis> dto = new UnitDataAnalysis> + AnalysisBaseDto data = GenerateFinalResult(input.UnitData.HexMessageList, dataType); + UnitDataAnalysis> dto = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -58,10 +59,12 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH } return await Task.FromResult(false); } - public AnalysisBaseDto GenerateFinalResult(List hexMessageList,string dataType) + public AnalysisBaseDto GenerateFinalResult(List hexMessageList,string dataType) { - AnalysisBaseDto dto = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto dto = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.WaterMeter + }; var arr = hexMessageList.GetRange(11, 4); var errorCodeInfo = arr.CheckErrorCode(); if (errorCodeInfo != null) @@ -70,9 +73,10 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH dto.ErrorCodeMsg = errorCodeInfo.Item2; } else - decimal.TryParse($"{arr[11]}{arr[12]}{arr[13]}.{arr[14]}", out value); - - dto.DataValue = value; + { + if (decimal.TryParse($"{arr[11]}{arr[12]}{arr[13]}.{arr[14]}", out decimal value)) + dto.DataValue = value; + } dto.DataType = dataType; dto.FiledDesc = "水示值"; dto.FiledName = dto.DataType.GetDataFieldByGatherDataType() ?? string.Empty; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F25_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F25_Analysis.cs index a58c574..4c754e3 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F25_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F25_Analysis.cs @@ -1,11 +1,14 @@ using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; +using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Protocol.Contracts.Protocol.Dto; using JiShe.CollectBus.Protocol.Dto; using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH { @@ -32,13 +35,15 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List remarks = new List() { "当前总有功功率", "当前A相有功功率", "当前B相有功功率", "当前C相有功功率", "当前总无功功率", "当前A相无功功率", "当前B相无功功率", "当前C相无功功率", "当前总功率因数", "当前A相功率因数", "当前B相功率因数", "当前C相功率因数", "当前A相电压", "当前B相电压", "当前C相电压", "当前A相电流", "当前C相电流", "当前 C相电流", "当前零序电流", "当前总视在功率", "当前A相视在功率", "当前B相视在功率", "当前C相视在功率" }; - List> list = new List>(); + List> list = new List>(); List data = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); for (int i = 1; i < data.Count; i++) { - AnalysisBaseDto dto = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto dto = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCodeInfo = data[i].CheckErrorCode(); if (errorCodeInfo != null) { @@ -46,15 +51,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH dto.ErrorCodeMsg = errorCodeInfo.Item2; } else - decimal.TryParse(data[i], out value); - dto.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + dto.DataValue = value; + } + dto.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}_{DataType[i-1]}"; - dto.FiledName = DataType[i - 1]; + dto.FiledName = DataType[i - 1].GetDataFieldByGatherDataType() ?? string.Empty; dto.TimeSpan = Convert.ToDateTime($"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"); dto.FiledDesc = remarks[i - 1]; list.Add(dto); } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs index b639f0d..c54d058 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs @@ -1,11 +1,13 @@ using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; +using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Protocol.Contracts.Protocol.Dto; using JiShe.CollectBus.Protocol.Dto; using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH { @@ -33,27 +35,30 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH List data = await AnalysisDataUnitAsync(input.UnitData?.HexMessageList!); List remarks = new List() { "Uab/Ua 相位角", "Ub 相位角", "Ucb/Uc 相位角", "Ia 相位角", "Ib 相位角", "Ic 相位角" }; - List> list = new List>(); + List> list = new List>(); for (int i = 0; i < data.Count; i++) { - AnalysisBaseDto dto = new AnalysisBaseDto(); - decimal value = 0; + AnalysisBaseDto dto = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCodeInfo = data[i].CheckErrorCode(); if (errorCodeInfo != null) { dto.ValidData = false; dto.ErrorCodeMsg = errorCodeInfo.Item2; - } + } else - decimal.TryParse(data[i], out value); - dto.DataValue = value; - + { + if(decimal.TryParse(data[i], out decimal value)) + dto.DataValue = value; + } dto.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}_{DataType[i]}"; - dto.FiledName = DataType[i]; + dto.FiledName = DataType[i].GetDataFieldByGatherDataType() ?? string.Empty; dto.FiledDesc= remarks[i]; list.Add(dto); } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F100_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F100_Analysis.cs index 084338b..3df913f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F100_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F100_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向无功总电能量"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向无功总电能量"); if (data.Count > 0) { @@ -56,7 +56,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -71,7 +71,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F101_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F101_Analysis.cs index 5457f1d..f4d4c0a 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F101_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F101_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向有功总电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向有功总电能示值"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F102_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F102_Analysis.cs index 9a10a3d..4e02149 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F102_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F102_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向无功总电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向无功总电能示值"); if (data.Count > 0) { @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F103_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F103_Analysis.cs index 790f871..94faa02 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F103_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F103_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向有功总电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向有功总电能示值"); if (data.Count > 0) { @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F104_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F104_Analysis.cs index c19133c..a76189a 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F104_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F104_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向无功总电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向无功总电能示值"); if (data.Count > 0) { @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F105_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F105_Analysis.cs index 2b0b1e8..05fa701 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F105_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F105_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "功率因数"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "功率因数"); if (data.Count > 0) { @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F106_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F106_Analysis.cs index 76cb330..ce50726 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F106_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F106_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相功率因数"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相功率因数"); if (data.Count > 0) { @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F107_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F107_Analysis.cs index b774044..a07cce6 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F107_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F107_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相功率因数"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相功率因数"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F108_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F108_Analysis.cs index 89b569b..520970c 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F108_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F108_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相功率因数"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相功率因数"); if (data.Count > 0) { @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F11_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F11_Analysis.cs index 9502506..661dce8 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F11_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F11_Analysis.cs @@ -8,6 +8,7 @@ using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH { @@ -35,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = GenerateFinalResult(datas,3, dataType, "抄表日冻结电能表正向有功最大需量及发生时间"); + List> data = GenerateFinalResult(datas,3, dataType, "抄表日冻结电能表正向有功最大需量及发生时间"); if (data.Count > 0) { @@ -52,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -86,18 +87,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(12, 1);//费率数 M(1≤M≤12) values.Add(ratingCount.ToString()); int handlerNum = 13; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3 * (ratingCount + 1);//12 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1);//28 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 handlerNum += 3 * (ratingCount + 1);//48 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) @@ -108,7 +109,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH values.Add(errorCode.Item1); else { - await _analysisStrategyContext.ExecuteAsync>(nameof(Appendix_A5), arr, (value) => + await _analysisStrategyContext.ExecuteAsync>(appendixName, arr, (value) => { values.Add(value.ToString()); }); @@ -117,19 +118,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH return values; } - public List> GenerateFinalResult(List data, int index, string dataType, string filedDesc = "") + public List> GenerateFinalResult(List data, int index, string dataType, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); int fCount = Convert.ToInt32(data[2]) + 1; for (int i = 1; i <= 2; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter }; int startIndex = i == 1 ? 3 : (3 + i * fCount); - decimal value = 0; var errorCode = data[startIndex].CheckErrorCode(); if (errorCode != null) { @@ -137,12 +137,14 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[startIndex], out value); - - meter.DataValue = value; + { + if(decimal.TryParse(data[startIndex], out decimal value)) + { + meter.DataValue = value; + } + } string timeSpan = $"{DateTime.Now.Year}-{data[startIndex + fCount].Substring(0, 2)}-{data[startIndex + fCount].Substring(2, 2)} {data[startIndex + fCount].Substring(4, 2)}:{data[startIndex + fCount].Substring(6, 2)}:00"; - DateTime readingDate = DateTime.Now; - if (DateTime.TryParse(timeSpan, out readingDate)) + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F145_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F145_Analysis.cs index 5348f46..cff5120 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F145_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F145_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "一象限无功电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "一象限无功电能示值"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F146_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F146_Analysis.cs index aa7e1b3..28c8244 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F146_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F146_Analysis.cs @@ -31,13 +31,14 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH try { ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(input.A.Code); ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); - + List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "四象限无功电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "四象限无功电能示值"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F147_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F147_Analysis.cs index f253797..3fa0625 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F147_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F147_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "二象限无功电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "二象限无功电能示值"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F148_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F148_Analysis.cs index abeaa33..9c7346b 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F148_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F148_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "三象限无功电能示值"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "三象限无功电能示值"); if (data.Count > 0) { @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F161_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F161_Analysis.cs index c8c0709..b46161d 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F161_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F161_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType,timeSpan, "正向有功总电能示值").IsValidData(new List() { "0D_161", "0D_161_1", "0D_161_2", "0D_161_3", "0D_161_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType,timeSpan, "正向有功总电能示值").IsValidData(new List() { "0D_161", "0D_161_1", "0D_161_2", "0D_161_3", "0D_161_4" }); if (data.Count > 0) { @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F162_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F162_Analysis.cs index 37586a4..c4d6ac4 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F162_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F162_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "正向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_162", "0D_162_1", "0D_162_2", "0D_162_3", "0D_162_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "正向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_162", "0D_162_1", "0D_162_2", "0D_162_3", "0D_162_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F163_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F163_Analysis.cs index 2eca6e7..3fdee69 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F163_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F163_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "反向有功总电能示值").IsValidData(new List() { "0D_163", "0D_163_1", "0D_163_2", "0D_163_3", "0D_163_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "反向有功总电能示值").IsValidData(new List() { "0D_163", "0D_163_1", "0D_163_2", "0D_163_3", "0D_163_4" }); if (data.Count > 0) { @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F164_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F164_Analysis.cs index 5f65463..6ecc824 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F164_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F164_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结反向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_164", "0D_164_1", "0D_164_2", "0D_164_3", "0D_164_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结反向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_164", "0D_164_1", "0D_164_2", "0D_164_3", "0D_164_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F165_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F165_Analysis.cs index ba7ea40..f52b8d1 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F165_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F165_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结一象限无功电能示值").IsValidData(new List() { "0D_165", "0D_165_1", "0D_165_2", "0D_165_3", "0D_165_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结一象限无功电能示值").IsValidData(new List() { "0D_165", "0D_165_1", "0D_165_2", "0D_165_3", "0D_165_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F166_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F166_Analysis.cs index a9e3dfe..12c012c 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F166_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F166_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结二象限无功电能示值").IsValidData(new List() { "0D_166", "0D_166_1", "0D_166_2", "0D_166_3", "0D_166_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结二象限无功电能示值").IsValidData(new List() { "0D_166", "0D_166_1", "0D_166_2", "0D_166_3", "0D_166_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F167_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F167_Analysis.cs index b30f48c..2e76d9f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F167_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F167_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结三象限无功电能示值").IsValidData(new List() { "0D_167", "0D_167_1", "0D_167_2", "0D_167_3", "0D_167_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结三象限无功电能示值").IsValidData(new List() { "0D_167", "0D_167_1", "0D_167_2", "0D_167_3", "0D_167_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F168_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F168_Analysis.cs index e6c2143..566b374 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F168_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F168_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结四象限无功电能示值").IsValidData(new List() { "0D_168", "0D_168_1", "0D_168_2", "0D_168_3", "0D_168_4" }); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "日冻结四象限无功电能示值").IsValidData(new List() { "0D_168", "0D_168_1", "0D_168_2", "0D_168_3", "0D_168_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F177_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F177_Analysis.cs index a5aafb0..d685851 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F177_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F177_Analysis.cs @@ -35,7 +35,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结正向有功电能示值").IsValidData(new List() { "0D_177", "0D_177_1", "0D_177_2", "0D_177_3", "0D_177_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结正向有功电能示值").IsValidData(new List() { "0D_177", "0D_177_1", "0D_177_2", "0D_177_3", "0D_177_4" }); if (data.Count > 0) { // 查询电表信息 @@ -51,7 +51,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -66,7 +66,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F178_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F178_Analysis.cs index 33597da..20a9ccb 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F178_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F178_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结正向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_178", "0D_178_1", "0D_178_2", "0D_178_3", "0D_178_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结正向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_178", "0D_178_1", "0D_178_2", "0D_178_3", "0D_178_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F179_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F179_Analysis.cs index e1cf7c9..10234b0 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F179_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F179_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "反向有功总电能示值").IsValidData(new List() { "0D_179", "0D_179_1", "0D_179_2", "0D_179_3", "0D_179_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "反向有功总电能示值").IsValidData(new List() { "0D_179", "0D_179_1", "0D_179_2", "0D_179_3", "0D_179_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F180_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F180_Analysis.cs index 7c9dc8a..f896e59 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F180_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F180_Analysis.cs @@ -35,7 +35,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结反向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_180", "0D_180_1", "0D_180_2", "0D_180_3", "0D_180_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结反向无功(组合无功 1)电能示值").IsValidData(new List() { "0D_180", "0D_180_1", "0D_180_2", "0D_180_3", "0D_180_4" }); if (data.Count > 0) { // 查询电表信息 @@ -51,7 +51,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -66,7 +66,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F181_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F181_Analysis.cs index c799490..2e8ef47 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F181_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F181_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结一象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_181", "0D_181_1", "0D_181_2", "0D_181_3", "0D_181_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结一象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_181", "0D_181_1", "0D_181_2", "0D_181_3", "0D_181_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F182_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F182_Analysis.cs index 7e1fd3f..f21f425 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F182_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F182_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结二象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_182", "0D_182_1", "0D_182_2", "0D_182_3", "0D_182_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结二象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_182", "0D_182_1", "0D_182_2", "0D_182_3", "0D_182_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F183_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F183_Analysis.cs index 9f00652..81a8710 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F183_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F183_Analysis.cs @@ -35,7 +35,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结三象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_183", "0D_183_1", "0D_183_2", "0D_183_3", "0D_183_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结三象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_183", "0D_183_1", "0D_183_2", "0D_183_3", "0D_183_4" }); if (data.Count > 0) { // 查询电表信息 @@ -51,7 +51,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -66,7 +66,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F184_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F184_Analysis.cs index 732af70..e2f6747 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F184_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F184_Analysis.cs @@ -36,7 +36,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-01 00:00:00"; - List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结四象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_184", "0D_184_1", "0D_184_2", "0D_184_3", "0D_184_4" }); + List> data = datas.GenerateFinalResultTd_m(3, dataType, timeSpan, "月冻结四象限无功电能示值(总、费率 1~M)").IsValidData(new List() { "0D_184", "0D_184_1", "0D_184_2", "0D_184_3", "0D_184_4" }); if (data.Count > 0) { // 查询电表信息 @@ -52,7 +52,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -67,7 +67,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F189_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F189_Analysis.cs index 4c5461d..40fc28c 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F189_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F189_Analysis.cs @@ -37,7 +37,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH string timeSpan = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "抄表日冻结正向有功最大需量及发生时间"); + List> data = datas.GenerateFinalResultTd_d(3, dataType, timeSpan, "抄表日冻结正向有功最大需量及发生时间"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +53,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +68,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -87,13 +87,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(12, 1); values.Add(ratingCount.ToString()); int handlerNum = 13; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F190_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F190_Analysis.cs index 2f5723b..2270784 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F190_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F190_Analysis.cs @@ -34,10 +34,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - - AnalysisBaseDto data = GenerateFinalResult(datas, "抄表日冻结正向无功最大需量及发生时间"); - data.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - + string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; + AnalysisBaseDto data = GenerateFinalResult(datas, "抄表日冻结正向无功最大需量及发生时间", dataType); + // 查询电表信息 AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.DeviceType.ToString(), "15"); if (ammeterInfo != null) @@ -47,7 +46,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH data.DatabaseBusiID = ammeterInfo.DatabaseBusiID; data.DeviceAddress = ammeterInfo.AmmerterAddress; } - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -62,7 +61,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -81,18 +80,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(12, 1); values.Add(ratingCount.ToString()); int handlerNum = 13; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3 * (ratingCount + 1);//12 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1);//28 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 handlerNum += 3 * (ratingCount + 1);//48 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) @@ -112,15 +111,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH return values; } - public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc = "") + public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc,string dataType) { - List> list = new List>(); - AnalysisBaseDto meter = new AnalysisBaseDto + List> list = new List>(); + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter }; - - decimal value = 0; var errorCode = data[3].CheckErrorCode(); if (errorCode != null) { @@ -128,15 +125,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[3], out value); - meter.DataValue = value; - - string timeSpan = $"{DateTime.Now.Year}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00";//$"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)}"; - DateTime readingDate = DateTime.Now; - if (DateTime.TryParse(timeSpan, out readingDate)) + { + if(decimal.TryParse(data[3], out decimal value)) + { + meter.DataValue = value; + } + } + string timeSpan = $"{DateTime.Now.Year}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00"; + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; } + meter.DataType = dataType; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; return meter; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F193_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F193_Analysis.cs index 9805b15..b7e920f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F193_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F193_Analysis.cs @@ -35,9 +35,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - - AnalysisBaseDto data = GenerateFinalResult(datas, "月冻结正向有功最大需量及发生时间"); - data.DataType= $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; + string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; + + AnalysisBaseDto data = GenerateFinalResult(datas, "月冻结正向有功最大需量及发生时间", dataType); // 查询电表信息 AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.DeviceType.ToString(), "15"); if (ammeterInfo != null) @@ -47,7 +47,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH data.DatabaseBusiID = ammeterInfo.DatabaseBusiID; data.DeviceAddress = ammeterInfo.AmmerterAddress; } - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -62,7 +62,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -83,13 +83,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(11, 1); values.Add(ratingCount.ToString()); int handlerNum = 12; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 return values; } - private async Task> GetDataAsync(List data, int len, string appendixName) + private async Task> GetDataAsync(List data, int len, string appendixName) { List values = new List(); var errorCode = data.CheckErrorCode(); @@ -104,14 +104,12 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH } return values; } - public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc = "") + public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc, string dataType) { - AnalysisBaseDto meter = new AnalysisBaseDto + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter, }; - - decimal value = 0; var errorCode = data[3].CheckErrorCode(); if (errorCode != null) { @@ -119,15 +117,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[3], out value); - meter.DataValue = value; - - string timeSpan = $"{data[0].Substring(0, 4)}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00";//$"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)}"; - DateTime readingDate = DateTime.Now; - if (DateTime.TryParse(timeSpan, out readingDate)) + { + if(decimal.TryParse(data[3], out decimal value)) + { + meter.DataValue = value; + } + } + string timeSpan = $"{data[0].Substring(0, 4)}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00"; + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; } + meter.DataType = dataType; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; return meter; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F195_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F195_Analysis.cs index 229c4cd..ef5bc1f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F195_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F195_Analysis.cs @@ -35,10 +35,10 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); + string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - AnalysisBaseDto data = GenerateFinalResult(datas, "月冻结反向有功最大需量及发生时间"); - data.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - // 查询电表信息 + AnalysisBaseDto data = GenerateFinalResult(datas, "月冻结反向有功最大需量及发生时间", dataType); + // 查询电表信息 AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.DeviceType.ToString(), "15"); if (ammeterInfo != null) { @@ -47,7 +47,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH data.DatabaseBusiID = ammeterInfo.DatabaseBusiID; data.DeviceAddress = ammeterInfo.AmmerterAddress; } - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -62,7 +62,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Month, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -83,13 +83,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(11, 1); values.Add(ratingCount.ToString()); int handlerNum = 12; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), 3,nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3), 3,nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4), 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 return values; } - private async Task> GetDataAsync(List data, int len, string appendixName) + private async Task> GetDataAsync(List data, int len, string appendixName) { List values = new List(); var errorCode = data.CheckErrorCode(); @@ -104,14 +104,12 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH } return values; } - public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc = "") + public AnalysisBaseDto GenerateFinalResult(List data, string filedDesc,string dataType) { - AnalysisBaseDto meter = new AnalysisBaseDto + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter }; - - decimal value = 0; var errorCode = data[3].CheckErrorCode(); if (errorCode != null) { @@ -119,15 +117,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[3], out value); - meter.DataValue = value; - - string timeSpan = $"{data[0].Substring(0, 4)}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00";//$"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)}"; - DateTime readingDate = DateTime.Now; - if (DateTime.TryParse(timeSpan, out readingDate)) + { + if(decimal.TryParse(data[3], out decimal value)) + { + meter.DataValue = value; + } + } + string timeSpan = $"{data[0].Substring(0, 4)}-{data[4].Substring(0, 2)}-{data[4].Substring(2, 2)} {data[4].Substring(4, 2)}:{data[4].Substring(6, 2)}:00"; + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; } + meter.DataType = dataType; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; return meter; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F19_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F19_Analysis.cs index 7fd8ea4..e8f200f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F19_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F19_Analysis.cs @@ -10,6 +10,7 @@ using System.Data; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.IotSystems.Ammeters; using JiShe.CollectBus.Common.Helpers; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH { @@ -37,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = GenerateFinalResult(datas, dataType, "月冻结电能表正向有功最大需量及发生时间"); + List> data = GenerateFinalResult(datas, dataType, "月冻结电能表正向有功最大需量及发生时间"); if (data.Count > 0) { // 查询电表信息 @@ -53,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -68,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -87,18 +88,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(11, 1); values.Add(ratingCount.ToString()); int handlerNum = 12; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3 * (ratingCount + 1); - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 handlerNum += 3 * (ratingCount + 1); - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) @@ -118,16 +119,15 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH return values; } - public List> GenerateFinalResult(List data, string dataType,string filedDesc = "") + public List> GenerateFinalResult(List data, string dataType,string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); int fCount = Convert.ToInt32(data[2]) + 1; for (int i = 1; i <= 2; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); + AnalysisBaseDto meter = new AnalysisBaseDto(); meter.DeviceType= MeterTypeEnum.Ammeter; int startIndex = i == 1 ? 3 : (3 + i * fCount); - decimal value = 0; var errorCode = data[startIndex].CheckErrorCode(); if (errorCode != null) { @@ -135,17 +135,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[startIndex], out value); - meter.DataValue = value; - //2021 01 15 + { + if(decimal.TryParse(data[startIndex], out decimal value)) + { + meter.DataValue = value; + } + } string timeSpan = $"{DateTime.Now.Year}-{data[startIndex + fCount].Substring(0, 2)}-{data[startIndex + fCount].Substring(2, 2)} {data[startIndex + fCount].Substring(4, 2)}:{data[startIndex + fCount].Substring(6, 2)}:00"; - DateTime readingDate = DateTime.Now; - if (DateTime.TryParse(timeSpan, out readingDate)) + if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; } meter.DataType = i == 1 ? dataType : $"{dataType}_{ i - 1}"; - filedDesc = i == 1 ? filedDesc : filedDesc.Replace("有功", "无功"); meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F3_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F3_Analysis.cs index 9342427..5267153 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F3_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F3_Analysis.cs @@ -41,7 +41,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH //冻结数据时标 var time = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; - List> data = GenerateFinalResult(datas,dataType, "日冻结正向有/无功最大需量及发生时间"); + List> data = GenerateFinalResult(datas,dataType, "日冻结正向有/无功最大需量及发生时间"); if (data.Count > 0) { // 查询电表信息 @@ -57,7 +57,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -72,7 +72,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -92,18 +92,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(12, 1);//费率数 M(1≤M≤12) values.Add(ratingCount.ToString()); int handlerNum = 13; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3 * (ratingCount + 1);//12 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1);//28 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 handlerNum += 3 * (ratingCount + 1);//48 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) @@ -123,61 +123,52 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH return values; } - public List> GenerateFinalResult(List data,string dataType, string filedDesc = "") + public List> GenerateFinalResult(List data,string dataType, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); int fCount = Convert.ToInt32(data[2]) + 1; for (int i = 1; i <= 2; i++) { - try + AnalysisBaseDto meter = new AnalysisBaseDto { - AnalysisBaseDto meter = new AnalysisBaseDto - { - DeviceType = MeterTypeEnum.Ammeter - }; - int startIndex = i == 1 ? 3 : (3 + i * fCount); + DeviceType = MeterTypeEnum.Ammeter + }; + int startIndex = i == 1 ? 3 : (3 + i * fCount); - var errorCode = data[startIndex].CheckErrorCode(); - if (errorCode != null) - meter.ValidData = false; - decimal.TryParse(data[startIndex], out decimal value);//decimal.TryParse(data[startIndex], out value); + var errorCode = data[startIndex].CheckErrorCode(); + if (errorCode != null) + meter.ValidData = false; + if(decimal.TryParse(data[startIndex], out decimal value)) meter.DataValue = value; - //TODO:日冻结类数据时标Td 20210824 - var dataTime = string.Empty; - errorCode = data[0].CheckErrorCode(); - if (data[0].Length == 8 && errorCode is null) - dataTime = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} 00:00:00"; - if (!DateTime.TryParse(dataTime, out DateTime readingDate)) - meter.ValidData = false; - meter.TimeSpan = readingDate;// - + //TODO:日冻结类数据时标Td + var dataTime = string.Empty; + errorCode = data[0].CheckErrorCode(); + if (data[0].Length == 8 && errorCode is null) + dataTime = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} 00:00:00"; + if (DateTime.TryParse(dataTime, out DateTime readingDate)) + meter.TimeSpan = readingDate; + else + meter.ValidData = false; //TODO:最大需量发生时间 - errorCode = data[startIndex + fCount].CheckErrorCode(); - if (errorCode != null && data[startIndex + fCount].Length != 8) + errorCode = data[startIndex + fCount].CheckErrorCode(); + if (errorCode != null && data[startIndex + fCount].Length != 8) + meter.ValidData = false; + else + { + string timeSpan = $"{data[0].Substring(0, 4)}-{data[startIndex + fCount].Substring(0, 2)}-{data[startIndex + fCount].Substring(2, 2)} {data[startIndex + fCount].Substring(4, 2)}:{data[startIndex + fCount].Substring(6, 2)}:00"; + if (!DateTime.TryParse(timeSpan, out DateTime tsField)) meter.ValidData = false; else - { - string timeSpan = $"{data[0].Substring(0, 4)}-{data[startIndex + fCount].Substring(0, 2)}-{data[startIndex + fCount].Substring(2, 2)} {data[startIndex + fCount].Substring(4, 2)}:{data[startIndex + fCount].Substring(6, 2)}:00"; - if (!DateTime.TryParse(timeSpan, out DateTime tsField)) - meter.ValidData = false; - else - meter.TimeSpan=tsField; - } - - meter.DataType = i == 1 ? dataType : $"{dataType}_{ i - 1}"; - filedDesc = i == 1 ? filedDesc : filedDesc.Replace("有功", "无功"); - meter.FiledDesc = filedDesc; - meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; - list.Add(meter); - } - catch - { + meter.TimeSpan=tsField; } + meter.DataType = i == 1 ? dataType : $"{dataType}_{ i - 1}"; + filedDesc = i == 1 ? filedDesc : filedDesc.Replace("有功", "无功"); + meter.FiledDesc = filedDesc; + meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; + list.Add(meter); + } - if (list.Count == 0) - throw new Exception("错误数据"); - return list; } } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F4_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F4_Analysis.cs index 8b7e7eb..1fb68ad 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F4_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F4_Analysis.cs @@ -40,7 +40,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH //冻结数据时标 var time = $"{datas[0].Substring(0, 4)}-{datas[0].Substring(4, 2)}-{datas[0].Substring(6, 2)} 00:00:00"; - List> data = GenerateFinalResult(datas, dataType, "日冻结反向有/无功最大需量及发生时间"); + List> data = GenerateFinalResult(datas, dataType, "日冻结反向有/无功最大需量及发生时间"); if (data.Count > 0) { // 查询电表信息 @@ -56,7 +56,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -71,7 +71,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Day, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -91,18 +91,18 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int ratingCount = hexMessageList.GetRatingCount(12, 1);//费率数 M(1≤M≤12) values.Add(ratingCount.ToString()); int handlerNum = 13; - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向有功总最大需量 handlerNum += 3 * (ratingCount + 1);//12 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向有功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1);//28 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 3 * (ratingCount + 1)), ratingCount, 3, nameof(Appendix_A23)));//正向无功总最大需量 handlerNum += 3 * (ratingCount + 1);//48 - values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 + values.AddRange(await GetDataAsync(hexMessageList.GetRange(handlerNum, 4 * (ratingCount + 1)), ratingCount, 4, nameof(Appendix_A17)));//正向无功总最大需量发生时间 handlerNum += 4 * (ratingCount + 1); return values; } - private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) + private async Task> GetDataAsync(List data, int ratingCount, int len, string appendixName) { List values = new List(); for (int i = 0; i < ratingCount + 1; i++) @@ -122,13 +122,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH return values; } - public List> GenerateFinalResult(List data,string dataType, string filedDesc = "") + public List> GenerateFinalResult(List data,string dataType, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); int fCount = Convert.ToInt32(data[2]) + 1; for (int i = 1; i <= 2; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter }; @@ -140,17 +140,17 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.ValidData = false; meter.ErrorCodeMsg = errorCode.Item2; } - decimal.TryParse(data[startIndex], out decimal value);//decimal.TryParse(data[startIndex], out value); - meter.DataValue = value; - - //TODO:日冻结类数据时标Td 20210824 + if(decimal.TryParse(data[startIndex], out decimal value)) + meter.DataValue = value; + //TODO:日冻结类数据时标Td var dataTime = string.Empty; errorCode = data[0].CheckErrorCode(); if (data[0].Length == 8 && errorCode is null) dataTime = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} 00:00:00"; if (!DateTime.TryParse(dataTime, out DateTime readingDate)) meter.ValidData = false; - meter.TimeSpan = readingDate; + else + meter.TimeSpan = readingDate; //TODO:最大需量发生时间 errorCode = data[startIndex + fCount].CheckErrorCode(); @@ -169,7 +169,6 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; list.Add(meter); - } return list; } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F81_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F81_Analysis.cs index 4f917de..acf04cd 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F81_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F81_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "有功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "有功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F82_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F82_Analysis.cs index 1854237..ce5d692 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F82_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F82_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相有功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相有功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F83_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F83_Analysis.cs index a35f66f..a5ea520 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F83_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F83_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相有功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相有功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F84_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F84_Analysis.cs index 4c70465..648be75 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F84_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F84_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相有功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相有功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F85_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F85_Analysis.cs index 4b85f94..3fd2907 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F85_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F85_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "无功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "无功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F86_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F86_Analysis.cs index cc86276..2dad0e8 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F86_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F86_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相无功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相无功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F87_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F87_Analysis.cs index 8aeaef4..de93427 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F87_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F87_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相无功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相无功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F88_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F88_Analysis.cs index 3f1cdb7..3e24bb4 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F88_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F88_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相无功功率曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相无功功率曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F89_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F89_Analysis.cs index 227418b..a89b0c7 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F89_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F89_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相电压曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相电压曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F90_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F90_Analysis.cs index 428eeae..30f16b0 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F90_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F90_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相电压曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相电压曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F91_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F91_Analysis.cs index 3a7f5c0..1b5e012 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F91_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F91_Analysis.cs @@ -38,7 +38,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相电压曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相电压曲线"); if (data.Count > 0) { // 查询电表信息 @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -69,7 +69,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F92_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F92_Analysis.cs index 6c7f733..b3b41aa 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F92_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F92_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相电流曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "A相电流曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F93_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F93_Analysis.cs index 5176d2f..f6282a5 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F93_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F93_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相电流曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "B相电流曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F94_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F94_Analysis.cs index 60e0820..6d6025f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F94_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F94_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相电流曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "C相电流曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F95_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F95_Analysis.cs index 391f375..d4174da 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F95_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F95_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "测量点零序电流曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "测量点零序电流曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F97_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F97_Analysis.cs index e31ea6f..0e790dc 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F97_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F97_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向有功总电能量曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向有功总电能量曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F98_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F98_Analysis.cs index 7e863aa..d772796 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F98_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F98_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向无功总电能量曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "正向无功总电能量曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F99_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F99_Analysis.cs index b3763db..f22d2f1 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F99_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0DH/AFN13_F99_Analysis.cs @@ -39,7 +39,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH int density = Convert.ToInt32(Convert.ToInt32(datas[1]).GetEnumDescription(typeof(DensityEnums))); string dataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}"; - List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向有功总电能量曲线"); + List> data = datas.GenerateFinalResultTd_c(3, density, dataType, "反向有功总电能量曲线"); if (data.Count > 0) { // 查询电表信息 @@ -55,7 +55,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH }); } } - UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> + UnitDataAnalysis>> unitDataAnalysis = new UnitDataAnalysis>> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -70,7 +70,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0DH DensityUnit = DensityUnit.Minute, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveMultipleDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_10H/AFN16_F97_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_10H/AFN16_F97_Analysis.cs index 3d17fd7..7fa1d92 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_10H/AFN16_F97_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_10H/AFN16_F97_Analysis.cs @@ -18,6 +18,9 @@ using static FreeSql.Internal.GlobalFilter; namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H { + /// + /// 透抄 电网频率 + /// public class AFN16_F97_Analysis : IAnalysisStrategy { private readonly ILogger _logger; @@ -37,7 +40,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H ArgumentNullException.ThrowIfNull(input.UnitData?.HexMessageList); List datas = await AnalysisDataUnitAsync(input.UnitData.HexMessageList); - AnalysisBaseDto data = GenerateFinalResult(datas); + AnalysisBaseDto data = GenerateFinalResult(datas); // 查询电表信息 AmmeterInfo ammeterInfo = await _dataStorage.GetMeterInfoAsync(data.DeviceType.ToString(), "15"); if (ammeterInfo != null) @@ -47,7 +50,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H data.DatabaseBusiID = ammeterInfo.DatabaseBusiID; data.DeviceAddress = ammeterInfo.AmmerterAddress; } - UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> + UnitDataAnalysis> unitDataAnalysis = new UnitDataAnalysis> { Code = input.A.Code!, AFN = input.AFN_FC.AFN, @@ -62,7 +65,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H DensityUnit = DensityUnit.Hour, ReceivedTime = input.ReceivedTime }; - await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); + await _dataStorage.SaveDataToIotDbAsync(unitDataAnalysis); result?.Invoke(unitDataAnalysis); return await Task.FromResult(true); } @@ -73,10 +76,10 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H } } - private AnalysisBaseDto GenerateFinalResult(List data) + private AnalysisBaseDto GenerateFinalResult(List data) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - decimal.TryParse(data[7], out decimal value); + AnalysisBaseDto meter = new AnalysisBaseDto(); + var errorCode = data[7].CheckErrorCode(); if (errorCode != null) { @@ -84,7 +87,11 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_10H meter.ErrorCodeMsg = errorCode.Item2; } else - meter.DataValue = value; + { + if(decimal.TryParse(data[7], out decimal value)) + meter.DataValue = value; + } + meter.DataType = "10_97"; meter.ValidData = data[2].Equals("91") || data[2].Equals("B1"); meter.FiledDesc = "电网频率";//"电网频率"; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs index 00c5c63..a9119d8 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs @@ -199,7 +199,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData DeviceType = $"{item.DeviceType}.{IOTDBDataType.Data}", ProjectId = $"{item.ProjectId}", Timestamps = item.TimeSpan!.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity).GetDateTimeOffset().ToUnixTimeNanoseconds(), // TODO:这里暂时格式化15分钟数据,需要进行调整 - SingleMeasuring = new Tuple(item.FiledName ?? string.Empty, item.DataValue ?? default) + SingleMeasuring = new Tuple(item.FiledName ?? string.Empty, item.DataValue) }; _runtimeContext.UseTableSessionPool = true; // 使用表模型池 var taskSendInfo = await _dbProvider.QueryAsync(new IoTDBQueryOptions() { TableNameOrTreePath = DevicePathBuilder.GetTableName(), Conditions = conditions, PageIndex = 0, PageSize = 1 }); diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/Protocol3761Extensions.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/Protocol3761Extensions.cs index caa6793..dcfd2f7 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/Protocol3761Extensions.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/Protocol3761Extensions.cs @@ -4,6 +4,7 @@ using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Protocol.Contracts.Protocol.Dto; using NUglify.JavaScript.Syntax; using System.Text.RegularExpressions; +using YamlDotNet.Core.Tokens; namespace JiShe.CollectBus.Protocol.T37612012 { @@ -239,15 +240,15 @@ namespace JiShe.CollectBus.Protocol.T37612012 /// /// /// - public static List> GenerateFinalResultTd_c(this List data, int index,int density,string dataType, string filedDesc = "") + public static List> GenerateFinalResultTd_c(this List data, int index,int density,string dataType, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); - meter.DeviceType= MeterTypeEnum.Ammeter; - - decimal value = 0; + AnalysisBaseDto meter = new AnalysisBaseDto + { + DeviceType = MeterTypeEnum.Ammeter + }; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) { @@ -255,9 +256,13 @@ namespace JiShe.CollectBus.Protocol.T37612012 meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; - meter.DataType = dataType.ToUpper(); + { + if(decimal.TryParse(data[i], out decimal value)) + { + meter.DataValue = value; + } + } + meter.DataType = dataType; meter.FiledDesc = filedDesc; meter.FiledName = meter.DataType.GetDataFieldByGatherDataType() ?? string.Empty; if (DateTime.TryParse(CalculateTimeSpan(i - 3, data[0], density), out DateTime readingDate)) @@ -276,14 +281,13 @@ namespace JiShe.CollectBus.Protocol.T37612012 /// /// /// - public static List> GenerateFinalResultTd_m(this List data, int index,string dataType,string timeSpan, string filedDesc = "") + public static List> GenerateFinalResultTd_m(this List data, int index,string dataType,string timeSpan, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto(); + AnalysisBaseDto meter = new AnalysisBaseDto(); meter.DeviceType = MeterTypeEnum.Ammeter; - decimal value = 0; var errorCode = data[i].CheckErrorCode(); if (errorCode != null) { @@ -291,8 +295,12 @@ namespace JiShe.CollectBus.Protocol.T37612012 meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out decimal value)) + { + meter.DataValue = value; + } + } if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; @@ -312,13 +320,13 @@ namespace JiShe.CollectBus.Protocol.T37612012 /// /// /// - public static List> GenerateFinalResultTd_d(this List data, int index,string dataType, string timeSpan, string filedDesc = "") + public static List> GenerateFinalResultTd_d(this List data, int index,string dataType, string timeSpan, string filedDesc = "") { - List> list = new List>(); + List> list = new List>(); int typeIndex = 0; for (int i = index; i < data.Count; i++) { - AnalysisBaseDto meter = new AnalysisBaseDto + AnalysisBaseDto meter = new AnalysisBaseDto { DeviceType = MeterTypeEnum.Ammeter }; @@ -330,8 +338,12 @@ namespace JiShe.CollectBus.Protocol.T37612012 meter.ErrorCodeMsg = errorCode.Item2; } else - decimal.TryParse(data[i], out value); - meter.DataValue = value; + { + if(decimal.TryParse(data[i], out value)) + { + meter.DataValue = value; + } + } if (DateTime.TryParse(timeSpan, out DateTime readingDate)) { meter.TimeSpan = readingDate; @@ -364,29 +376,33 @@ namespace JiShe.CollectBus.Protocol.T37612012 /// /// /// - public static List> IsValidData(this List> meterDatas, List mark) + public static List> IsValidData(this List> meterDatas, List mark) { bool isUpload = false; var jfpgSum = 0M; - var totalItem = meterDatas.Find(f => f.DataType.Equals(mark[0]));//meterDatas.Find(f => f.DataType.Equals(mark[0])); - for (int i = 1; i <= meterDatas.Count - 1; i++) + foreach (var item in meterDatas) { - var value = meterDatas[i];//meterDatas.Find(f => f.DataType.Equals(mark[i])); - if (value.ValidData) - jfpgSum += value.DataValue; + if (item.ValidData && item.DataValue.HasValue) + jfpgSum += item.DataValue.Value; + } + var totalItem = meterDatas.FirstOrDefault(f => f.DataType.Equals(mark[0]));//meterDatas.Find(f => f.DataType.Equals(mark[0])); + if (totalItem != null) + { + var floatingNum = (jfpgSum * 5 / 100);//上下浮动数据 + var minjfpgSum = jfpgSum - floatingNum;//100-(100*5/100); + var maxjfpgSum = jfpgSum + floatingNum; + if ((totalItem.DataValue <= maxjfpgSum || totalItem.DataValue >= minjfpgSum))//总值,在JFPG之和的浮动范围内 + isUpload = true; + else + isUpload = false; } - var floatingNum = (jfpgSum * 5 / 100);//上下浮动数据 - var minjfpgSum = jfpgSum - floatingNum;//100-(100*5/100); - var maxjfpgSum = jfpgSum + floatingNum; - if (totalItem.DataValue <= maxjfpgSum || totalItem.DataValue >= minjfpgSum)//总值,在JFPG之和的浮动范围内 - isUpload = true; - else - isUpload = false; if (!isUpload) + { meterDatas.ForEach(f => { f.ValidData = false; }); + } return meterDatas; } } diff --git a/services/JiShe.CollectBus.Domain/Protocol3761/Dto/AnalysisBaseDto.cs b/services/JiShe.CollectBus.Domain/Protocol3761/Dto/AnalysisBaseDto.cs index 8d693e3..331fce6 100644 --- a/services/JiShe.CollectBus.Domain/Protocol3761/Dto/AnalysisBaseDto.cs +++ b/services/JiShe.CollectBus.Domain/Protocol3761/Dto/AnalysisBaseDto.cs @@ -71,10 +71,10 @@ namespace JiShe.CollectBus.Protocol.Contracts.Protocol.Dto public class AnalysisBaseDto : AnalysisBaseDto { - /// - /// 抄读值 - /// - public T? DataValue { get; set; } + /// + /// 抄读值 + /// + public T? DataValue { get; set; } = default; } } diff --git a/shared/JiShe.CollectBus.Common/Extensions/StringExtensions.cs b/shared/JiShe.CollectBus.Common/Extensions/StringExtensions.cs index d2cea60..4b24683 100644 --- a/shared/JiShe.CollectBus.Common/Extensions/StringExtensions.cs +++ b/shared/JiShe.CollectBus.Common/Extensions/StringExtensions.cs @@ -1183,10 +1183,10 @@ namespace JiShe.CollectBus.Common.Extensions /// /// /// - public static string HexToDecStr(this int hexString) + public static string HexToDecStr(this int hexString,bool isUpper= true) { var decimalString = Convert.ToString(hexString, 16); - return decimalString; + return isUpper? decimalString.ToUpper(): decimalString; } /// diff --git a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml index 30e91e8..a58ded5 100644 --- a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml +++ b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml @@ -16,7 +16,6 @@ 后端服务 - From 75efbb3a36e9d686e12487eeb675eccdf65618a6 Mon Sep 17 00:00:00 2001 From: zenghongyao <873884283@qq.com> Date: Thu, 8 May 2025 15:51:25 +0800 Subject: [PATCH 11/15] =?UTF-8?q?=E8=B0=83=E8=AF=95=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=90=A6=E8=AE=A4=E5=B8=A7=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AnalysisData/AFN_00H/AFN0_F2_Analysis.cs | 3 +++ .../AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs | 2 +- web/JiShe.CollectBus.Host/Pages/Monitor.cshtml | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_00H/AFN0_F2_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_00H/AFN0_F2_Analysis.cs index 5c2e890..27fd11f 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_00H/AFN0_F2_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_00H/AFN0_F2_Analysis.cs @@ -37,6 +37,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_00H TimeDensity = -1 }; result?.Invoke(dto); +#if DEBUG + _logger.LogWarning($"全部否认:{input.A.Code}-{input.DT.Fn}-{input.BaseHexMessage.HexMessageString}"); +#endif return Task.FromResult(true); } catch (Exception ex) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs index d67d8d1..59ae0fc 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F130_Analysis.cs @@ -99,7 +99,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData.AFN_0CH meter.DataValue = value; } meter.DataType = $"{afn.ToString().PadLeft(2, '0')}_{fn}_{i - index}"; - string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00" + string timeSpan = $"{data[0].Substring(0, 4)}-{data[0].Substring(4, 2)}-{data[0].Substring(6, 2)} {data[0].Substring(8, 2)}:{data[0].Substring(10, 2)}:00"; if(DateTime.TryParse(timeSpan, out DateTime readingDate)) meter.TimeSpan = readingDate; meter.FiledDesc = filedDesc; diff --git a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml index a58ded5..30e91e8 100644 --- a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml +++ b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml @@ -16,6 +16,7 @@ 后端服务 + From 1a9d3924b0edd6db3e9566efe8ba203785868df2 Mon Sep 17 00:00:00 2001 From: zenghongyao <873884283@qq.com> Date: Thu, 8 May 2025 17:20:07 +0800 Subject: [PATCH 12/15] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=BB=88=E7=AB=AF?= =?UTF-8?q?=E6=97=A5=E5=8E=86=E6=97=B6=E9=92=9F=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AnalysisData/AFN_0CH/AFN12_F2_Analysis.cs | 5 ++++- .../AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs | 2 +- .../Appendix/Appendix_A1.cs | 9 ++++++--- web/JiShe.CollectBus.Host/Pages/Monitor.cshtml | 1 - 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F2_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F2_Analysis.cs index 2bc496f..5bac5c7 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F2_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F2_Analysis.cs @@ -6,6 +6,8 @@ using JiShe.CollectBus.Protocol.Interfaces; using JiShe.CollectBus.Protocol.T37612012.Appendix; using JiShe.CollectBus.Protocol3761; using Microsoft.Extensions.Logging; +using static System.Runtime.InteropServices.JavaScript.JSType; +using System.Diagnostics.Metrics; namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH { @@ -71,7 +73,8 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH { await _analysisStrategyContext.ExecuteAsync>(nameof(Appendix_A1), arr, (value) => { - dto.DataValue = value; + var data = (Tuple)value; + dto.DataValue = $"{data.Item1} {data.Item2}"; }); } dto.DataType = dataType; diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs index c54d058..f4dd742 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/AFN_0CH/AFN12_F49_Analysis.cs @@ -54,7 +54,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AFN_0CH dto.DataValue = value; } dto.DataType = $"{input.AFN_FC.AFN.HexToDecStr().PadLeft(2, '0')}_{input.DT.Fn}_{DataType[i]}"; - dto.FiledName = DataType[i].GetDataFieldByGatherDataType() ?? string.Empty; + dto.FiledName = dto.DataType.GetDataFieldByGatherDataType() ?? string.Empty; dto.FiledDesc= remarks[i]; list.Add(dto); } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/Appendix/Appendix_A1.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/Appendix/Appendix_A1.cs index 05d45d9..eadc9a3 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/Appendix/Appendix_A1.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/Appendix/Appendix_A1.cs @@ -21,10 +21,13 @@ namespace JiShe.CollectBus.Protocol.T37612012.Appendix var day = data[3]; string binString = data[4].HexTo4BinZero(); var months = (binString.Substring(3, 1).BinToDec() * 10) + Convert.ToInt32(binString.Substring(4, 4).BinToHex()); - var week = binString.Substring(0, 3).HexTo4BinZero(); + var week = binString.Substring(0, 3).BinToHex(); var year = $"{DateTime.Now.ToString("yyyy").Substring(0, 2)}{data[5]}"; - string date= $"{year}-{months.ToString().PadLeft(2, '0')}-{day} {hours}:{minutes}:{seconds}_{week}"; - result?.Invoke(date); + string date= $"{year}-{months.ToString().PadLeft(2, '0')}-{day} {hours}:{minutes}:{seconds}"; + string[] weekdays = {"", "星期一", "星期二", "星期三","星期四", "星期五", "星期六", "星期日"}; + int.TryParse(week, out int weekday); + // Item1=日期,Item2=星期几 + result?.Invoke(Tuple.Create(date, weekdays[weekday])); return await Task.FromResult(true); } diff --git a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml index 30e91e8..a58ded5 100644 --- a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml +++ b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml @@ -16,7 +16,6 @@ 后端服务 - From fa593de7541b9bd1d19f44ada3b07d1ed2e3cce1 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 17:21:20 +0800 Subject: [PATCH 13/15] =?UTF-8?q?=E5=AE=8C=E5=96=84IoTDB=E9=A9=B1=E5=8A=A8?= =?UTF-8?q?=EF=BC=8C=E9=80=82=E9=85=8D=E5=A2=9E=E9=87=8F=E6=BA=90=E7=A0=81?= =?UTF-8?q?=E7=94=9F=E6=88=90=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComplexTypeSourceAnalyzers.cs | 130 ++++++--- .../Attributes/EntityTypeAttribute.cs | 19 -- .../TableNameOrTreePathAttribute.cs | 3 +- .../JiShe.CollectBus.IoTDB/Model/Class1.cs | 12 + .../JiShe.CollectBus.IoTDB/Model/IoTEntity.cs | 7 + .../Model/TableModelSingleMeasuringEntity.cs | 8 +- .../Model/TreeModelSingleMeasuringEntity.cs | 6 +- .../Provider/DeviceMetadata.cs | 6 +- .../Provider/DevicePathBuilder.cs | 2 +- .../Provider/IoTDBProvider.cs | 254 +++++++----------- .../AnalysisData/DataStorage.cs | 20 +- .../Ammeters/ElectricityMeter.cs | 4 +- .../Ammeters/ElectricityMeterTreeModel.cs | 4 +- .../MeterReadingTelemetryPacketInfo.cs | 4 +- .../EntityMemberInfo.cs | 7 + .../EntityTypeEnum.cs | 15 +- .../ISourceEntityAccessor.cs | 5 + .../SourceAnalyzersAttribute.cs | 7 + .../Consts/IOTDBDataTypeConst.cs | 29 ++ .../Consts/T37612012PacketItemCodeConst.cs | 22 +- 20 files changed, 291 insertions(+), 273 deletions(-) delete mode 100644 modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs create mode 100644 modules/JiShe.CollectBus.IoTDB/Model/Class1.cs rename {modules/JiShe.CollectBus.IoTDB/EnumInfo => shared/JiShe.CollectBus.Analyzers.Shared}/EntityTypeEnum.cs (57%) create mode 100644 shared/JiShe.CollectBus.Common/Consts/IOTDBDataTypeConst.cs diff --git a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs index 15179af..bad9528 100644 --- a/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs +++ b/modules/JiShe.CollectBus.Analyzers/ComplexTypeSourceAnalyzers.cs @@ -1,4 +1,5 @@ -using Microsoft.CodeAnalysis; +using JiShe.CollectBus.Analyzers.Shared; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; @@ -40,18 +41,37 @@ namespace JiShe.CollectBus.IncrementalGenerator private static ClassDeclarationSyntax GetClassDeclaration(GeneratorSyntaxContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; - var attributeType = context.SemanticModel.Compilation.GetTypeByMetadataName(AttributeFullName); + var semanticModel = context.SemanticModel; - foreach (var attribute in classDecl.AttributeLists.SelectMany(al => al.Attributes)) + // 获取类符号 + var classSymbol = semanticModel.GetDeclaredSymbol(classDecl) as INamedTypeSymbol; + if (classSymbol == null) return null; + + // 检查是否包含 SourceAnalyzers 特性 + var sourceAnalyzerAttr = classSymbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass?.ToDisplayString() == AttributeFullName); + + // 必须包含 EntityType 参数 + if (sourceAnalyzerAttr == null || + sourceAnalyzerAttr.ConstructorArguments.Length == 0) { - var symbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol; - if (symbol is IMethodSymbol ctor && - SymbolEqualityComparer.Default.Equals(ctor.ContainingType, attributeType)) - { - return classDecl; - } + return null; } - return null; + + return classDecl; + + //var classDecl = (ClassDeclarationSyntax)context.Node; + //var attributeType = context.SemanticModel.Compilation.GetTypeByMetadataName(AttributeFullName); + + //foreach (var attribute in classDecl.AttributeLists.SelectMany(al => al.Attributes)) + //{ + // var symbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol; + // if (symbol is IMethodSymbol ctor && + // SymbolEqualityComparer.Default.Equals(ctor.ContainingType, attributeType)) + // { + // return classDecl; + // } + //} + //return null; } /// @@ -154,6 +174,25 @@ namespace JiShe.CollectBus.IncrementalGenerator Compilation compilation, HashSet processedTypes) { + // 获取 SourceAnalyzers 特性的 EntityType 参数 + var sourceAnalyzerAttr = classSymbol.GetAttributes() + .FirstOrDefault(attr => + attr.AttributeClass?.ToDisplayString() == AttributeFullName); + + // 解析 EntityType 枚举值 + string entityTypeValue = "EntityTypeEnum.Other"; // 默认值 + if (sourceAnalyzerAttr != null && + sourceAnalyzerAttr.ConstructorArguments.Length > 0) + { + var arg = sourceAnalyzerAttr.ConstructorArguments[0]; + if (arg.Kind == TypedConstantKind.Enum && + arg.Type is INamedTypeSymbol enumType) + { + int enumValue = (int)arg.Value!; + entityTypeValue = GetEnumMemberName(enumType, enumValue); + } + } + var code = new StringBuilder(); code.AppendLine("// "); code.AppendLine("#nullable enable"); @@ -185,12 +224,14 @@ namespace JiShe.CollectBus.IncrementalGenerator //类名称 code.AppendLine($" public string EntityName {{get;}} = \"{classSymbol.Name}\";"); - + // 添加 EntityType 属性 + code.AppendLine($" public EntityTypeEnum? EntityType {{ get; }} = {entityTypeValue};"); + foreach (var prop in propList) { // 安全类型转换 if (prop.Type is not ITypeSymbol propType) continue; - + if (propType is INamedTypeSymbol namedType) { GenerateStandardAccessors(prop, namedType, code); @@ -262,7 +303,7 @@ namespace JiShe.CollectBus.IncrementalGenerator : $"obj.{propName}.{elements[i].Name}"; } } - + /// /// 处理System.Tuple类型的访问器生成 /// @@ -300,7 +341,7 @@ namespace JiShe.CollectBus.IncrementalGenerator } } } - + /// /// 增强的工厂类实现 /// @@ -381,7 +422,7 @@ namespace JiShe.CollectBus.IncrementalGenerator $"Get{prop.Name}_{element.Name}(targetEntity),"); } } - + } code.AppendLine(" _ => throw new ArgumentException($\"Unknown property: {propertyName}\")"); @@ -425,7 +466,7 @@ namespace JiShe.CollectBus.IncrementalGenerator code.AppendLine($" targetEntity, ({elementType})value);"); code.AppendLine(" break;"); } - } + } } code.AppendLine(" default:"); @@ -475,10 +516,10 @@ namespace JiShe.CollectBus.IncrementalGenerator /// 生成当前类属性信息集合 /// private static void GenerateEntityMemberInfoList( - IEnumerable propList, - StringBuilder code, - Compilation compilation, - INamedTypeSymbol classSymbol) + IEnumerable propList, + StringBuilder code, + Compilation compilation, + INamedTypeSymbol classSymbol) { code.AppendLine(" public List MemberList { get; } = new()"); code.AppendLine(" {"); @@ -487,8 +528,10 @@ namespace JiShe.CollectBus.IncrementalGenerator foreach (var prop in propList) { - var propType = prop.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - var parentType = prop.ContainingType.ToDisplayString(); + var entityType = prop.ContainingType.ToDisplayString();//entity 实体类型名称 + var propType = prop.Type;//实体属性的类型 + var propTypeName = propType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var declaredTypeName = propType.Name; // 直接获取类型名称(如 "Int32") // 处理主属性 var propAttributes = prop.GetAttributes() @@ -503,9 +546,10 @@ namespace JiShe.CollectBus.IncrementalGenerator mainMember.Append( $"new EntityMemberInfo(" + $"\"{prop.Name}\", " + - $"typeof({propType}), " + - $"(e) => Get{prop.Name}(({parentType})e), " + - $"(e, v) => Set{prop.Name}(({parentType})e, ({propType})v))"); + $"typeof({propTypeName}), " + + $"\"{declaredTypeName}\", " + + $"(e) => Get{prop.Name}(({entityType})e), " + + $"(e, v) => Set{prop.Name}(({entityType})e, ({propTypeName})v))"); if (attributeInitializers.Any()) { @@ -516,20 +560,22 @@ namespace JiShe.CollectBus.IncrementalGenerator initializerLines.Add(mainMember.ToString()); - // 处理元组元素(假设不需要处理元组元素的特性) + // 处理元组元素,(暂不需要处理元组元素的特性) if (prop.Type is INamedTypeSymbol { IsTupleType: true } tupleType) { foreach (var element in tupleType.TupleElements) { - var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - var elementName = element.Name; + var elementType = element.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);//元组元素的类型 + var elementName = element.Name;//元组元素名称 + var elementDeclaredName = element.Type.Name;//元组元素类型名称 initializerLines.Add( - $"new EntityMemberInfo(" + - $"\"{prop.Name}.{elementName}\", " + - $"typeof({elementType}), " + - $"(e) => Get{prop.Name}_{elementName}(({parentType})e), " + - $"(e, v) => Set{prop.Name}_{elementName}(({parentType})e, ({elementType})v))"); + $"new EntityMemberInfo(" + + $"\"{prop.Name}.{elementName}\", " + + $"typeof({elementType}), " + + $"\"{elementDeclaredName}\", " + + $"(e) => Get{prop.Name}_{elementName}(({entityType})e), " + + $"(e, v) => Set{prop.Name}_{elementName}(({entityType})e, ({elementType})v))"); } } } @@ -621,5 +667,23 @@ namespace JiShe.CollectBus.IncrementalGenerator { return attribute.AttributeClass?.ToDisplayString() == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"; } + + /// + /// 获取枚举的参数 + /// + /// + /// + /// + private static string GetEnumMemberName(INamedTypeSymbol enumType, int value) + { + foreach (var member in enumType.GetMembers().OfType()) + { + if (member.ConstantValue is int intValue && intValue == value) + { + return $"{enumType.ToDisplayString()}.{member.Name}"; + } + } + return $"{enumType.ToDisplayString()}.Other"; + } } } \ No newline at end of file diff --git a/modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs deleted file mode 100644 index 89a4e38..0000000 --- a/modules/JiShe.CollectBus.IoTDB/Attributes/EntityTypeAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -using JiShe.CollectBus.IoTDB.Enums; - -namespace JiShe.CollectBus.IoTDB.Attributes -{ - /// - /// IoTDB实体类型特性 - /// - [AttributeUsage(AttributeTargets.Class)] - public class EntityTypeAttribute : System.Attribute - { - public EntityTypeEnum EntityType { get; } - - - public EntityTypeAttribute(EntityTypeEnum entityType) - { - EntityType = entityType; - } - } -} diff --git a/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs b/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs index ba0ca12..5f986b5 100644 --- a/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs +++ b/modules/JiShe.CollectBus.IoTDB/Attributes/TableNameOrTreePathAttribute.cs @@ -1,5 +1,4 @@ -using JiShe.CollectBus.IoTDB.Enums; - + namespace JiShe.CollectBus.IoTDB.Attributes { /// diff --git a/modules/JiShe.CollectBus.IoTDB/Model/Class1.cs b/modules/JiShe.CollectBus.IoTDB/Model/Class1.cs new file mode 100644 index 0000000..9bcd5ff --- /dev/null +++ b/modules/JiShe.CollectBus.IoTDB/Model/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.IoTDB.Model +{ + internal class Class1 + { + } +} diff --git a/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs index 40403ed..f2d55a5 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/IoTEntity.cs @@ -1,4 +1,5 @@ using JiShe.CollectBus.Common.Attributes; +using JiShe.CollectBus.Common.Consts; using JiShe.CollectBus.IoTDB.Attributes; namespace JiShe.CollectBus.IoTDB.Model @@ -20,6 +21,12 @@ namespace JiShe.CollectBus.IoTDB.Model [TAGColumn] public string ProjectId { get; set; } + /// + /// 数据类型 + /// + [TAGColumn] + public string DataType { get; set; } = IOTDBDataTypeConst.Data; + /// /// 设备类型集中器、电表、水表、流量计、传感器等 /// diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs index a5c98cf..376b677 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TableModelSingleMeasuringEntity.cs @@ -1,14 +1,12 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attributes; -using JiShe.CollectBus.IoTDB.Enums; +using JiShe.CollectBus.IoTDB.Attributes; namespace JiShe.CollectBus.IoTDB.Model { /// /// Table模型单项数据实体 - /// - [EntityType(EntityTypeEnum.TableModel)] - [SourceAnalyzers] + /// + [SourceAnalyzers(EntityTypeEnum.TableModel)] public class TableModelSingleMeasuringEntity : IoTEntity { /// diff --git a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs index 6244cdf..56a6c54 100644 --- a/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs +++ b/modules/JiShe.CollectBus.IoTDB/Model/TreeModelSingleMeasuringEntity.cs @@ -1,14 +1,12 @@ using JiShe.CollectBus.Analyzers.Shared; -using JiShe.CollectBus.IoTDB.Attributes; -using JiShe.CollectBus.IoTDB.Enums; +using JiShe.CollectBus.IoTDB.Attributes; namespace JiShe.CollectBus.IoTDB.Model { /// /// Tree模型单项数据实体 /// - [EntityType(EntityTypeEnum.TreeModel)] - [SourceAnalyzers] + [SourceAnalyzers(EntityTypeEnum.TreeModel)] public class TreeModelSingleMeasuringEntity : IoTEntity { /// diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/DeviceMetadata.cs b/modules/JiShe.CollectBus.IoTDB/Provider/DeviceMetadata.cs index a093bb7..f48d218 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/DeviceMetadata.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/DeviceMetadata.cs @@ -1,5 +1,5 @@ using Apache.IoTDB; -using JiShe.CollectBus.IoTDB.Enums; +using JiShe.CollectBus.Analyzers.Shared; namespace JiShe.CollectBus.IoTDB.Provider { @@ -9,9 +9,9 @@ namespace JiShe.CollectBus.IoTDB.Provider public class DeviceMetadata { /// - /// IoTDB实体类型枚举 + /// 实体类型枚举 /// - public EntityTypeEnum EntityType { get; set; } + public EntityTypeEnum? EntityType { get; set; } /// /// 是否有单测量值 diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/DevicePathBuilder.cs b/modules/JiShe.CollectBus.IoTDB/Provider/DevicePathBuilder.cs index 6a1a596..57e1b09 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/DevicePathBuilder.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/DevicePathBuilder.cs @@ -15,7 +15,7 @@ namespace JiShe.CollectBus.IoTDB.Provider /// public static string GetDevicePath(T entity) where T : IoTEntity { - return $"root.{entity.SystemName.ToLower()}.`{entity.ProjectId}`.`{entity.DeviceType}`.`{entity.DeviceId}`"; + return $"root.{entity.SystemName.ToLower()}.`{entity.ProjectId}`.`{entity.DeviceType}`.{entity.DataType}.`{entity.DeviceId}`"; } diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index c88403f..bacbf61 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -195,6 +195,8 @@ namespace JiShe.CollectBus.IoTDB.Provider } ); + metadata.EntityType = accessor.EntityType; + return await Task.FromResult(metaData); } @@ -262,26 +264,31 @@ namespace JiShe.CollectBus.IoTDB.Provider var devicePaths = new HashSet(); List tempColumnNames = new List(); tempColumnNames.AddRange(metadata.ColumnNames); - + var accessor = SourceEntityAccessorFactory.GetAccessor(); - var entityTypeAttribute = typeof(T).GetCustomAttribute(); + var memberCache = new Dictionary(); // 缓存优化查询 + // 预构建成员缓存(Key: NameOrPath) + foreach (var member in accessor.MemberList) + { + memberCache[member.NameOrPath] = member; + } - if (entityTypeAttribute == null) + if (accessor.EntityType == null || metadata.EntityType == null) { throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 没有指定,属于异常情况,-101"); } - if (metadata.EntityType != entityTypeAttribute.EntityType) + if (metadata.EntityType != accessor.EntityType) { throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 和{nameof(DeviceMetadata)}的 EntityType 不一致,属于异常情况,-102"); } - if (metadata.EntityType == Enums.EntityTypeEnum.TreeModel && _runtimeContext.UseTableSessionPool == true) + if (metadata.EntityType == EntityTypeEnum.TreeModel && _runtimeContext.UseTableSessionPool == true) { throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 tree模型不能使用table模型Session连接,属于异常情况,-103"); } - else if (metadata.EntityType == Enums.EntityTypeEnum.TableModel && _runtimeContext.UseTableSessionPool == false) + else if (metadata.EntityType == EntityTypeEnum.TableModel && _runtimeContext.UseTableSessionPool == false) { throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 table模型不能使用tree模型Session连接,属于异常情况,-104"); } @@ -299,13 +306,31 @@ namespace JiShe.CollectBus.IoTDB.Provider var rowValues = new List(); foreach (var measurement in tempColumnNames) - { - var value = accessor.GetPropertyValue(entity, measurement); + { + if (!memberCache.TryGetValue(measurement, out var member)) + { + throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName}没有找到{measurement}对应的member信息,-105"); + } + + var value = member.GetValue(entity); + + // 特性查询优化 + var attributes = member.CustomAttributes ?? Enumerable.Empty(); + var singleMeasuringAttr = attributes.OfType().FirstOrDefault(); + if (singleMeasuringAttr != null)//如果是单侧点 + { + var tupleItemKey = $"{member.NameOrPath}.Item2"; + if (!memberCache.TryGetValue(tupleItemKey, out var tupleMember)) + { + throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName} 没有找到{measurement}对应的member Item2 信息,-106"); + } + + value = tupleMember.GetValue(entity); + } if (value != null) { - Type tupleType = value.GetType(); - var tempValue = tupleType.Name.ToUpper() switch + var tempValue = member.DeclaredTypeName.ToUpper() switch { "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), _ => value @@ -319,70 +344,6 @@ namespace JiShe.CollectBus.IoTDB.Provider } } - //foreach (var measurement in tempColumnNames) - //{ - - // PropertyInfo propertyInfo = typeof(T).GetProperty(measurement); - // if (propertyInfo == null) - // { - // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,没有找到{measurement}属性,属于异常情况,-101。"); - // } - - // var value = propertyInfo.GetValue(entity); - // if (propertyInfo.IsDefined(typeof(SingleMeasuringAttribute), false) && metadata.IsSingleMeasuring == true)//表示当前对象是单测点模式 - // { - // if (value != null) - // { - // Type tupleType = value.GetType(); - // Type[] tupleArgs = tupleType.GetGenericArguments(); - // Type item2Type = tupleArgs[1]; // T 的实际类型 - // var item1 = tupleType.GetProperty("Item1")!.GetValue(value); - // var item2 = tupleType.GetProperty("Item2")!.GetValue(value); - // if (item1 == null || item2 == null) - // { - // throw new Exception($"{nameof(BuildTablet)} 构建表模型{typeof(T).Name}时,单测点模式构建失败,没有获取测点名称或者测点值,-102。"); - // } - - // var indexOf = metadata.ColumnNames.IndexOf(measurement); - // metadata.ColumnNames[indexOf] = (string)item1!; - - // rowValues.Add(item2); - // } - // else - // { - // rowValues.Add(null); - // } - - // //同时如果是单测点模式,且是table模型存储,路径只能通过DevicePathBuilder.GetDeviceTableName(entity)获取 - // if (_runtimeContext.UseTableSessionPool) - // { - // tableNameOrTreePath = DevicePathBuilder.GetDeviceTableName(entity); - // } - // } - // else - // { - - // //需要根据value的类型,进行相应的值映射转换,例如datetime转换为long的时间戳值 - // if (value != null) - // { - // Type tupleType = value.GetType(); - // var tempValue = tupleType.Name.ToUpper() switch - // { - // "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), - // _ => value - // }; - - // rowValues.Add(tempValue); - // } - // else - // { - // rowValues.Add(value); - // } - - // } - - //} - values.Add(rowValues); //如果指定了路径 @@ -573,16 +534,20 @@ namespace JiShe.CollectBus.IoTDB.Provider var results = new List(); var metadata = await GetMetadata(); - var properties = typeof(T).GetProperties(); + var accessor = SourceEntityAccessorFactory.GetAccessor(); + var memberCache = new Dictionary(); // 缓存优化查询 + + // 预构建成员缓存(Key: NameOrPath) + foreach (var member in accessor.MemberList) + { + memberCache[member.NameOrPath] = member; + } var columns = new List() { "Timestamps" }; var dataTypes = new List() { TSDataType.TIMESTAMP }; columns.AddRange(metadata.ColumnNames); dataTypes.AddRange(metadata.DataTypes); - //metadata.ColumnNames.Insert(0, "Timestamps"); - //metadata.DataTypes.Insert(0, TSDataType.TIMESTAMP); - var accessor = SourceEntityAccessorFactory.GetAccessor(); while (dataSet.HasNext() && results.Count < pageSize) { @@ -598,23 +563,20 @@ namespace JiShe.CollectBus.IoTDB.Provider var value = record.Values[indexOf]; TSDataType tSDataType = dataTypes[indexOf]; - var prop = properties.FirstOrDefault(p => - p.Name.Equals(measurement, StringComparison.OrdinalIgnoreCase)); - if (prop != null && !(value is System.DBNull)) + if (!memberCache.TryGetValue(measurement, out var member) && !(value is System.DBNull)) { - dynamic tempValue = GetTSDataValue(tSDataType, value); + throw new Exception($"{nameof(ParseResults)} 解析查询结果 {accessor.EntityName} 属性赋值出现异常,没有找到{measurement}对应的 member信息"); + } - if (measurement.ToLower().EndsWith("time")) - { - //typeof(T).GetProperty(measurement)?.SetValue(entity, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); + dynamic tempValue = GetTSDataValue(tSDataType, value); - accessor.SetPropertyValue(entity, measurement, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); - } - else - { - accessor.SetPropertyValue(entity, measurement, tempValue); - //typeof(T).GetProperty(measurement)?.SetValue(entity, tempValue); - } + if (measurement.ToLower().EndsWith("time")) + { + member.Setter(entity, TimestampHelper.ConvertToDateTime(tempValue, TimestampUnit.Nanoseconds)); + } + else + { + member.Setter(entity, tempValue); } } @@ -634,83 +596,58 @@ namespace JiShe.CollectBus.IoTDB.Provider private List CollectColumnMetadata(ISourceEntityAccessor accessor) { var columns = new List(); + var memberCache = new Dictionary(); // 缓存优化查询 + + // 预构建成员缓存(Key: NameOrPath) + foreach (var member in accessor.MemberList) + { + memberCache[member.NameOrPath] = member; + } foreach (var member in accessor.MemberList) { - //元组的子项字段详情不处理。 - if (member.NameOrPath.Contains(".Item")) - { - continue; - } - - string declaredTypeName = string.Empty; + // 过滤元组子项 + if (member.NameOrPath.Contains(".Item")) continue; - Type declaredType = member.DeclaredType;//属性的类型,如string,int等 + // 类型名称处理 + Type declaredType = member.DeclaredType; + var underlyingType = Nullable.GetUnderlyingType(declaredType); + string declaredTypeName = underlyingType?.Name ?? member.DeclaredTypeName; - // 处理可空类型 - if (declaredType.IsGenericType && declaredType.GetGenericTypeDefinition() == typeof(Nullable<>)) + // 特性查询优化 + var attributes = member.CustomAttributes ?? Enumerable.Empty(); + var tagAttr = attributes.OfType().FirstOrDefault(); + var attrColumn = attributes.OfType().FirstOrDefault(); + var fieldColumn = attributes.OfType().FirstOrDefault(); + var singleMeasuringAttr = attributes.OfType().FirstOrDefault(); + + // 构建ColumnInfo + ColumnInfo? column = null; + if (tagAttr != null) { - Type underlyingType = Nullable.GetUnderlyingType(declaredType); - declaredTypeName = underlyingType.Name; + column = new ColumnInfo(member.NameOrPath, ColumnCategory.TAG, GetDataTypeFromTypeName(declaredTypeName), false); } - else + else if (attrColumn != null) { - declaredTypeName = member.NameOrPath; + column = new ColumnInfo(member.NameOrPath, ColumnCategory.ATTRIBUTE, GetDataTypeFromTypeName(declaredTypeName), false); + } + else if (fieldColumn != null) + { + column = new ColumnInfo(member.NameOrPath, ColumnCategory.FIELD, GetDataTypeFromTypeName(declaredTypeName), false); } - - var tagAttr = member.CustomAttributes?.OfType().FirstOrDefault(); - var attrColumn = member.CustomAttributes?.OfType().FirstOrDefault(); - var fieldColumn = member.CustomAttributes?.OfType().FirstOrDefault(); - - //判断是否是单测数据 - var singleMeasuringAttribute = member.CustomAttributes?.OfType().FirstOrDefault(); - - //先获取Tag标签和属性标签 - ColumnInfo? column = tagAttr != null ? new ColumnInfo( - name: member.NameOrPath, - category: ColumnCategory.TAG, - dataType: GetDataTypeFromTypeName(declaredTypeName), - false - ) : attrColumn != null ? new ColumnInfo( - member.NameOrPath, - ColumnCategory.ATTRIBUTE, - GetDataTypeFromTypeName(declaredTypeName), - false - ) : fieldColumn != null ? new ColumnInfo( - member.NameOrPath, - ColumnCategory.FIELD, - GetDataTypeFromTypeName(declaredTypeName), - false) - : null; - - //检查是不是单侧点模式 - if (singleMeasuringAttribute != null && column == null) + // 单测模式处理 + if (singleMeasuringAttr != null && column == null) { - //warning: 单侧点模式注意事项 - //Entity实体 字段类型是 Tuple,Item1=>测点名称,Item2=>测点值,泛型 - //只有一个Filed字段。 - //MeasuringName 默认为 SingleMeasuringAttribute.FieldName,以便于在获取对应的Value的时候重置为 Item1 的值。 - - Type tupleType = accessor.MemberList.Where(d => d.NameOrPath == $"{member.NameOrPath}.Item2").FirstOrDefault()?.DeclaredType; - - if (tupleType == null) + var tupleItemKey = $"{member.NameOrPath}.Item2"; + if (!memberCache.TryGetValue(tupleItemKey, out var tupleMember)) { - throw new Exception($"{nameof(CollectColumnMetadata)} {accessor.EntityName} {member.NameOrPath} 属性解析异常"); + throw new Exception($"{nameof(CollectColumnMetadata)} {accessor.EntityName} {member.NameOrPath} 单侧点属性解析异常"); } - - column = new ColumnInfo( - member.NameOrPath, - ColumnCategory.FIELD, - GetDataTypeFromTypeName(tupleType.Name), - true - ); + column = new ColumnInfo(member.NameOrPath, ColumnCategory.FIELD, GetDataTypeFromTypeName(tupleMember.DeclaredTypeName), true); } - if (column.HasValue) - { - columns.Add(column.Value); - } + if (column.HasValue) columns.Add(column.Value); } return columns; } @@ -740,15 +677,6 @@ namespace JiShe.CollectBus.IoTDB.Provider ProcessCategory(groupedColumns, ColumnCategory.ATTRIBUTE, metadata); ProcessCategory(groupedColumns, ColumnCategory.FIELD, metadata); - var entityTypeAttribute = typeof(T).GetCustomAttribute(); - - if (entityTypeAttribute == null) - { - throw new ArgumentException($"{nameof(BuildDeviceMetadata)} 构建设备元数据时 {nameof(IoTEntity)} 的EntityType 没有指定,属于异常情况,-101"); - } - - metadata.EntityType = entityTypeAttribute.EntityType; - return metadata; } diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs index b8dbcb4..9162ab0 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs @@ -93,8 +93,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{data.DeviceId}", - DeviceType = $"{data.DeviceType.ToString()}.{IOTDBDataType.Data}", + DeviceType = $"{data.DeviceType.ToString()}", ProjectId = $"{data.ProjectId}", + DataType = IOTDBDataTypeConst.Data, Timestamps = data.TimeSpan!.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity).GetDateTimeOffset().ToUnixTimeNanoseconds(), SingleMeasuring = (data.FiledName ?? string.Empty, data.DataValue ?? default) }; @@ -196,8 +197,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{item.DeviceId}", - DeviceType = $"{item.DeviceType}.{IOTDBDataType.Data}", + DeviceType = $"{item.DeviceType}", ProjectId = $"{item.ProjectId}", + DataType = IOTDBDataTypeConst.Data, Timestamps = item.TimeSpan!.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity).GetDateTimeOffset().ToUnixTimeNanoseconds(), // TODO:这里暂时格式化15分钟数据,需要进行调整 SingleMeasuring =(item.FiledName ?? string.Empty, item.DataValue ?? default) }; @@ -221,7 +223,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData SystemName = _applicationOptions.SystemType, ProjectId = $"{item.ProjectId}", DeviceType = $"{item.DeviceType}", - DeviceId = $"{item.DeviceId}", + DeviceId = $"{item.DeviceId}", Timestamps = DateTime.Now.CheckTimePoint().GetDateTimeOffset().ToUnixTimeNanoseconds(), DatabaseBusiID = item.DatabaseBusiID, PendingCopyReadTime = item.TimeSpan.Value.GetFormatTime(analysisBaseDto.DensityUnit, analysisBaseDto.TimeDensity), @@ -280,8 +282,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{data.DeviceId}", - DeviceType = $"{data.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", + DataType = IOTDBDataTypeConst.Data, Timestamps = timestamps, SingleMeasuring = (data.FiledName!, data.DataValue!) }; @@ -292,8 +295,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{data.DeviceId}", - DeviceType = $"{data.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", + DataType = IOTDBDataTypeConst.Data, Timestamps = timestamps, SingleMeasuring = (ConcentratorStatusFieldConst.FrameData, analysisBaseDto.HexMessage ?? string.Empty) }; @@ -306,9 +310,10 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{data.DeviceId}", - DeviceType = $"{data.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", Timestamps = timestamps, + DataType = IOTDBDataTypeConst.Status, SingleMeasuring = (ConcentratorStatusFieldConst.RecordingTime, (data.TimeSpan.HasValue ? data.TimeSpan.Value : DateTime.Now).GetDateTimeOffset().ToUnixTimeNanoseconds()) }; _runtimeContext.UseTableSessionPool = false; // 使树模型池 @@ -318,8 +323,9 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{data.DeviceId}", - DeviceType = $"{data.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, SingleMeasuring = (ConcentratorStatusFieldConst.Remark, data.FiledDesc ?? string.Empty) }; diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs index ca1d0db..1e1e6cb 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeter.cs @@ -1,12 +1,10 @@ using JiShe.CollectBus.Analyzers.Shared; using JiShe.CollectBus.IoTDB.Attributes; -using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; namespace JiShe.CollectBus.Ammeters { - [EntityType(EntityTypeEnum.TableModel)] - [SourceAnalyzers] + [SourceAnalyzers(EntityTypeEnum.TableModel)] public class ElectricityMeter : IoTEntity { [ATTRIBUTEColumn] diff --git a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs index 5fb6010..49b5abe 100644 --- a/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs +++ b/services/JiShe.CollectBus.Domain/Ammeters/ElectricityMeterTreeModel.cs @@ -1,13 +1,11 @@ using JiShe.CollectBus.Analyzers.Shared; using JiShe.CollectBus.IoTDB.Attributes; -using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; using System; namespace JiShe.CollectBus.Ammeters { - [EntityType(EntityTypeEnum.TreeModel)] - [SourceAnalyzers] + [SourceAnalyzers(EntityTypeEnum.TreeModel)] public class ElectricityMeterTreeModel : IoTEntity { [ATTRIBUTEColumn] diff --git a/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs b/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs index 1d361be..c812f56 100644 --- a/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs +++ b/services/JiShe.CollectBus.Domain/IotSystems/MeterReadingRecords/MeterReadingTelemetryPacketInfo.cs @@ -1,6 +1,5 @@ using JiShe.CollectBus.Analyzers.Shared; using JiShe.CollectBus.IoTDB.Attributes; -using JiShe.CollectBus.IoTDB.Enums; using JiShe.CollectBus.IoTDB.Model; using System; @@ -9,8 +8,7 @@ namespace JiShe.CollectBus.IotSystems.MeterReadingRecords /// /// 抄读任务数据 /// - [EntityType(EntityTypeEnum.TableModel)] - [SourceAnalyzers] + [SourceAnalyzers(EntityTypeEnum.TableModel)] public class MeterReadingTelemetryPacketInfo : IoTEntity { /// diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs index 28520be..523a5df 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/EntityMemberInfo.cs @@ -19,6 +19,11 @@ namespace JiShe.CollectBus.Analyzers.Shared /// public Type DeclaredType { get; set; } + /// + /// 声明的类型的名称 + /// + public string DeclaredTypeName { get; } + /// /// 获取值 /// @@ -38,11 +43,13 @@ namespace JiShe.CollectBus.Analyzers.Shared public EntityMemberInfo( string nameOrPath, Type declaredType, + string declaredTypeName, Func getter, Action setter) { NameOrPath = nameOrPath; this.DeclaredType = declaredType; + DeclaredTypeName = declaredTypeName; Getter = getter; Setter = setter; } diff --git a/modules/JiShe.CollectBus.IoTDB/EnumInfo/EntityTypeEnum.cs b/shared/JiShe.CollectBus.Analyzers.Shared/EntityTypeEnum.cs similarity index 57% rename from modules/JiShe.CollectBus.IoTDB/EnumInfo/EntityTypeEnum.cs rename to shared/JiShe.CollectBus.Analyzers.Shared/EntityTypeEnum.cs index 26c6645..bddaa86 100644 --- a/modules/JiShe.CollectBus.IoTDB/EnumInfo/EntityTypeEnum.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/EntityTypeEnum.cs @@ -1,24 +1,27 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -namespace JiShe.CollectBus.IoTDB.Enums +namespace JiShe.CollectBus.Analyzers.Shared { /// - /// IoTDB实体类型枚举 + /// 实体类型枚举 /// public enum EntityTypeEnum { /// - /// 树模型 + /// IoTDB树模型 /// TreeModel = 1, /// - /// 表模型 + /// IoTDB表模型 /// TableModel = 2, + + /// + /// 其他情况 + /// + Other = 3 } } diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs index a6256ab..2c3a5b0 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/ISourceEntityAccessor.cs @@ -12,6 +12,11 @@ namespace JiShe.CollectBus.Analyzers.Shared /// string EntityName { get; } + /// + /// 实体类型 + /// + EntityTypeEnum? EntityType { get;} + /// /// 获取属性值 /// diff --git a/shared/JiShe.CollectBus.Analyzers.Shared/SourceAnalyzersAttribute.cs b/shared/JiShe.CollectBus.Analyzers.Shared/SourceAnalyzersAttribute.cs index 0b33a6a..ad02607 100644 --- a/shared/JiShe.CollectBus.Analyzers.Shared/SourceAnalyzersAttribute.cs +++ b/shared/JiShe.CollectBus.Analyzers.Shared/SourceAnalyzersAttribute.cs @@ -8,5 +8,12 @@ namespace JiShe.CollectBus.Analyzers.Shared [AttributeUsage(AttributeTargets.Class)] public class SourceAnalyzersAttribute : Attribute { + public EntityTypeEnum EntityType { get; } + + + public SourceAnalyzersAttribute(EntityTypeEnum entityType) + { + EntityType = entityType; + } } } diff --git a/shared/JiShe.CollectBus.Common/Consts/IOTDBDataTypeConst.cs b/shared/JiShe.CollectBus.Common/Consts/IOTDBDataTypeConst.cs new file mode 100644 index 0000000..7c076c9 --- /dev/null +++ b/shared/JiShe.CollectBus.Common/Consts/IOTDBDataTypeConst.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Common.Consts +{ + /// + /// IOTDB数据树类型 + /// + public class IOTDBDataTypeConst + { + /// + /// 数据 + /// + public const string Data = "Data"; + + /// + /// 事件 + /// + public const string Event = "Event"; + + /// + /// 状态 + /// + public const string Status = "Status"; + } +} diff --git a/shared/JiShe.CollectBus.Common/Consts/T37612012PacketItemCodeConst.cs b/shared/JiShe.CollectBus.Common/Consts/T37612012PacketItemCodeConst.cs index 5123fab..1d93ff8 100644 --- a/shared/JiShe.CollectBus.Common/Consts/T37612012PacketItemCodeConst.cs +++ b/shared/JiShe.CollectBus.Common/Consts/T37612012PacketItemCodeConst.cs @@ -151,27 +151,7 @@ namespace JiShe.CollectBus.Common.Consts public const string Ic = "0C_49_Ic"; // 当前电压、电流相位角 } - - /// - /// IOTDB数据树类型 - /// - public class IOTDBDataType - { - /// - /// 数据 - /// - public const string Data = "Data"; - - /// - /// 事件 - /// - public const string Event = "Event"; - - /// - /// 状态 - /// - public const string Status = "Status"; - } + /// /// 集中器状态字段 From 8d1fc46e8f0fbb37b14c27df354b2a7a6843ae62 Mon Sep 17 00:00:00 2001 From: zenghongyao <873884283@qq.com> Date: Thu, 8 May 2025 17:33:07 +0800 Subject: [PATCH 14/15] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AnalysisData/DataStorage.cs | 27 ++++++++++--------- .../Pages/Monitor.cshtml | 1 + 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs index e3421d1..d43276d 100644 --- a/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs +++ b/protocols/JiShe.CollectBus.Protocol.T37612012/AnalysisData/DataStorage.cs @@ -284,7 +284,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData DeviceId = $"{data.DeviceId}", DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", - DataType = IOTDBDataTypeConst.Data, + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, SingleMeasuring = (data.FiledName!, data.DataValue!) }; @@ -297,7 +297,7 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData DeviceId = $"{data.DeviceId}", DeviceType = $"{data.DeviceType}", ProjectId = $"{data.ProjectId}", - DataType = IOTDBDataTypeConst.Data, + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, SingleMeasuring = (ConcentratorStatusFieldConst.FrameData, analysisBaseDto.HexMessage ?? string.Empty) }; @@ -359,10 +359,11 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData { SystemName = _applicationOptions.SystemType, DeviceId = $"{item.DeviceId}", - DeviceType = $"{item.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{item.DeviceType}", ProjectId = $"{item.ProjectId}", + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, - SingleMeasuring = new Tuple(item.FiledName!, item.DataValue!) + SingleMeasuring = (item.FiledName!, item.DataValue!) }; _runtimeContext.UseTableSessionPool = false; // 使树模型池 await _dbProvider.InsertAsync(treeData); @@ -370,11 +371,11 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData var treeFrameData = new TreeModelSingleMeasuringEntity() { SystemName = _applicationOptions.SystemType, - DeviceId = $"{item.DeviceId}", - DeviceType = $"{item.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{item.DeviceType}", ProjectId = $"{item.ProjectId}", + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, - SingleMeasuring = new Tuple(ConcentratorStatusFieldConst.FrameData, analysisBaseDto.HexMessage ?? string.Empty) + SingleMeasuring = (ConcentratorStatusFieldConst.FrameData, analysisBaseDto.HexMessage ?? string.Empty) }; _runtimeContext.UseTableSessionPool = false; // 使树模型池 @@ -384,11 +385,11 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData var treeRecordingTimeData = new TreeModelSingleMeasuringEntity() { SystemName = _applicationOptions.SystemType, - DeviceId = $"{item.DeviceId}", - DeviceType = $"{item.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{item.DeviceType}", ProjectId = $"{item.ProjectId}", + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, - SingleMeasuring = new Tuple(ConcentratorStatusFieldConst.RecordingTime, (item.TimeSpan.HasValue ? item.TimeSpan.Value : DateTime.Now).GetDateTimeOffset().ToUnixTimeNanoseconds()) + SingleMeasuring = (ConcentratorStatusFieldConst.RecordingTime, (item.TimeSpan.HasValue ? item.TimeSpan.Value : DateTime.Now).GetDateTimeOffset().ToUnixTimeNanoseconds()) }; _runtimeContext.UseTableSessionPool = false; // 使树模型池 await _dbProvider.InsertAsync(treeRecordingTimeData); @@ -396,11 +397,11 @@ namespace JiShe.CollectBus.Protocol.T37612012.AnalysisData var treeRemarkData = new TreeModelSingleMeasuringEntity() { SystemName = _applicationOptions.SystemType, - DeviceId = $"{item.DeviceId}", - DeviceType = $"{item.DeviceType}.{IOTDBDataType.Status}", + DeviceType = $"{item.DeviceType}", ProjectId = $"{item.ProjectId}", + DataType = IOTDBDataTypeConst.Status, Timestamps = timestamps, - SingleMeasuring = new Tuple(ConcentratorStatusFieldConst.Remark, item.FiledDesc ?? string.Empty) + SingleMeasuring =(ConcentratorStatusFieldConst.Remark, item.FiledDesc ?? string.Empty) }; _runtimeContext.UseTableSessionPool = false; // 使树模型池 await _dbProvider.InsertAsync(treeRemarkData); diff --git a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml index a58ded5..30e91e8 100644 --- a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml +++ b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml @@ -16,6 +16,7 @@ 后端服务 + From 541c118dbbe06600f9546eeb3c7b17e8ef369e37 Mon Sep 17 00:00:00 2001 From: ChenYi <296215406@outlook.com> Date: Thu, 8 May 2025 22:44:01 +0800 Subject: [PATCH 15/15] =?UTF-8?q?=E4=BF=AE=E5=A4=8DIoTDB=E9=A9=B1=E5=8A=A8?= =?UTF-8?q?=E9=80=82=E9=85=8D=E5=A2=9E=E9=87=8F=E6=BA=90=E7=A0=81=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=99=A8=E4=BB=A5=E5=90=8E=EF=BC=8C=E5=8D=95=E4=BE=A7?= =?UTF-8?q?=E7=82=B9=E6=A8=A1=E5=BC=8F=E5=A4=B1=E6=95=88=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Exceptions/IoTException.cs | 22 + .../JiShe.CollectBus.IoTDB.csproj | 3 +- .../Provider/IoTDBProvider.cs | 430 +++++++++++++----- .../BasicScheduledMeterReadingService.cs | 20 +- .../Helpers/CommonHelper.cs | 17 +- .../Pages/Monitor.cshtml | 3 +- web/JiShe.CollectBus.Host/appsettings.json | 2 +- 7 files changed, 370 insertions(+), 127 deletions(-) create mode 100644 modules/JiShe.CollectBus.IoTDB/Exceptions/IoTException.cs diff --git a/modules/JiShe.CollectBus.IoTDB/Exceptions/IoTException.cs b/modules/JiShe.CollectBus.IoTDB/Exceptions/IoTException.cs new file mode 100644 index 0000000..93bed4f --- /dev/null +++ b/modules/JiShe.CollectBus.IoTDB/Exceptions/IoTException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.IoTDB.Exceptions +{ + /// + /// IoTDB异常 + /// + public class IoTException : Exception + { + public int ErrorCode { get; } + + public IoTException(string message, int errorCode) + : base($"{message} (Code: {errorCode})") + { + ErrorCode = errorCode; + } + } +} diff --git a/modules/JiShe.CollectBus.IoTDB/JiShe.CollectBus.IoTDB.csproj b/modules/JiShe.CollectBus.IoTDB/JiShe.CollectBus.IoTDB.csproj index 3911399..78b81e3 100644 --- a/modules/JiShe.CollectBus.IoTDB/JiShe.CollectBus.IoTDB.csproj +++ b/modules/JiShe.CollectBus.IoTDB/JiShe.CollectBus.IoTDB.csproj @@ -14,7 +14,6 @@ - + diff --git a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs index bacbf61..db86791 100644 --- a/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs +++ b/modules/JiShe.CollectBus.IoTDB/Provider/IoTDBProvider.cs @@ -21,6 +21,7 @@ using Microsoft.Extensions.Logging; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; using JiShe.CollectBus.Analyzers.Shared; +using JiShe.CollectBus.IoTDB.Exceptions; namespace JiShe.CollectBus.IoTDB.Provider { @@ -250,128 +251,337 @@ namespace JiShe.CollectBus.IoTDB.Provider } } + ///// + ///// 构建Tablet + ///// + ///// + ///// 表实体 + ///// 设备元数据 + ///// + //private Tablet BuildTablet(IEnumerable entities, DeviceMetadata metadata) where T : IoTEntity + //{ + // var timestamps = new List(); + // var values = new List>(); + // var devicePaths = new HashSet(); + // List tempColumnNames = new List(); + // tempColumnNames.AddRange(metadata.ColumnNames); + + // var accessor = SourceEntityAccessorFactory.GetAccessor(); + + // var memberCache = new Dictionary(); // 缓存优化查询 + // // 预构建成员缓存(Key: NameOrPath) + // foreach (var member in accessor.MemberList) + // { + // memberCache[member.NameOrPath] = member; + // } + + // if (accessor.EntityType == null || metadata.EntityType == null) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 没有指定,属于异常情况,-101"); + // } + + // if (metadata.EntityType != accessor.EntityType) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 和{nameof(DeviceMetadata)}的 EntityType 不一致,属于异常情况,-102"); + // } + + // if (metadata.EntityType == EntityTypeEnum.TreeModel && _runtimeContext.UseTableSessionPool == true) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 tree模型不能使用table模型Session连接,属于异常情况,-103"); + // } + // else if (metadata.EntityType == EntityTypeEnum.TableModel && _runtimeContext.UseTableSessionPool == false) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 table模型不能使用tree模型Session连接,属于异常情况,-104"); + // } + + // string tableNameOrTreePath = string.Empty; + // var tableNameOrTreePathAttribute = typeof(T).GetCustomAttribute(); + // if (tableNameOrTreePathAttribute != null) + // { + // tableNameOrTreePath = tableNameOrTreePathAttribute.TableNameOrTreePath; + // } + + // foreach (var entity in entities) + // { + // timestamps.Add(entity.Timestamps); + // var rowValues = new List(); + + // foreach (var measurement in metadata.ColumnNames) + // { + // if (!memberCache.TryGetValue(measurement, out var member)) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName}没有找到{measurement}对应的member信息,-105"); + // } + + // var value = member.GetValue(entity); + + // // 特性查询优化 + // var attributes = member.CustomAttributes ?? Enumerable.Empty(); + // var singleMeasuringAttr = attributes.OfType().FirstOrDefault(); + // if (singleMeasuringAttr != null)//如果是单侧点 + // { + + // var tupleItem1Key = $"{member.NameOrPath}.Item1"; + // if (!memberCache.TryGetValue(tupleItem1Key, out var tuple1Member)) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName} 没有找到{measurement}对应的member Item1 信息,-106"); + // } + // int indexOf = metadata.ColumnNames.IndexOf(measurement); + // tempColumnNames[indexOf] = (string)tuple1Member.GetValue(entity); + + // var tupleItem2Key = $"{member.NameOrPath}.Item2"; + // if (!memberCache.TryGetValue(tupleItem2Key, out var tuple2Member)) + // { + // throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName} 没有找到{measurement}对应的member Item2 信息,-107"); + // } + + // value = tuple2Member.GetValue(entity); + // } + + // if (value != null) + // { + // var tempValue = member.DeclaredTypeName.ToUpper() switch + // { + // "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), + // _ => value + // }; + + // rowValues.Add(tempValue); + // } + // else + // { + // rowValues.Add(value); + // } + // } + + // values.Add(rowValues); + + // //如果指定了路径 + // if (!string.IsNullOrWhiteSpace(tableNameOrTreePath)) + // { + // devicePaths.Add(tableNameOrTreePath); + // } + // else + // { + // if (!_runtimeContext.UseTableSessionPool)//树模型 + // { + // devicePaths.Add(DevicePathBuilder.GetDevicePath(entity)); + // } + // else + // { + // devicePaths.Add(DevicePathBuilder.GetTableName()); + // } + // } + // } + + // if (devicePaths.Count > 1) + // { + // throw new Exception($"{nameof(BuildTablet)} 构建Tablet《{typeof(T).Name}》时,批量插入的设备路径不一致。"); + // } + + // return _runtimeContext.UseTableSessionPool + // ? BuildTableSessionTablet(metadata, devicePaths.First(), tempColumnNames, values, timestamps) + // : BuildSessionTablet(metadata, devicePaths.First(), tempColumnNames,values, timestamps); + //} + /// /// 构建Tablet /// /// - /// 表实体 + /// 表实体集合 /// 设备元数据 /// private Tablet BuildTablet(IEnumerable entities, DeviceMetadata metadata) where T : IoTEntity { - var timestamps = new List(); - var values = new List>(); - var devicePaths = new HashSet(); - List tempColumnNames = new List(); - tempColumnNames.AddRange(metadata.ColumnNames); - - var accessor = SourceEntityAccessorFactory.GetAccessor(); + // 前置校验 + ValidateMetadataAndAccessor(metadata, out var accessor); - var memberCache = new Dictionary(); // 缓存优化查询 - // 预构建成员缓存(Key: NameOrPath) - foreach (var member in accessor.MemberList) + // 初始化数据结构 + var (timestamps, values, devicePaths) = (new List(), new List>(), new HashSet()); + var tempColumnNames = new List(metadata.ColumnNames); + var memberCache = BuildMemberCache(accessor); + var tableNameOrTreePath = GetTableNameOrTreePath(); + + // 处理每个实体 + foreach (var entity in entities) { - memberCache[member.NameOrPath] = member; + ProcessEntity(entity, accessor, metadata, memberCache, tempColumnNames, timestamps, values); + UpdateDevicePaths(entity, tableNameOrTreePath, devicePaths); } + // 后置校验与返回 + ValidateDevicePaths(devicePaths); + // return CreateFinalTablet(metadata, devicePaths.First(), tempColumnNames, values, timestamps); + return _runtimeContext.UseTableSessionPool + ? BuildTableSessionTablet(metadata, devicePaths.First(), tempColumnNames, values, timestamps) + : BuildSessionTablet(metadata, devicePaths.First(), tempColumnNames, values, timestamps); + } + + private void ValidateMetadataAndAccessor(DeviceMetadata metadata, out ISourceEntityAccessor accessor) where T : IoTEntity + { + accessor = SourceEntityAccessorFactory.GetAccessor(); + if (accessor.EntityType == null || metadata.EntityType == null) { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 没有指定,属于异常情况,-101"); + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,EntityType未指定", -101); } if (metadata.EntityType != accessor.EntityType) { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 {nameof(T)}的EntityType 和{nameof(DeviceMetadata)}的 EntityType 不一致,属于异常情况,-102"); + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,EntityType不一致", -102); } - if (metadata.EntityType == EntityTypeEnum.TreeModel && _runtimeContext.UseTableSessionPool == true) + bool isTableModel = accessor.EntityType == EntityTypeEnum.TableModel; + if (_runtimeContext.UseTableSessionPool != isTableModel) { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 tree模型不能使用table模型Session连接,属于异常情况,-103"); + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,Session类型不匹配: 预期{(isTableModel ? "Table" : "Tree")}模型", isTableModel ? -104 : -103); } - else if (metadata.EntityType == EntityTypeEnum.TableModel && _runtimeContext.UseTableSessionPool == false) + } + + /// + /// 处理实体并获取值 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void ProcessEntity( + T entity, + ISourceEntityAccessor accessor, + DeviceMetadata metadata, + Dictionary memberCache, + List tempColumnNames, + List timestamps, + List> values) where T : IoTEntity + { + timestamps.Add(entity.Timestamps); + var rowValues = new object[metadata.ColumnNames.Count]; + + Parallel.ForEach(metadata.ColumnNames, (measurement, state, index) => { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构{nameof(Tablet)}时 table模型不能使用tree模型Session连接,属于异常情况,-104"); - } - - string tableNameOrTreePath = string.Empty; - var tableNameOrTreePathAttribute = typeof(T).GetCustomAttribute(); - if (tableNameOrTreePathAttribute != null) - { - tableNameOrTreePath = tableNameOrTreePathAttribute.TableNameOrTreePath; - } - - foreach (var entity in entities) - { - timestamps.Add(entity.Timestamps); - var rowValues = new List(); - - foreach (var measurement in tempColumnNames) - { - if (!memberCache.TryGetValue(measurement, out var member)) - { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName}没有找到{measurement}对应的member信息,-105"); - } - - var value = member.GetValue(entity); - - // 特性查询优化 - var attributes = member.CustomAttributes ?? Enumerable.Empty(); - var singleMeasuringAttr = attributes.OfType().FirstOrDefault(); - if (singleMeasuringAttr != null)//如果是单侧点 - { - var tupleItemKey = $"{member.NameOrPath}.Item2"; - if (!memberCache.TryGetValue(tupleItemKey, out var tupleMember)) - { - throw new ArgumentException($"{nameof(BuildTablet)} 构建存储结构时{accessor.EntityName} 没有找到{measurement}对应的member Item2 信息,-106"); - } - - value = tupleMember.GetValue(entity); - } - - if (value != null) - { - var tempValue = member.DeclaredTypeName.ToUpper() switch - { - "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), - _ => value - }; - - rowValues.Add(tempValue); - } - else - { - rowValues.Add(value); - } - } - - values.Add(rowValues); - - //如果指定了路径 - if (!string.IsNullOrWhiteSpace(tableNameOrTreePath)) + if (!memberCache.TryGetValue(measurement, out var member)) { - devicePaths.Add(tableNameOrTreePath); + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,找不到成员: {measurement}", -105); } - else + + object value = ResolveMemberValue(entity, member, memberCache, tempColumnNames, (int)index); + rowValues[index] = ConvertValueByType(member, value); + }); + + values.Add(rowValues.ToList()); + } + + private object ResolveMemberValue( + T entity, + EntityMemberInfo member, + Dictionary memberCache, + List tempColumnNames, + int columnIndex) where T : IoTEntity + { + // 单测点逻辑 + if (member.CustomAttributes?.OfType().FirstOrDefault() is { } attr) + { + var tuple1Key = $"{member.NameOrPath}.Item1"; + var tuple2Key = $"{member.NameOrPath}.Item2"; + + if (!memberCache.TryGetValue(tuple1Key, out var tuple1) || !memberCache.TryGetValue(tuple2Key, out var tuple2)) { - if (!_runtimeContext.UseTableSessionPool)//树模型 - { - devicePaths.Add(DevicePathBuilder.GetDevicePath(entity)); - } - else - { - devicePaths.Add(DevicePathBuilder.GetTableName()); - } + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,单侧点元组成员缺失", -106); } + + tempColumnNames[columnIndex] = (string)tuple1.GetValue(entity); + return tuple2.GetValue(entity); + } + return member.GetValue(entity); + } + + /// + /// 设置实体的成员值 + /// + /// + /// + /// + private object ConvertValueByType(EntityMemberInfo member, object value) + { + return member.DeclaredTypeName switch + { + "DATETIME" => Convert.ToDateTime(value).GetDateTimeOffset().ToUnixTimeNanoseconds(), + _ => value + }; + } + + /// + /// 处理设备路径 + /// + /// + /// + /// + /// + private void UpdateDevicePaths( + T entity, + string tableNameOrTreePath, + HashSet devicePaths) where T : IoTEntity + { + if (!string.IsNullOrEmpty(tableNameOrTreePath)) + { + devicePaths.Add(tableNameOrTreePath); + return; + } + + var path = _runtimeContext.UseTableSessionPool + ? DevicePathBuilder.GetTableName() + : DevicePathBuilder.GetDevicePath(entity); + devicePaths.Add(path); + } + + /// + /// 验证设备路径 + /// + /// + private void ValidateDevicePaths(HashSet devicePaths) + { + if (devicePaths.Count == 0) + { + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,设备路径集合为空", -108); } if (devicePaths.Count > 1) { - throw new Exception($"{nameof(BuildTablet)} 构建Tablet《{typeof(T).Name}》时,批量插入的设备路径不一致。"); + var paths = string.Join(", ", devicePaths.Take(3)); + { + throw new IoTException($"{nameof(BuildTablet)} 构建IoTDB数据结构时,设备路径不一致。检测到路径: {paths}...", -109); + } } + } - return _runtimeContext.UseTableSessionPool - ? BuildTableSessionTablet(metadata, devicePaths.First(), values, timestamps) - : BuildSessionTablet(metadata, devicePaths.First(), values, timestamps); + /// + /// 缓存优化:避免重复反射 + /// + /// + /// + private string GetTableNameOrTreePath() + { + return AttributeCache.TableNameOrTreePath; + } + + /// + /// 特性缓存辅助类 + /// + /// + private static class AttributeCache + { + public static readonly string TableNameOrTreePath; + + static AttributeCache() + { + var attr = typeof(T).GetCustomAttribute(); + TableNameOrTreePath = attr?.TableNameOrTreePath ?? string.Empty; + } } /// @@ -379,16 +589,17 @@ namespace JiShe.CollectBus.IoTDB.Provider /// /// 已解析的设备数据元数据 /// 设备路径 + /// 数据列集合 /// 数据集合 /// 时间戳集合 /// - private Tablet BuildSessionTablet(DeviceMetadata metadata, string devicePath, List> values, List timestamps) + private Tablet BuildSessionTablet(DeviceMetadata metadata, string devicePath, List columns, List> values, List timestamps) { //todo 树模型需要去掉TAG类型和ATTRIBUTE类型的字段,只需要保留FIELD类型字段即可 return new Tablet( devicePath, - metadata.ColumnNames, + columns, metadata.DataTypes, values, timestamps @@ -400,14 +611,15 @@ namespace JiShe.CollectBus.IoTDB.Provider /// /// 已解析的设备数据元数据 /// 表名称 + /// 数据列集合 /// 数据集合 /// 时间戳集合 /// - private Tablet BuildTableSessionTablet(DeviceMetadata metadata, string tableName, List> values, List timestamps) + private Tablet BuildTableSessionTablet(DeviceMetadata metadata, string tableName, List columns,List> values, List timestamps) { var tablet = new Tablet( tableName, - metadata.ColumnNames, + columns, metadata.ColumnCategories, metadata.DataTypes, values, @@ -535,13 +747,7 @@ namespace JiShe.CollectBus.IoTDB.Provider var metadata = await GetMetadata(); var accessor = SourceEntityAccessorFactory.GetAccessor(); - var memberCache = new Dictionary(); // 缓存优化查询 - - // 预构建成员缓存(Key: NameOrPath) - foreach (var member in accessor.MemberList) - { - memberCache[member.NameOrPath] = member; - } + var memberCache = BuildMemberCache(accessor); var columns = new List() { "Timestamps" }; var dataTypes = new List() { TSDataType.TIMESTAMP }; @@ -596,13 +802,7 @@ namespace JiShe.CollectBus.IoTDB.Provider private List CollectColumnMetadata(ISourceEntityAccessor accessor) { var columns = new List(); - var memberCache = new Dictionary(); // 缓存优化查询 - - // 预构建成员缓存(Key: NameOrPath) - foreach (var member in accessor.MemberList) - { - memberCache[member.NameOrPath] = member; - } + var memberCache = BuildMemberCache(accessor); foreach (var member in accessor.MemberList) { @@ -807,5 +1007,21 @@ namespace JiShe.CollectBus.IoTDB.Provider TSDataType.STRING => Convert.ToString(value), _ => Convert.ToString(value) }; + + /// + /// 缓存实体属性信息 + /// + /// + /// + /// + private Dictionary BuildMemberCache(ISourceEntityAccessor accessor) + { + var cache = new Dictionary(StringComparer.Ordinal); + foreach (var member in accessor.MemberList) + { + cache[member.NameOrPath] = member; + } + return cache; + } } } diff --git a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs index 32a1d7c..bab879d 100644 --- a/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs +++ b/services/JiShe.CollectBus.Application/ScheduledMeterReading/BasicScheduledMeterReadingService.cs @@ -7,8 +7,9 @@ using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.DataChannels; +using JiShe.CollectBus.DataMigration.Options; using JiShe.CollectBus.GatherItem; -using JiShe.CollectBus.IoTDB.Context; using JiShe.CollectBus.IoTDB.Interface; using JiShe.CollectBus.IoTDB.Model; using JiShe.CollectBus.IoTDB.Options; @@ -17,8 +18,8 @@ using JiShe.CollectBus.IotSystems.Ammeters; using JiShe.CollectBus.IotSystems.MeterReadingRecords; using JiShe.CollectBus.IotSystems.Watermeter; using JiShe.CollectBus.Kafka.Internal; -using JiShe.CollectBus.Kafka.Producer; using JiShe.CollectBus.Protocol.Interfaces; +using JiShe.CollectBus.Protocol.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; @@ -26,14 +27,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using JiShe.CollectBus.Protocol.Models; -using System.Threading.Channels; -using static IdentityModel.ClaimComparer; -using JiShe.CollectBus.DataChannels; -using JiShe.CollectBus.DataMigration.Options; -using static System.Runtime.InteropServices.JavaScript.JSType; -using static System.Formats.Asn1.AsnWriter; -using System.Threading; namespace JiShe.CollectBus.ScheduledMeterReading { @@ -329,7 +322,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading /// public virtual async Task InitAmmeterCacheData(string gatherCode = "") { - return; + //return; // 创建取消令牌源 //var cts = new CancellationTokenSource(); @@ -744,7 +737,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading ItemCode = tempItem, DataTimeMark = new Protocol.DataTimeMark() { - Density = ammeterInfo.TimeDensity,//todo 转换成协议的值 + Density = ammeterInfo.TimeDensity.GetDensity(),//转换成协议的值 Point = 1, DataTime = timestamps, } @@ -1354,7 +1347,6 @@ namespace JiShe.CollectBus.ScheduledMeterReading } List taskList = new List(); - var metadata = await _dbProvider.GetMetadata(); var itemCode = T37612012PacketItemCodeConst.AFN09HFN01H; //var subItemCode = T6452007PacketItemCodeConst.C08; @@ -1673,7 +1665,7 @@ namespace JiShe.CollectBus.ScheduledMeterReading IsReceived = false, ScoreValue = $"{ammeterInfo.FocusAddress}.{taskMark}".Md5Fun(), }; - } + } #endregion } diff --git a/shared/JiShe.CollectBus.Common/Helpers/CommonHelper.cs b/shared/JiShe.CollectBus.Common/Helpers/CommonHelper.cs index 648c1aa..e3177a1 100644 --- a/shared/JiShe.CollectBus.Common/Helpers/CommonHelper.cs +++ b/shared/JiShe.CollectBus.Common/Helpers/CommonHelper.cs @@ -859,6 +859,21 @@ namespace JiShe.CollectBus.Common.Helpers } - + /// + /// 采集频率转换为集中器采集密度 + /// + /// + /// + public static int GetDensity(this int timeDensity) => + timeDensity switch + { + 0 => 0,//无 + 1 => 255,//1分钟 + 5 => 245,//5分钟 + 15 => 1,//15分钟 + 30 => 2,//30分钟 + 60 => 3,//60分钟 + _ => -1//采集项本身无密度位 + }; } } diff --git a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml index 30e91e8..9509b08 100644 --- a/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml +++ b/web/JiShe.CollectBus.Host/Pages/Monitor.cshtml @@ -15,8 +15,7 @@ - 后端服务 - + 后端服务 diff --git a/web/JiShe.CollectBus.Host/appsettings.json b/web/JiShe.CollectBus.Host/appsettings.json index 7034d26..43f1723 100644 --- a/web/JiShe.CollectBus.Host/appsettings.json +++ b/web/JiShe.CollectBus.Host/appsettings.json @@ -141,7 +141,7 @@ } }, "ServerApplicationOptions": { - "ServerTagName": "JiSheCollectBus99", + "ServerTagName": "JiSheCollectBus4", "SystemType": "Energy", "FirstCollectionTime": "2025-04-28 15:07:00", "AutomaticVerificationTime": "16:07:00",