Compare commits

..

No commits in common. "d18f60f9a799a298a240133db36b89c2c1a4267d" and "c5c428f551b757ce4c8d9f8ba83f684fe709636c" have entirely different histories.

23 changed files with 107 additions and 382 deletions

View File

@ -62,8 +62,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "0.Docs", "0.Docs", "{D8346C
readme.md = readme.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JiShe.CollectBus.IncrementalGenerator", "shared\JiShe.CollectBus.IncrementalGenerator\JiShe.CollectBus.IncrementalGenerator.csproj", "{828D20BC-454E-0467-B29D-429B25F1E0CA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -150,10 +148,6 @@ Global
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Release|Any CPU.Build.0 = Release|Any CPU
{828D20BC-454E-0467-B29D-429B25F1E0CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{828D20BC-454E-0467-B29D-429B25F1E0CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{828D20BC-454E-0467-B29D-429B25F1E0CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{828D20BC-454E-0467-B29D-429B25F1E0CA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -179,7 +173,6 @@ Global
{8A61DF78-069B-40B5-8811-614E2960443E} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{E27377CC-E2D3-4237-060F-96EA214D3129} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{75B7D419-C261-577D-58D6-AA3ACED9129F} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{828D20BC-454E-0467-B29D-429B25F1E0CA} = {EBF7C01F-9B4F-48E6-8418-2CBFDA51EB0B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4324B3B4-B60B-4E3C-91D8-59576B4E26DD}

View File

@ -1,17 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Apache.IoTDB" Version="2.0.2" />
<PackageReference Include="Volo.Abp" Version="8.3.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.IncrementalGenerator\JiShe.CollectBus.IncrementalGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
</ItemGroup>
</Project>

View File

@ -1,10 +1,9 @@
using JiShe.CollectBus.Common.Attributes;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Attribute;
namespace JiShe.CollectBus.IoTDB.Model
{
/// <summary>
/// IoT实体基类此类适用于多个数据测点记录场景单个测点请使用子类 SingleMeasuring,新增字段只能现有字段末尾添加,否则会导致数据写入失败。
/// IoT实体基类此类适用于多个数据测点记录场景单个测点请使用子类 SingleMeasuring
/// </summary>
public abstract class IoTEntity
{

View File

@ -1,6 +1,11 @@
using JiShe.CollectBus.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Enums;
using JiShe.CollectBus.IoTDB.Provider;
namespace JiShe.CollectBus.IoTDB.Model
{
@ -8,7 +13,6 @@ namespace JiShe.CollectBus.IoTDB.Model
/// Table模型单项数据实体
/// </summary>
[EntityType(EntityTypeEnum.TableModel)]
[GenerateAccessors]
public class TableModelSingleMeasuringEntity<T> : IoTEntity
{
/// <summary>

View File

@ -1,6 +1,11 @@
using JiShe.CollectBus.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Enums;
using JiShe.CollectBus.IoTDB.Provider;
namespace JiShe.CollectBus.IoTDB.Model
{
@ -8,7 +13,6 @@ namespace JiShe.CollectBus.IoTDB.Model
/// Tree模型单项数据实体
/// </summary>
[EntityType(EntityTypeEnum.TreeModel)]
[GenerateAccessors]
public class TreeModelSingleMeasuringEntity<T> : IoTEntity
{
/// <summary>

View File

@ -26,7 +26,7 @@
/// <summary>
/// 连接池大小
/// </summary>
public int PoolSize { get; set; } = 8;
public int PoolSize { get; set; } = 2;
/// <summary>
/// 查询时每次查询的数据量默认1024

View File

@ -70,7 +70,7 @@ namespace JiShe.CollectBus.IoTDB.Provider
var result = await _sessionPool.InsertAlignedTabletAsync(tablet);
if (result != 0)
{
throw new Exception($"{nameof(SessionPoolAdapter)} Tree模型数据入库没有成功返回结果为{result}请检查IoTEntity继承子类属性索引是否有变动。");
throw new Exception($"{nameof(SessionPoolAdapter)} Tree模型数据入库没有成功返回结果为{result}");
}
//await CloseAsync();
return result;

View File

@ -68,7 +68,7 @@ namespace JiShe.CollectBus.IoTDB.Provider
var result = await _sessionPool.InsertAsync(tablet);
if (result != 0)
{
throw new Exception($"{nameof(TableSessionPoolAdapter)} table模型数据入库没有成功返回结果为{result}请检查IoTEntity继承子类属性索引是否有变动。");
throw new Exception($"{nameof(TableSessionPoolAdapter)} table模型数据入库没有成功返回结果为{result}");
}
//await CloseAsync();

View File

@ -66,17 +66,12 @@ public class CollectBusApplicationModule : AbpModule
.ToList();
foreach (var type in types) await context.AddBackgroundWorkerAsync(type);
//Task.Run(() =>
//{
// //默认初始化表计信息
// var dbContext = context.ServiceProvider.GetRequiredService<EnergySystemScheduledMeterReadingService>();
// dbContext.InitAmmeterCacheData();
// //await dbContext.InitWatermeterCacheData();
//}).ConfigureAwait(false);
//默认初始化表计信息
var dbContext = context.ServiceProvider.GetRequiredService<EnergySystemScheduledMeterReadingService>();
_= dbContext.InitAmmeterCacheData();
Task.Run(() =>
{
//默认初始化表计信息
var dbContext = context.ServiceProvider.GetRequiredService<EnergySystemScheduledMeterReadingService>();
dbContext.InitAmmeterCacheData();
//await dbContext.InitWatermeterCacheData();
}).ConfigureAwait(false);
}
}

View File

@ -30,7 +30,6 @@
<ProjectReference Include="..\..\modules\JiShe.CollectBus.FreeRedis\JiShe.CollectBus.FreeRedis.csproj" />
<ProjectReference Include="..\..\modules\JiShe.CollectBus.Kafka\JiShe.CollectBus.Kafka.csproj" />
<ProjectReference Include="..\..\modules\JiShe.CollectBus.MongoDB\JiShe.CollectBus.MongoDB.csproj" />
</ItemGroup>
</Project>

View File

@ -66,7 +66,6 @@ public class SampleAppService : CollectBusAppService, ISampleAppService, IKafkaS
IssuedMessageHexString = "messageHexString",
Timestamps = testTime// DateTimeOffset.UtcNow.ToUnixTimeNanoseconds()//testTime.GetDateTimeOffset().ToUnixTimeNanoseconds(),
};
await _iotDBProvider.InsertAsync(meter);
}

View File

@ -286,51 +286,52 @@ namespace JiShe.CollectBus.ScheduledMeterReading
public virtual async Task InitAmmeterCacheData(string gatherCode = "")
{
//此处代码不要删除
#if DEBUG
var timeDensity = "15";
var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
//#if DEBUG
// var timeDensity = "15";
// var redisCacheMeterInfoHashKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoHashKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
// var redisCacheMeterInfoSetIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoSetIndexKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
// var redisCacheMeterInfoZSetScoresIndexKeyTemp = $"{string.Format(RedisConst.CacheMeterInfoZSetScoresIndexKey, SystemType, "JiSheCollectBus2", MeterTypeEnum.Ammeter, timeDensity)}";
List<AmmeterInfo> meterInfos = new List<AmmeterInfo>();
List<string> focusAddressDataLista = new List<string>();
var timer1 = Stopwatch.StartNew();
// List<AmmeterInfo> meterInfos = new List<AmmeterInfo>();
// List<string> focusAddressDataLista = new List<string>();
// var timer1 = Stopwatch.StartNew();
var allIds = new HashSet<string>();
decimal? score = null;
string member = null;
// var allIds = new HashSet<string>();
// decimal? score = null;
// string member = null;
while (true)
{
var page = await _redisDataCacheService.GetAllPagedData<AmmeterInfo>(
redisCacheMeterInfoHashKeyTemp,
redisCacheMeterInfoZSetScoresIndexKeyTemp,
pageSize: 1000,
lastScore: score,
lastMember: member);
// while (true)
// {
// var page = await _redisDataCacheService.GetAllPagedData<AmmeterInfo>(
// redisCacheMeterInfoHashKeyTemp,
// redisCacheMeterInfoZSetScoresIndexKeyTemp,
// pageSize: 1000,
// lastScore: score,
// lastMember: member);
meterInfos.AddRange(page.Items);
focusAddressDataLista.AddRange(page.Items.Select(d => d.FocusAddress));
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.FocusAddress));
// 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);
return;
#else
var meterInfos = await GetAmmeterInfoList(gatherCode);
#endif
// timer1.Stop();
// _logger.LogError($"读取数据总共花费时间{timer1.ElapsedMilliseconds}毫秒");
// DeviceGroupBalanceControl.InitializeCache(focusAddressDataLista, _kafkaOptions.NumPartitions);
// return;
//#else
// var meterInfos = await GetAmmeterInfoList(gatherCode);
//#endif
var meterInfos = await GetAmmeterInfoList(gatherCode);
if (meterInfos == null || meterInfos.Count <= 0)
{
throw new NullReferenceException($"{nameof(InitAmmeterCacheData)} 初始化电表缓存数据时,电表数据为空");

View File

@ -35,7 +35,6 @@ namespace JiShe.CollectBus.ScheduledMeterReading
//[Route($"/energy/app/scheduled")]
public class EnergySystemScheduledMeterReadingService : BasicScheduledMeterReadingService
{
string systemType = string.Empty;
string serverTagName = string.Empty;
private readonly ILogger<BasicScheduledMeterReadingService> _logger;
private readonly IIoTDbProvider _dbProvider;
@ -60,13 +59,12 @@ namespace JiShe.CollectBus.ScheduledMeterReading
applicationOptions)
{
serverTagName = applicationOptions.Value.ServerTagName;
systemType = applicationOptions.Value.SystemType;
_dbProvider = dbProvider;
_logger = logger;
_protocolService = protocolService;
}
public sealed override string SystemType => systemType;
public sealed override string SystemType => SystemTypeConst.Energy;
public sealed override string ServerTagName => serverTagName;

View File

@ -1,12 +1,10 @@
using JiShe.CollectBus.Common;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Enums;
using JiShe.CollectBus.IoTDB.Model;
namespace JiShe.CollectBus.Ammeters
{
[EntityType(EntityTypeEnum.TreeModel)]
[GenerateAccessors]
public class ElectricityMeterTreeModel : IoTEntity
{
[ATTRIBUTEColumn]

View File

@ -1,9 +1,16 @@
using JiShe.CollectBus.Common;
using JiShe.CollectBus.Common.Attributes;
using JiShe.CollectBus.Common.Encrypt;
using JiShe.CollectBus.Common.Enums;
using JiShe.CollectBus.Common.Models;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Enums;
using JiShe.CollectBus.IoTDB.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Entities.Auditing;
namespace JiShe.CollectBus.IotSystems.MeterReadingRecords
{
@ -11,7 +18,6 @@ namespace JiShe.CollectBus.IotSystems.MeterReadingRecords
/// 抄读任务数据
/// </summary>
[EntityType(EntityTypeEnum.TableModel)]
[GenerateAccessors]
public class MeterReadingTelemetryPacketInfo : IoTEntity
{
/// <summary>
@ -90,7 +96,6 @@ namespace JiShe.CollectBus.IotSystems.MeterReadingRecords
/// <summary>
/// 抄读计量点
/// </summary>
[FIELDColumn]
public int Pn { get; set; }
/// <summary>
@ -109,7 +114,6 @@ namespace JiShe.CollectBus.IotSystems.MeterReadingRecords
/// <summary>
/// 帧序列域 SEQ
/// </summary>
[FIELDColumn]
public int Seq { get; set; }
/// <summary>
@ -128,7 +132,7 @@ namespace JiShe.CollectBus.IotSystems.MeterReadingRecords
/// 发送次数
/// </summary>
[FIELDColumn]
public int? SendNum { get; set; }
public int SendNum { get; set; }
/// <summary>
/// 下次发送时间

View File

@ -25,9 +25,7 @@
<ProjectReference Include="..\..\modules\JiShe.CollectBus.IoTDB\JiShe.CollectBus.IoTDB.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Domain.Shared\JiShe.CollectBus.Domain.Shared.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.IncrementalGenerator\JiShe.CollectBus.IncrementalGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Volo.Abp.Emailing" Version="8.3.3" />

View File

@ -1,12 +0,0 @@
using System;
namespace JiShe.CollectBus.Common
{
/// <summary>
/// 标记需要生成源码的类
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class GenerateAccessorsAttribute : Attribute
{
}
}

View File

@ -26,6 +26,7 @@
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Volo.Abp.Core" Version="8.3.3" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="8.3.3" />
</ItemGroup>
</Project>

View File

@ -8,12 +8,12 @@
/// <summary>
/// 服务器标识
/// </summary>
public string ServerTagName { get; set; }
public required string ServerTagName { get; set; }
/// <summary>
/// 系统类型
/// </summary>
public string SystemType { get; set; }
public required string SystemType { get; set; }
/// <summary>
/// 首次采集时间
@ -23,31 +23,31 @@
/// <summary>
/// 自动验证时间
/// </summary>
public string AutomaticVerificationTime { get; set; }
public required string AutomaticVerificationTime { get; set; }
/// <summary>
/// 自动获取终端版时间
/// </summary>
public string AutomaticTerminalVersionTime { get; set; }
public required string AutomaticTerminalVersionTime { get; set; }
/// <summary>
/// 自动获取远程通信模块(SIM)版本时间
/// </summary>
public string AutomaticTelematicsModuleTime { get; set; }
public required string AutomaticTelematicsModuleTime { get; set; }
/// <summary>
/// 日冻结抄读时间
/// </summary>
public string AutomaticDayFreezeTime { get; set; }
public required string AutomaticDayFreezeTime { get; set; }
/// <summary>
/// 月冻结抄读时间
/// </summary>
public string AutomaticMonthFreezeTime { get; set; }
public required string AutomaticMonthFreezeTime { get; set; }
/// <summary>
/// 默认协议插件
/// </summary>
public string DefaultProtocolPlugin { get; set; }
public required string DefaultProtocolPlugin { get; set; }
}
}

View File

@ -1,227 +0,0 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JiShe.CollectBus.IncrementalGenerator
{
/// <summary>
/// 复杂类型源生成器
/// </summary>
[Generator(LanguageNames.CSharp)]
public class ComplexTypeSourceGenerator : IIncrementalGenerator
{
private const string AttributeFullName = "JiShe.CollectBus.Common.GenerateAccessorsAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
//Debugger.Launch();
context.RegisterPostInitializationOutput(ctx =>
{
ctx.AddSource("DebugInit.g.cs", "// Generator initialized");
});
// 步骤1筛选带有 [GenerateAccessors] 的类
var classDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (s, _) => IsClassWithAttribute(s),
transform: static (ctx, _) => GetClassDeclaration(ctx))
.Where(static c => c is not null);
// 步骤2合并编译信息
var compilationAndClasses = context.CompilationProvider.Combine(classDeclarations.Collect());
context.RegisterSourceOutput(compilationAndClasses, (spc, source) =>
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;
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;
}
private static void GenerateCode(
Compilation compilation,
IEnumerable<ClassDeclarationSyntax> classes,
SourceProductionContext context)
{
var processedTypes = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default);
if (!classes.Any())
{
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor("GEN002", "No Targets",
"No classes with [GenerateAccessors] found", "Debug", DiagnosticSeverity.Warning, true),
Location.None));
}
foreach (var classDecl in classes.Distinct())
{
var model = compilation.GetSemanticModel(classDecl.SyntaxTree);
var classSymbol = model.GetDeclaredSymbol(classDecl) as INamedTypeSymbol;
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),
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("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}"); // 调试输出
context.AddSource($"{classSymbol.Name}Extension.g.cs", SourceText.From(code, Encoding.UTF8));
}
}
private static string BuildAccessorsForType(
INamedTypeSymbol classSymbol,
Compilation compilation,
HashSet<ITypeSymbol> processedTypes)
{
var code = new StringBuilder();
code.AppendLine("#pragma warning disable CS0419 // 禁用警告");
code.AppendLine("// Generated code for " + classSymbol.Name);
code.AppendLine("// <auto-generated/>");
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 classSymbol.GetMembers().OfType<IPropertySymbol>())
{
if (prop.IsIndexer) continue;
GeneratePropertyAccessors(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))}>" : "";
public static string GetGenericParams(INamedTypeSymbol symbol)
{
if (!symbol.IsGenericType) return "";
var parameters = symbol.TypeParameters.Select(t => t.Name);
return $"<{string.Join(", ", parameters)}>";
}
private static void GeneratePropertyAccessors(
IPropertySymbol prop,
StringBuilder code,
Compilation compilation,
HashSet<ITypeSymbol> processedTypes)
{
// 关键修复点1安全类型转换
if (prop.Type is not ITypeSymbol propType) return;
code.AppendLine($" // Processing property: {prop.Name}");
// 处理元组类型
if (propType is INamedTypeSymbol { IsTupleType: true } tupleType)
{
GenerateTupleAccessors(prop, tupleType, code);
}
else if (propType is INamedTypeSymbol namedType)
{
GenerateStandardAccessors(prop, namedType, code);
ProcessNestedType(namedType, compilation, processedTypes);
}
}
private static void GenerateTupleAccessors(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 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};");
if (prop.SetMethod != null)
{
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<ITypeSymbol> 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("<");
}
}
}

View File

@ -1,27 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsRoslynComponent>true</IsRoslynComponent>
<NoPackageAnalysis>true</NoPackageAnalysis>
<ImportDirectoryBuildProps>false</ImportDirectoryBuildProps>
<BaseOutputPath>bin</BaseOutputPath>
<IncludeBuildOutput>false</IncludeBuildOutput>
<LangVersion>latest</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<!-- 指定生成文件的输出目录 -->
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.13.0" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" >
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
</ItemGroup>
</Project>

View File

@ -5,7 +5,7 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>
</PropertyGroup>
<ItemGroup>
<Compile Remove="logs\**" />
@ -57,7 +57,7 @@
<ProjectReference Include="..\..\services\JiShe.CollectBus.Application.Contracts\JiShe.CollectBus.Application.Contracts.csproj" />
<ProjectReference Include="..\..\services\JiShe.CollectBus.Application\JiShe.CollectBus.Application.csproj" />
<ProjectReference Include="..\JiShe.CollectBus.HttpApi\JiShe.CollectBus.HttpApi.csproj" />
</ItemGroup>
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">

View File

@ -5,7 +5,7 @@
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Information",
"Default": "Warning",
"Override": {
"Microsoft": "Warning",
"Volo.Abp": "Warning",
@ -87,7 +87,7 @@
"UserName": "root",
"Password": "root",
"ClusterList": [ "192.168.1.9:6667" ],
"PoolSize": 32,
"PoolSize": 2,
"DataBaseName": "energy",
"OpenDebugMode": true,
"UseTableSessionPoolByDefault": false
@ -142,9 +142,9 @@
}
},
"ServerApplicationOptions": {
"ServerTagName": "JiSheCollectBus4",
"SystemType": "Energy",
"FirstCollectionTime": "2025-04-28 15:07:00",
"ServerTagName": "JiSheCollectBus100",
"SystemType": null,
"FirstCollectionTime": "2025-04-22 16:07:00",
"AutomaticVerificationTime": "16:07:00",
"AutomaticTerminalVersionTime": "17:07:00",
"AutomaticTelematicsModuleTime": "17:30:00",