Compare commits

..

9 Commits

Author SHA1 Message Date
Diego
62e0a6ee9d gitee登录按钮隐藏 2025-06-19 17:04:22 +08:00
Diego
765e5564d4 10.8.10 2025-06-19 16:56:04 +08:00
Diego
10eecac19b feat: 优化设备状态逻辑 2025-06-19 11:41:43 +08:00
Diego
59241b8faa fix: opcua插件订阅检查失效 2025-06-19 10:42:54 +08:00
Diego
52b3097f04 10.8.7 2025-06-18 22:04:48 +08:00
Diego
d922296b70 feat: 重构插件任务 2025-06-18 17:11:57 +08:00
Diego
aec91da28b 10.8.2
feat: 优化闭包导致的状态机内存占用,高并发时内存显著下降
fix(sqldb): 定时上传模式时,实时表时效
fix(taos): 初始化失败
2025-06-17 17:09:05 +08:00
Diego
013ff394be 10.8.1 2025-06-16 18:25:55 +08:00
Diego
081e07473d 10.8.0 2025-06-16 18:12:28 +08:00
191 changed files with 3139 additions and 1825 deletions

View File

@@ -0,0 +1,6 @@
## Release 1.0
### New Rules
Rule ID | Category | Severity | Notes
--------|----------|----------|--------------------
TG0001 | Conflict | Error | SetParametersAsyncGenerator

View File

@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>netstandard2.0;</TargetFrameworks>
<Version>$(SourceGeneratorVersion)</Version>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<NoPackageAnalysis>true</NoPackageAnalysis>
<SignAssembly>false</SignAssembly>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<IncludeBuildOutput>false</IncludeBuildOutput>
<!-- 避免 DLL 被打包到 lib/ -->
<EnableSourceGenerator>true</EnableSourceGenerator>
<!-- 可选 -->
</PropertyGroup>
<ItemGroup>
<None Include="$(OutputPath)\$(TargetFileName)" Pack="true"
PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="AnalyzerReleases.Shipped.md" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.9.0" PrivateAssets="all" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,9 @@
//------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权除特别声明外的代码归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库https://github.com/kimdiego2098/ThingsGateway
// 使用文档https://thingsgateway.cn/
// QQ群605534569
//------------------------------------------------------------------------------

View File

@@ -0,0 +1,534 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace BlazorSetParametersAsyncGenerator;
[Generator]
public partial class SetParametersAsyncGenerator : ISourceGenerator
{
private string m_DoNotGenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
internal sealed class DoNotGenerateSetParametersAsyncAttribute : Attribute
{
}
}
"""
;
private string m_GenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
internal sealed class GenerateSetParametersAsyncAttribute : Attribute
{
public bool RequireExactMatch { get; set; }
}
}
"""
;
private string m_GlobalGenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
internal sealed class GlobalGenerateSetParametersAsyncAttribute : Attribute
{
public bool Enable { get; }
public GlobalGenerateSetParametersAsyncAttribute(bool enable = true)
{
Enable = enable;
}
}
}
"""
;
private static readonly DiagnosticDescriptor ParameterNameConflict = new DiagnosticDescriptor(
id: "TG0001",
title: "Parameter name conflict",
messageFormat: "Parameter names are case insensitive. {0} conflicts with {1}.",
category: "Conflict",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Parameter names must be case insensitive to be usable in routes. Rename the parameter to not be in conflict with other parameters.");
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(a =>
{
a.AddSource(nameof(m_DoNotGenerateSetParametersAsyncAttribute), m_DoNotGenerateSetParametersAsyncAttribute);
a.AddSource(nameof(m_GenerateSetParametersAsyncAttribute), m_GenerateSetParametersAsyncAttribute);
a.AddSource(nameof(m_GlobalGenerateSetParametersAsyncAttribute), m_GlobalGenerateSetParametersAsyncAttribute);
});
// Register a syntax receiver that will be created for each generation pass
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
// https://github.com/dotnet/AspNetCore.Docs/blob/1e199f340780f407a685695e6c4d953f173fa891/aspnetcore/blazor/webassembly-performance-best-practices.md#implement-setparametersasync-manually
if (context.SyntaxReceiver is not SyntaxReceiver receiver)
{
return;
}
var candidate_classes = GetCandidateClasses(receiver, context);
foreach (var class_symbol in candidate_classes.Distinct(SymbolEqualityComparer.Default).Cast<INamedTypeSymbol>())
{
GenerateSetParametersAsyncMethod(context, class_symbol);
}
}
private static void GenerateSetParametersAsyncMethod(GeneratorExecutionContext context, INamedTypeSymbol class_symbol)
{
var force_exact_match = class_symbol.GetAttributes().Any(a => a.NamedArguments.Any(na => na.Key == "RequireExactMatch" && na.Value.Value is bool v && v));
var namespaceName = class_symbol.ContainingNamespace.ToDisplayString();
var type_kind = class_symbol.TypeKind switch { TypeKind.Class => "class", TypeKind.Interface => "interface", _ => "struct" };
var type_parameters = string.Join(", ", class_symbol.TypeArguments.Select(t => t.Name));
type_parameters = string.IsNullOrEmpty(type_parameters) ? type_parameters : "<" + type_parameters + ">";
context.AddCode(class_symbol.ToDisplayString() + "_override.cs", $@"
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Threading.Tasks;
#pragma warning disable CA2007
#pragma warning disable CS0162
#pragma warning disable CS8632
namespace {namespaceName}
{{
public partial class {class_symbol.Name}{type_parameters}
{{
private bool _initialized;
/// <summary>
/// <inheritdoc/>
/// </summary>
public override Task SetParametersAsync(ParameterView parameters)
{{
Dictionary<string,object?> parameterValues = new();
foreach (var parameter in parameters)
{{
if(BlazorImplementation__WriteSingleParameter(parameter.Name, parameter.Value)==false)
{{
// 如果没有处理参数,则添加到参数列表中
parameterValues.Add(parameter.Name, parameter.Value);
}}
}}
if(parameterValues.Count > 0)
{{
parameters.SetParameterProperties(this);
}}
if (!_initialized)
{{
_initialized = true;
return RunInitAndSetParametersAsync();
}}
else
{{
return CallOnParametersSetAsync();
}}
}}
// We do not want the debugger to consider NavigationExceptions caught by this method as user-unhandled.
#if NET9_0_OR_GREATER
[System.Diagnostics.DebuggerDisableUserUnhandledExceptions]
#endif
private async Task RunInitAndSetParametersAsync()
{{
Task task;
try
{{
OnInitialized();
task = OnInitializedAsync();
}}
catch (Exception ex) when (ex is not NavigationException)
{{
throw;
}}
if (task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Canceled)
{{
// Call state has changed here so that we render after the sync part of OnInitAsync has run
// and wait for it to finish before we continue. If no async work has been done yet, we want
// to defer calling StateHasChanged up until the first bit of async code happens or until
// the end. Additionally, we want to avoid calling StateHasChanged if no
// async work is to be performed.
StateHasChanged();
try
{{
await task;
}}
catch // avoiding exception filters for AOT runtime support
{{
// Ignore exceptions from task cancellations.
// Awaiting a canceled task may produce either an OperationCanceledException (if produced as a consequence of
// CancellationToken.ThrowIfCancellationRequested()) or a TaskCanceledException (produced as a consequence of awaiting Task.FromCanceled).
// It's much easier to check the state of the Task (i.e. Task.IsCanceled) rather than catch two distinct exceptions.
if (!task.IsCanceled)
{{
throw;
}}
}}
// Don't call StateHasChanged here. CallOnParametersSetAsync should handle that for us.
}}
await CallOnParametersSetAsync();
}}
// We do not want the debugger to consider NavigationExceptions caught by this method as user-unhandled.
#if NET9_0_OR_GREATER
[System.Diagnostics.DebuggerDisableUserUnhandledExceptions]
#endif
private Task CallOnParametersSetAsync()
{{
Task task;
try
{{
OnParametersSet();
task = OnParametersSetAsync();
}}
catch (Exception ex) when (ex is not NavigationException)
{{
#if NET9_0_OR_GREATER
System.Diagnostics.Debugger.BreakForUserUnhandledException(ex);
#endif
throw;
}}
// If no async work is to be performed, i.e. the task has already ran to completion
// or was canceled by the time we got to inspect it, avoid going async and re-invoking
// StateHasChanged at the culmination of the async work.
var shouldAwaitTask = task.Status != TaskStatus.RanToCompletion &&
task.Status != TaskStatus.Canceled;
// We always call StateHasChanged here as we want to trigger a rerender after OnParametersSet and
// the synchronous part of OnParametersSetAsync has run.
StateHasChanged();
return shouldAwaitTask ?
CallStateHasChangedOnAsyncCompletion(task) :
Task.CompletedTask;
}}
// We do not want the debugger to stop more than once per user-unhandled exception.
#if NET9_0_OR_GREATER
[System.Diagnostics.DebuggerDisableUserUnhandledExceptions]
#endif
private async Task CallStateHasChangedOnAsyncCompletion(Task task)
{{
try
{{
await task;
}}
catch // avoiding exception filters for AOT runtime support
{{
// Ignore exceptions from task cancellations, but don't bother issuing a state change.
if (task.IsCanceled)
{{
return;
}}
throw;
}}
StateHasChanged();
}}
}}
}}
#pragma warning restore CS8632
#pragma warning restore CS0162
#pragma warning restore CA2007
");
var bases = class_symbol.GetTypeHierarchy().Where(t => !SymbolEqualityComparer.Default.Equals(t, class_symbol));
var members = class_symbol.GetMembers() // members of the type itself
.Concat(bases.SelectMany(t => t.GetMembers().Where(m => m.DeclaredAccessibility != Accessibility.Private))) // plus accessible members of any base
.Distinct(SymbolEqualityComparer.Default);
var property_symbols = members.OfType<IPropertySymbol>();
var writable_property_symbols = property_symbols.Where(ps =>
!ps.IsReadOnly || ps.GetAttributes().Any(a =>
a.AttributeClass?.Name is "CascadingParameter" or "CascadingParameterAttribute")
);
var parameter_symbols = writable_property_symbols
.Where(ps => ps.GetAttributes().Any(a => false
|| a.AttributeClass.Name == "Parameter"
|| a.AttributeClass.Name == "ParameterAttribute"
|| a.AttributeClass.Name == "CascadingParameter"
|| a.AttributeClass.Name == "CascadingParameterAttribute"
));
var name_conflicts = parameter_symbols.GroupBy(ps => ps.Name.ToLowerInvariant()).Where(g => g.Count() > 1);
foreach (var conflict in name_conflicts)
{
var key = conflict.Key;
var conflicting_parameters = conflict.ToList();
foreach (var parameter in conflicting_parameters)
{
var this_name = parameter.Name;
var conflicting_name = conflicting_parameters.Select(p => p.Name).FirstOrDefault(n => n != this_name);
foreach (var location in parameter.Locations)
{
context.ReportDiagnostic(Diagnostic.Create(ParameterNameConflict, location, this_name, conflicting_name));
}
}
}
var all = parameter_symbols.ToList();
var catch_all_parameter = parameter_symbols.FirstOrDefault(p =>
{
var parameter_attr = p.GetAttributes().FirstOrDefault(a => a.AttributeClass!.Name.StartsWith("Parameter"));
return parameter_attr?.NamedArguments.Any(n => n.Key == "CaptureUnmatchedValues" && n.Value.Value is bool v && v) == true;
});
var lower_case_match_cases = parameter_symbols.Except(new[] { catch_all_parameter }).Select(p => $"case \"{p.Name.ToLowerInvariant()}\": this.{p.Name} = ({p.Type.ToDisplayString()}) value; break;");
var lower_case_match_default = catch_all_parameter == null ? @"default: {return false;}" : $@"
default:
{{
this.{catch_all_parameter.Name} ??= new System.Collections.Generic.Dictionary<string, object>();
var writable_dict = this.{catch_all_parameter.Name};
if (!writable_dict.TryAdd(name, value))
{{
writable_dict[name] = value;
}}
break;
}}";
var exact_match_cases = parameter_symbols.Except(new[] { catch_all_parameter }).Select(p => $"case \"{p!.Name}\": this.{p.Name} = ({p.Type.ToDisplayString()}) value; break;");
string exact_match_default;
if (force_exact_match)
{
if (catch_all_parameter == null) // exact matches are forced, and we do not have a catch-all parameter, therefore we need to throw on unmatched parameter
{
exact_match_default = @"default: { return false;";
}
else // exact matches are forced, and we DO have a catch-all parameter, therefore we simply add that unmatched parameter to the dictionary
{
exact_match_default = $@"
default:
{{
this.{catch_all_parameter.Name} ??= new System.Collections.Generic.Dictionary<string, object>();
var writable_dict = this.{catch_all_parameter.Name};
if (!writable_dict.TryAdd(name, value))
{{
writable_dict[name] = value;
}}
break;
}}";
}
}
else
{
// exact matches are not forced, so if there is no exact match, we fall back to compare it in lower case
exact_match_default = $@"
default:
{{
switch (name.ToLowerInvariant())
{{
{string.Join("\n", lower_case_match_cases)}
{lower_case_match_default}
}}
break;
}}
";
}
context.AddCode(class_symbol.ToDisplayString() + "_implementation.cs", $@"
using System;
#pragma warning disable CS0162
#pragma warning disable CS0618
#pragma warning disable CS8632
namespace {namespaceName}
{{
public partial class {class_symbol.Name}{type_parameters}
{{
private bool BlazorImplementation__WriteSingleParameter(string name, object value)
{{
if(name != ""Body"")
{{
switch (name)
{{
{string.Join("\n", exact_match_cases)}
{exact_match_default}
}}
return true;
}}
return false;
}}
}}
}}
#pragma warning restore CS8632
#pragma warning restore CS0618
#pragma warning restore CS0162");
}
private static bool HasUserDefinedSetParametersAsync(INamedTypeSymbol classSymbol)
{
return classSymbol
.GetMembers("SetParametersAsync")
.OfType<IMethodSymbol>()
.Any(m =>
m.Parameters.Length == 1 &&
m.Parameters[0].Type.ToDisplayString() == "Microsoft.AspNetCore.Components.ParameterView" &&
m.DeclaredAccessibility == Accessibility.Public &&
!m.IsStatic);
}
private static bool IsPartial(INamedTypeSymbol symbol)
{
return symbol.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.OfType<ClassDeclarationSyntax>()
.Any(c => c.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)));
}
private static bool IsComponent(ClassDeclarationSyntax classDeclarationSyntax, INamedTypeSymbol symbol, Compilation compilation)
{
if (HasUserDefinedSetParametersAsync(symbol))
{
// 用户自己写了方法,不生成
return false;
}
if (!IsPartial(symbol))
{
return false;
}
if (classDeclarationSyntax.SyntaxTree.FilePath.EndsWith(".razor") || classDeclarationSyntax.SyntaxTree.FilePath.EndsWith(".razor.cs"))
{
return true;
}
var iComponent = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Components.IComponent");
var componentBase = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Components.ComponentBase");
if (iComponent == null || componentBase == null)
return false;
if (SymbolEqualityComparer.Default.Equals(symbol, iComponent))
return true;
if (SymbolEqualityComparer.Default.Equals(symbol, componentBase))
return true;
return false;
}
/// <summary>
/// Enumerate methods with at least one Group attribute
/// </summary>
private static IEnumerable<INamedTypeSymbol> GetCandidateClasses(SyntaxReceiver receiver, GeneratorExecutionContext context)
{
var compilation = context.Compilation;
var positiveAttributeSymbol = compilation.GetTypeByMetadataName("BlazorSetParametersAsyncGenerator.GenerateSetParametersAsyncAttribute");
var negativeAttributeSymbol = compilation.GetTypeByMetadataName("BlazorSetParametersAsyncGenerator.DoNotGenerateSetParametersAsyncAttribute");
// loop over the candidate methods, and keep the ones that are actually annotated
// 找特性
var assemblyAttributes = compilation.Assembly.GetAttributes();
var enableAttr = assemblyAttributes.FirstOrDefault(attr =>
attr.AttributeClass?.ToDisplayString() == "BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsyncAttribute");
var globalEnable = false;
if (enableAttr != null)
{
var arg = enableAttr.ConstructorArguments.FirstOrDefault();
if (arg.Value is bool b)
globalEnable = b;
}
foreach (ClassDeclarationSyntax class_declaration in receiver.CandidateClasses)
{
var model = compilation.GetSemanticModel(class_declaration.SyntaxTree);
var class_symbol = model.GetDeclaredSymbol(class_declaration);
if (class_symbol is null)
{
continue;
}
if (class_symbol.Name == "_Imports")
{
continue;
}
// 是否拒绝生成
var hasNegative = class_symbol.GetAttributes().Any(ad =>
ad.AttributeClass?.Equals(negativeAttributeSymbol, SymbolEqualityComparer.Default) == true);
if (hasNegative)
continue;
if (IsComponent(class_declaration, class_symbol, compilation))
{
if (globalEnable)
{
yield return class_symbol;
}
else
{
// 必须显式标注 Positive Attribute
var hasPositive = class_symbol.GetAttributes().Any(ad =>
ad.AttributeClass?.Equals(positiveAttributeSymbol, SymbolEqualityComparer.Default) == true);
if (hasPositive)
yield return class_symbol;
}
}
else
{
}
}
}
/// <summary>
/// Created on demand before each generation pass
/// </summary>
internal class SyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> CandidateClasses { get; } = new List<ClassDeclarationSyntax>();
/// <summary>
/// Called for every syntax node in the compilation, we can inspect the nodes and save any information useful for generation
/// </summary>
public void OnVisitSyntaxNode(SyntaxNode syntax_node)
{
// any class with at least one attribute is a candidate for property generation
if (syntax_node is ClassDeclarationSyntax classDeclarationSyntax)
{
CandidateClasses.Add(classDeclarationSyntax);
}
else
{
}
}
}
}

View File

@@ -0,0 +1,15 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
namespace BlazorSetParametersAsyncGenerator
{
internal static class SourceGeneratorContextExtension
{
public static void AddCode(this GeneratorExecutionContext context, string hint_name, string code)
{
context.AddSource(hint_name.Replace("<", "_").Replace(">", "_"), SourceText.From(code, Encoding.UTF8));
}
}
}

View File

@@ -0,0 +1,13 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace BlazorSetParametersAsyncGenerator
{
internal static class StringExtension
{
public static string NormalizeWhitespace(this string code)
{
return CSharpSyntaxTree.ParseText(code).GetRoot().NormalizeWhitespace().ToFullString();
}
}
}

View File

@@ -0,0 +1,19 @@
using Microsoft.CodeAnalysis;
namespace BlazorSetParametersAsyncGenerator
{
public static class TypeSymbolExtension
{
public static IEnumerable<INamedTypeSymbol> GetTypeHierarchy(this INamedTypeSymbol symbol)
{
yield return symbol;
if (symbol.BaseType != null)
{
foreach (var type in GetTypeHierarchy(symbol.BaseType))
{
yield return type;
}
}
}
}
}

View File

@@ -0,0 +1,49 @@
param($installPath, $toolsPath, $package, $project)
$analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers" ) * -Resolve
foreach($analyzersPath in $analyzersPaths)
{
# Install the language agnostic analyzers.
if (Test-Path $analyzersPath)
{
foreach ($analyzerFilePath in Get-ChildItem $analyzersPath -Filter *.dll)
{
if($project.Object.AnalyzerReferences)
{
$project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
}
}
}
}
# $project.Type gives the language name like (C# or VB.NET)
$languageFolder = ""
if($project.Type -eq "C#")
{
$languageFolder = "cs"
}
if($project.Type -eq "VB.NET")
{
$languageFolder = "vb"
}
if($languageFolder -eq "")
{
return
}
foreach($analyzersPath in $analyzersPaths)
{
# Install language specific analyzers.
$languageAnalyzersPath = join-path $analyzersPath $languageFolder
if (Test-Path $languageAnalyzersPath)
{
foreach ($analyzerFilePath in Get-ChildItem $languageAnalyzersPath -Filter *.dll)
{
if($project.Object.AnalyzerReferences)
{
$project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
}
}
}
}

View File

@@ -0,0 +1,56 @@
param($installPath, $toolsPath, $package, $project)
$analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers" ) * -Resolve
foreach($analyzersPath in $analyzersPaths)
{
# Uninstall the language agnostic analyzers.
if (Test-Path $analyzersPath)
{
foreach ($analyzerFilePath in Get-ChildItem $analyzersPath -Filter *.dll)
{
if($project.Object.AnalyzerReferences)
{
$project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName)
}
}
}
}
# $project.Type gives the language name like (C# or VB.NET)
$languageFolder = ""
if($project.Type -eq "C#")
{
$languageFolder = "cs"
}
if($project.Type -eq "VB.NET")
{
$languageFolder = "vb"
}
if($languageFolder -eq "")
{
return
}
foreach($analyzersPath in $analyzersPaths)
{
# Uninstall language specific analyzers.
$languageAnalyzersPath = join-path $analyzersPath $languageFolder
if (Test-Path $languageAnalyzersPath)
{
foreach ($analyzerFilePath in Get-ChildItem $languageAnalyzersPath -Filter *.dll)
{
if($project.Object.AnalyzerReferences)
{
try
{
$project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName)
}
catch
{
}
}
}
}
}

View File

@@ -91,7 +91,7 @@ public sealed class OperDescAttribute : MoAttribute
OperDescAttribute.WriteToQueue(log);
}
}
private static SqlSugarClient _db = DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
private static SqlSugarClient _db = DbContext.GetDB<SysOperateLog>();
/// <summary>
/// 将日志消息写入数据库中
/// </summary>

View File

@@ -267,7 +267,7 @@ public class RequestAuditFilter : IAsyncActionFilter, IOrderedFilter
}
else
{
logger.Log(LogLevel.Warning, $"{logData.Method}:{logData.Path}-{logData.Operation}{Environment.NewLine}{logData.Exception.ToSystemTextJsonString()}");
logger.Log(LogLevel.Warning, $"{logData.Method}:{logData.Path}-{logData.Operation}{Environment.NewLine}{logData.Exception?.ToSystemTextJsonString()}{Environment.NewLine}{logData.Validation?.ToSystemTextJsonString()}");
}
}

View File

@@ -8,5 +8,4 @@
// QQ群605534569
//------------------------------------------------------------------------------
global using ThingsGateway;
global using ThingsGateway.NewLife.Extension;

View File

@@ -61,7 +61,7 @@ public class HardwareJob : IJob, IHardwareJob
var historyHardwareInfos = MemoryCache.Get<List<HistoryHardwareInfo>>(CacheKey);
if (historyHardwareInfos == null)
{
using var db = _db.CopyNew();
using var db = DbContext.GetDB<HistoryHardwareInfo>(); ;
historyHardwareInfos = await db.Queryable<HistoryHardwareInfo>().Where(a => a.Date > DateTime.Now.AddDays(-3)).ToListAsync().ConfigureAwait(false);
MemoryCache.Set(CacheKey, historyHardwareInfos);
@@ -71,7 +71,7 @@ public class HardwareJob : IJob, IHardwareJob
private bool error = false;
private DateTime hisInsertTime = default;
private SqlSugarClient _db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew();
private SqlSugarClient _db = DbContext.GetDB<HistoryHardwareInfo>();
public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
{
@@ -81,7 +81,7 @@ public class HardwareJob : IJob, IHardwareJob
{
if (HardwareInfo.MachineInfo == null)
{
await MachineInfo.RegisterAsync().ConfigureAwait(false);
MachineInfo.Register();
HardwareInfo.MachineInfo = MachineInfo.Current;
string currentPath = Directory.GetCurrentDirectory();

View File

@@ -27,7 +27,7 @@ public class LogJob : IJob
private static async Task DeleteSysOperateLog(int daysAgo, CancellationToken stoppingToken)
{
using var db = DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
using var db = DbContext.GetDB<SysOperateLog>();
var time = DateTime.Now.AddDays(-daysAgo);
await db.DeleteableWithAttr<SysOperateLog>().Where(u => u.OpTime < time).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false); // 删除操作日志
}

View File

@@ -143,7 +143,7 @@ public class DatabaseLoggingWriter : IDatabaseLoggingWriter
if (flush)
{
SqlSugarClient ??= DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
SqlSugarClient ??= DbContext.GetDB<SysOperateLog>();
await SqlSugarClient.InsertableWithAttr(_operateLogMessageQueue.ToListWithDequeue()).ExecuteCommandAsync().ConfigureAwait(false);//入库
return true;
}
@@ -202,7 +202,7 @@ public class DatabaseLoggingWriter : IDatabaseLoggingWriter
if (flush)
{
SqlSugarClient ??= DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
SqlSugarClient ??= DbContext.GetDB<SysOperateLog>();
await SqlSugarClient.InsertableWithAttr(_operateLogMessageQueue.ToListWithDequeue()).ExecuteCommandAsync().ConfigureAwait(false);//入库
return true;
}

View File

@@ -46,7 +46,7 @@ public class AdminOAuthHandler<TOptions>(
/// </summary>
private static async Task Insertable()
{
var db = DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
var db = DbContext.GetDB<SysOperateLog>();
var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!;
while (!appLifetime.ApplicationStopping.IsCancellationRequested)
{
@@ -209,7 +209,7 @@ public class AdminOAuthHandler<TOptions>(
#endregion ,
using var db = DbContext.Db.GetConnectionScopeWithAttr<SysUser>().CopyNew();
using var db = DbContext.GetDB<SysUser>();
//更新用户登录信息
if (await db.Updateable(sysUser).UpdateColumns(it => new
{

View File

@@ -25,7 +25,7 @@ public abstract class AdminOAuthOptions : OAuthOptions
Backchannel = new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator // 若测试用
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});
Backchannel.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue("ThingsGateway", "1.0"));

View File

@@ -18,7 +18,7 @@ public class SysRelationSeedData : ISqlSugarEntitySeedData<SysRelation>
/// <inheritdoc/>
public IEnumerable<SysRelation> SeedData()
{
using var db = DbContext.Db.GetConnectionScopeWithAttr<SysRelation>().CopyNew();
using var db = DbContext.GetDB<SysRelation>();
if (db.Queryable<SysRelation>().Any(a => a.ObjectId == RoleConst.SuperAdminId))
return Enumerable.Empty<SysRelation>();
var data = SeedDataUtil.GetSeedData<SysRelation>(PathExtensions.CombinePathWithOs("SeedData", "Admin", "seed_sys_relation.json"));

View File

@@ -324,7 +324,7 @@ public class AuthService : IAuthService
#endregion ,
using var db = DbContext.Db.GetConnectionScopeWithAttr<SysUser>().CopyNew();
using var db = DbContext.GetDB<SysUser>();
//更新用户登录信息
if (await db.Updateable(sysUser).UpdateColumns(it => new
{

View File

@@ -78,7 +78,7 @@ public class Startup : AppStartup
//遍历配置
DbContext.DbConfigs?.ForEach(it =>
{
var connection = DbContext.Db.GetConnection(it.ConfigId);//获取数据库连接对象
var connection = DbContext.GetDB().GetConnection(it.ConfigId);//获取数据库连接对象
if (it.InitDatabase == true)
connection.DbMaintenance.CreateDatabase();//创建数据库,如果存在则不创建
});

View File

@@ -46,7 +46,6 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />
<ProjectReference Include="..\ThingsGateway.DB\ThingsGateway.DB.csproj" />
</ItemGroup>

View File

@@ -40,7 +40,7 @@ public static class ClearTokenUtil
public static async Task DeleteUserTokenByOrgIds(HashSet<long> orgIds)
{
// 获取用户ID列表
var userIds = await DbContext.Db.CopyNew().QueryableWithAttr<SysUser>().Where(it => orgIds.Contains(it.OrgId)).Select(it => it.Id).ToListAsync().ConfigureAwait(false);
var userIds = await DbContext.GetDB<SysUser>().Queryable<SysUser>().Where(it => orgIds.Contains(it.OrgId)).Select(it => it.Id).ToListAsync().ConfigureAwait(false);
//从redis中删除所属机构的用户token
App.CacheService.HashDel<VerificatInfo>(CacheConst.Cache_Token, userIds.Select(it => it.ToString()).ToArray());
}

View File

@@ -156,7 +156,7 @@ public class BlazorAppContext
CurrentUser = (await SysUserService.GetUserByIdAsync(UserManager.UserId))!;
}
}
TimeTick timeTick = new("50000");
TimeTick timeTick = new("60000");
/// <summary>
/// 是否拥有按钮授权
/// </summary>

View File

@@ -19,3 +19,4 @@ global using System.Diagnostics.CodeAnalysis;
global using ThingsGateway.Razor;
[assembly: SuppressMessage("Reliability", "CA2007", Justification = "<挂起>", Scope = "module")]
[assembly: BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsync(true)]

View File

@@ -22,12 +22,11 @@ public partial class SessionPage
#region
private async Task<QueryData<SessionOutput>> OnQueryAsync(QueryPageOptions options)
private Task<QueryData<SessionOutput>> OnQueryAsync(QueryPageOptions options)
{
return await Task.Run(async () =>
return Task.Run(() =>
{
var data = await SessionService.PageAsync(options);
return data;
return SessionService.PageAsync(options);
});
}

View File

@@ -17,6 +17,7 @@
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</PropertyGroup>
<ItemGroup>
<Content Remove="Locales\*.json" />
@@ -32,6 +33,12 @@
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -41,19 +41,19 @@ public abstract class PrimaryKeyEntity : PrimaryIdEntity
[SugarColumn(ColumnDescription = "扩展信息", ColumnDataType = StaticConfig.CodeFirst_BigString, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual string? ExtJson { get; set; }
public virtual string ExtJson { get; set; }
}
public interface IBaseEntity
{
DateTime? CreateTime { get; set; }
string? CreateUser { get; set; }
DateTime CreateTime { get; set; }
string CreateUser { get; set; }
long CreateUserId { get; set; }
bool IsDelete { get; set; }
int? SortCode { get; set; }
DateTime? UpdateTime { get; set; }
string? UpdateUser { get; set; }
long? UpdateUserId { get; set; }
int SortCode { get; set; }
DateTime UpdateTime { get; set; }
string UpdateUser { get; set; }
long UpdateUserId { get; set; }
}
/// <summary>
@@ -61,13 +61,22 @@ public interface IBaseEntity
/// </summary>
public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
{
private long createUserId;
private long updateUserId;
private DateTime createTime;
private DateTime updateTime;
private int sortCode;
private bool isDelete = false;
private string createUser;
private string updateUser;
/// <summary>
/// 创建时间
/// </summary>
[SugarColumn(ColumnDescription = "创建时间", IsOnlyIgnoreUpdate = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Visible = false, IsVisibleWhenAdd = false, IsVisibleWhenEdit = false)]
public virtual DateTime? CreateTime { get; set; }
public virtual DateTime CreateTime { get => createTime; set => createTime = value; }
/// <summary>
/// 创建人
@@ -76,7 +85,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[IgnoreExcel]
[NotNull]
[AutoGenerateColumn(Ignore = true)]
public virtual string? CreateUser { get; set; }
public virtual string CreateUser { get => createUser; set => createUser = value; }
/// <summary>
/// 创建者Id
@@ -84,7 +93,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "创建者Id", IsOnlyIgnoreUpdate = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual long CreateUserId { get; set; }
public virtual long CreateUserId { get => createUserId; set => createUserId = value; }
/// <summary>
/// 软删除
@@ -92,8 +101,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "软删除", IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual bool IsDelete { get; set; } = false;
public virtual bool IsDelete { get => isDelete; set => isDelete = value; }
/// <summary>
/// 更新时间
@@ -101,7 +109,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "更新时间", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Visible = false, IsVisibleWhenAdd = false, IsVisibleWhenEdit = false)]
public virtual DateTime? UpdateTime { get; set; }
public virtual DateTime UpdateTime { get => updateTime; set => updateTime = value; }
/// <summary>
/// 更新人
@@ -109,7 +117,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "更新人", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual string? UpdateUser { get; set; }
public virtual string UpdateUser { get => updateUser; set => updateUser = value; }
/// <summary>
/// 修改者Id
@@ -117,7 +125,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "修改者Id", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual long? UpdateUserId { get; set; }
public virtual long UpdateUserId { get => updateUserId; set => updateUserId = value; }
/// <summary>
/// 排序码
@@ -125,7 +133,7 @@ public abstract class BaseEntity : PrimaryKeyEntity, IBaseEntity
[SugarColumn(ColumnDescription = "排序码", IsNullable = true)]
[AutoGenerateColumn(Visible = false, DefaultSort = true, Sortable = true, DefaultSortOrder = SortOrder.Asc)]
[IgnoreExcel]
public virtual int? SortCode { get; set; }
public virtual int SortCode { get => sortCode; set => sortCode = value; }
}
public interface IBaseDataEntity

View File

@@ -161,7 +161,7 @@ public class BaseService<T> : IDataService<T>, IDisposable where T : class, new(
/// <returns></returns>
protected SqlSugarClient GetDB()
{
return DbContext.Db.GetConnectionScopeWithAttr<T>().CopyNew();
return DbContext.GetDB<T>();
}

View File

@@ -55,7 +55,7 @@ public static class CodeFirstUtils
var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();//获取实体类型
var tenantAtt = entityType.GetCustomAttribute<TenantAttribute>();//获取sqlSugar多库特性
if (tenantAtt == null) continue;//如果没有多库特性就下一个
using var db = DbContext.Db.GetConnectionScope(tenantAtt.configId.ToString()).CopyNew();//获取数据库对象
using var db = DbContext.GetDB(tenantAtt.configId.ToString());//获取数据库对象
var config = DbContext.DbConfigs.FirstOrDefault(u => u.ConfigId.ToString() == tenantAtt.configId.ToString());//获取数据库配置
if (config?.InitSeedData != true) continue;
var entityInfo = db.EntityMaintenance.GetEntityInfo(entityType);
@@ -99,7 +99,7 @@ public static class CodeFirstUtils
var ignoreInit = entityType.GetCustomAttribute<IgnoreInitTableAttribute>();//获取忽略初始化特性
if (ignoreInit != null) continue;//如果有忽略初始化特性
if (tenantAtt == null) continue;//如果没有多库特性就下一个
using var db = DbContext.Db.GetConnectionScope(tenantAtt.configId.ToString()).CopyNew();//获取数据库对象
using var db = DbContext.GetDB(tenantAtt.configId.ToString());//获取数据库对象
var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();//获取自动分表特性
if (splitTable == null)//如果特性是空
db.CodeFirst.InitTables(entityType);//普通创建

View File

@@ -24,7 +24,7 @@ public static class DbContext
/// <summary>
/// SqlSugar 数据库实例
/// </summary>
public static readonly SqlSugarScope Db;
private static readonly SqlSugarClient Db;
/// <summary>
/// 读取配置文件中的 ConnectionStrings:Sqlsugar 配置节点
@@ -37,9 +37,28 @@ public static class DbContext
/// <returns></returns>
public static SqlSugarClient GetDB<T>()
{
return Db.GetConnectionScopeWithAttr<T>().CopyNew();
return Db.GetConnectionWithAttr<T>().CopyNew();
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
public static SqlSugarClient GetDB()
{
return Db;
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
public static SqlSugarClient GetDB(string tenant)
{
return Db.GetConnection(tenant).CopyNew();//获取数据库对象
}
private static ISugarAopService sugarAopService;
private static ISugarAopService SugarAopService
{
@@ -62,7 +81,7 @@ public static class DbContext
{
DbConfigs.ForEach(it =>
{
var sqlsugarScope = db.GetConnectionScope(it.ConfigId);//获取当前库
var sqlsugarScope = db.GetConnection(it.ConfigId);//获取当前库
MoreSetting(sqlsugarScope);//更多设置
SugarAopService.AopSetting(sqlsugarScope, it.IsShowSql);//aop配置
}
@@ -75,7 +94,7 @@ public static class DbContext
/// 实体更多配置
/// </summary>
/// <param name="db"></param>
private static void MoreSetting(SqlSugarScopeProvider db)
private static void MoreSetting(SqlSugarProvider db)
{
db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings
{

View File

@@ -24,7 +24,7 @@ namespace ThingsGateway.Admin.Application;
/// 种子数据工具类
/// </summary>
[ThingsGateway.DependencyInjection.SuppressSniffer]
public static class SeedDataUtil
public static partial class SeedDataUtil
{
/// <summary>
/// 获取List列表
@@ -53,9 +53,7 @@ public static class SeedDataUtil
if (!string.IsNullOrEmpty(json))//如果有内容
{
//字段没有数据的替换成null
json = Regex.Replace(json, "\\\"[^\"]+?\\\": \\\"\\\"", match => match.Value.Replace("\"\"", "null"));
json = SeedDataRegex().Replace(json, match => match.Value.Replace("\"\"", "null"));
var jtoken = JToken.Parse(json);
jtoken = jtoken.SelectToken("Records") ?? jtoken.SelectToken("RECORDS");
@@ -96,6 +94,9 @@ public static class SeedDataUtil
return seedData;
}
[GeneratedRegex("\\\"[^\"]+?\\\": \\\"\\\"")]
private static partial Regex SeedDataRegex();
}
/// <summary>

View File

@@ -22,6 +22,7 @@
</ItemGroup>
<ItemGroup>
<!--<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />-->
<ProjectReference Include="..\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />
<ProjectReference Include="..\ThingsGateway.SqlSugar\ThingsGateway.SqlSugar.csproj" />
<!--<PackageReference Include="SqlSugarCore" Version="5.1.4.195" />-->

View File

@@ -87,8 +87,8 @@ internal static class Penetrates
// 本地静态方法
static bool Function(Type type)
{
// 排除 OData 控制器
if (type.Assembly.GetName().Name.StartsWith("Microsoft.AspNetCore.OData")) return false;
//// 排除 OData 控制器
//if (type.Assembly.GetName().Name.StartsWith("Microsoft.AspNetCore.OData")) return false;
// 不能是非公开、基元类型、值类型、抽象类、接口、泛型类
if (!type.IsPublic || type.IsPrimitive || type.IsValueType || type.IsAbstract || type.IsInterface || type.IsGenericType) return false;

View File

@@ -37,15 +37,15 @@ public sealed class Retry
{
if (action == null) throw new ArgumentNullException(nameof(action));
InvokeAsync(async () =>
InvokeAsync(() =>
{
action();
await Task.CompletedTask.ConfigureAwait(false);
return Task.CompletedTask;
}, numRetries, retryTimeout, finalThrow, exceptionTypes, fallbackPolicy == null ? null
: async (ex) =>
: (ex) =>
{
fallbackPolicy?.Invoke(ex);
await Task.CompletedTask.ConfigureAwait(false);
return Task.CompletedTask;
}, retryAction).GetAwaiter().GetResult();
}

View File

@@ -160,8 +160,8 @@ public sealed class DatabaseLoggerProvider : ILoggerProvider, ISupportExternalSc
_databaseLoggingWriter = _serviceScope.ServiceProvider.GetRequiredService(databaseLoggingWriterType) as IDatabaseLoggingWriter;
// 创建长时间运行的后台任务,并将日志消息队列中数据写入存储中
_processQueueTask = Task.Factory.StartNew(async state => await ((DatabaseLoggerProvider)state).ProcessQueueAsync().ConfigureAwait(false)
, this, TaskCreationOptions.LongRunning);
_processQueueTask = Task.Factory.StartNew(ProcessQueueAsync
, TaskCreationOptions.LongRunning);
}
/// <summary>

View File

@@ -90,8 +90,7 @@ public sealed class FileLoggerProvider : ILoggerProvider, ISupportExternalScope
_fileLoggingWriter = new FileLoggingWriter(this);
// 创建长时间运行的后台任务,并将日志消息队列中数据写入文件中
_processQueueTask = Task.Factory.StartNew(async state => await ((FileLoggerProvider)state).ProcessQueueAsync().ConfigureAwait(false)
, this, TaskCreationOptions.LongRunning);
_processQueueTask = Task.Factory.StartNew(ProcessQueueAsync, TaskCreationOptions.LongRunning);
}
/// <summary>

View File

@@ -110,8 +110,7 @@ internal sealed partial class SchedulerFactory : ISchedulerFactory
if (Persistence is not null)
{
// 创建长时间运行的后台任务,并将作业运行消息写入持久化中
_processQueueTask = Task.Factory.StartNew(async state => await ((SchedulerFactory)state).ProcessQueueAsync().ConfigureAwait(false)
, this, TaskCreationOptions.LongRunning);
_processQueueTask = Task.Factory.StartNew(ProcessQueueAsync, TaskCreationOptions.LongRunning);
}
}

View File

@@ -127,63 +127,57 @@ public class MachineInfo
//static MachineInfo() => RegisterAsync().Wait(100);
private static Task<MachineInfo>? _task;
/// <summary>异步注册一个初始化后的机器信息实例</summary>
/// <returns></returns>
public static Task<MachineInfo> RegisterAsync()
public static MachineInfo Register()
{
if (_task != null) return _task;
return _task = Task.Factory.StartNew(() =>
if (Current != null) return Current;
// 文件缓存加快机器信息获取。在Linux下可能StarAgent以root权限写入缓存文件其它应用以普通用户访问
var file = Path.GetTempPath().CombinePath("machine_info.json");
var json = "";
if (Current == null)
{
// 文件缓存加快机器信息获取。在Linux下可能StarAgent以root权限写入缓存文件其它应用以普通用户访问
var file = Path.GetTempPath().CombinePath("machine_info.json");
var json = "";
if (Current == null)
var f = file;
if (File.Exists(f))
{
var f = file;
if (File.Exists(f))
try
{
try
{
//XTrace.WriteLine("Load MachineInfo {0}", f);
json = File.ReadAllText(f);
Current = json.FromJsonNetString<MachineInfo>();
}
catch (Exception ex)
{
if (XTrace.Log.Level <= LogLevel.Debug) NewLife.Log.XTrace.WriteException(ex);
}
//XTrace.WriteLine("Load MachineInfo {0}", f);
json = File.ReadAllText(f);
Current = json.FromJsonNetString<MachineInfo>();
}
catch (Exception ex)
{
if (XTrace.Log.Level <= LogLevel.Debug) NewLife.Log.XTrace.WriteException(ex);
}
}
}
var mi = Current ?? new MachineInfo();
var mi = Current ?? new MachineInfo();
mi.Init();
Current = mi;
mi.Init();
Current = mi;
try
try
{
var json2 = mi.ToJsonNetString();
if (json != json2)
{
var json2 = mi.ToJsonNetString();
if (json != json2)
{
File.WriteAllText(file.EnsureDirectory(true), json2);
}
}
catch (Exception ex)
{
if (XTrace.Log.Level <= LogLevel.Debug) NewLife.Log.XTrace.WriteException(ex);
File.WriteAllText(file.EnsureDirectory(true), json2);
}
}
catch (Exception ex)
{
if (XTrace.Log.Level <= LogLevel.Debug) NewLife.Log.XTrace.WriteException(ex);
}
return mi;
});
return mi;
}
/// <summary>获取当前信息,如果未设置则等待异步注册结果</summary>
/// <returns></returns>
public static MachineInfo GetCurrent() => Current ?? RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult();
public static MachineInfo GetCurrent() => Current ?? Register();
#endregion

View File

@@ -172,7 +172,6 @@ public class TimerScheduler : ILogFeature
else if (!timer.Async)
Execute(timer);
else
//Task.Factory.StartNew(() => ProcessItem(timer));
// 不需要上下文流动,捕获所有异常
ThreadPool.UnsafeQueueUserWorkItem(s =>
{
@@ -231,8 +230,6 @@ public class TimerScheduler : ILogFeature
{
if (state is not TimerX timer) return;
TimerX.Current = timer;
// 控制日志显示
WriteLogEventArgs.CurrentThreadName = Name == "Default" ? "T" : Name;
@@ -274,7 +271,6 @@ public class TimerScheduler : ILogFeature
{
if (state is not TimerX timer) return;
TimerX.Current = timer;
// 控制日志显示
WriteLogEventArgs.CurrentThreadName = Name == "Default" ? "T" : Name;
@@ -322,8 +318,6 @@ public class TimerScheduler : ILogFeature
timer.Calling = false;
TimerX.Current = null;
// 控制日志显示
WriteLogEventArgs.CurrentThreadName = null;

View File

@@ -84,15 +84,7 @@ public class TimerX : ITimer, IDisposable
private readonly Cron[]? _crons;
#endregion
#region
#if NET452
private static readonly ThreadLocal<TimerX?> _Current = new();
#else
private static readonly AsyncLocal<TimerX?> _Current = new();
#endif
/// <summary>当前定时器</summary>
public static TimerX? Current { get => _Current.Value; set => _Current.Value = value; }
#endregion
#region
private TimerX(Object? target, MethodInfo method, Object? state, String? scheduler = null)
@@ -382,19 +374,27 @@ public class TimerX : ITimer, IDisposable
/// <param name="period">构造 Timer 时指定的回调方法调用之间的时间间隔。 指定 InfiniteTimeSpan 可以禁用定期终止。</param>
/// <returns></returns>
public Boolean Change(TimeSpan dueTime, TimeSpan period)
{
return Change((int)dueTime.TotalMilliseconds, (int)period.TotalMilliseconds);
}
/// <summary>更改计时器的启动时间和方法调用之间的时间间隔,使用 TimeSpan 值度量时间间隔。</summary>
/// <param name="dueTime">一个 TimeSpan表示在调用构造 ITimer 时指定的回调方法之前的延迟时间量。 指定 InfiniteTimeSpan 可防止重新启动计时器。 指定 Zero 可立即重新启动计时器。</param>
/// <param name="period">构造 Timer 时指定的回调方法调用之间的时间间隔。 指定 InfiniteTimeSpan 可以禁用定期终止。</param>
/// <returns></returns>
public Boolean Change(int dueTime, int period)
{
if (Absolutely) return false;
if (Crons?.Length > 0) return false;
if (period.TotalMilliseconds <= 0)
if (period <= 0)
{
Dispose();
return true;
}
Period = (Int32)period.TotalMilliseconds;
Period = period;
if (dueTime.TotalMilliseconds >= 0) SetNext((Int32)dueTime.TotalMilliseconds);
if (dueTime >= 0) SetNext(dueTime);
return true;
}

View File

@@ -280,43 +280,6 @@ public static class ControlHelper
}
}
private static void ProcessBell(ref String m)
{
var ch = (Char)7;
var p = 0;
while (true)
{
p = m.IndexOf(ch, p);
if (p < 0) break;
if (p > 0)
{
var str = m[..p];
if (p + 1 < m.Length) str += m[(p + 1)..];
m = str;
}
//Console.Beep();
// 用定时器来控制Beep避免被堵塞
_timer ??= new TimerX(Bell, null, 100, 100);
_Beep = true;
//SystemSounds.Beep.Play();
p++;
}
}
private static TimerX? _timer;
private static Boolean _Beep;
private static void Bell(Object? state)
{
if (_Beep)
{
_Beep = false;
Console.Beep();
}
}
[DllImport("user32.dll")]
private static extern Int32 SendMessage(IntPtr hwnd, Int32 wMsg, Int32 wParam, Int32 lParam);
private const Int32 SB_TOP = 6;

View File

@@ -13,6 +13,7 @@ namespace ThingsGateway.Razor;
/// <summary>
/// 母版页基类
/// </summary>
[BlazorSetParametersAsyncGenerator.DoNotGenerateSetParametersAsync]
public partial class BaseLayout
{
}

View File

@@ -11,7 +11,7 @@
namespace ThingsGateway.Razor;
/// <inheritdoc/>
public abstract class WebSiteModuleComponentBase : BootstrapModuleComponentBase
public abstract partial class WebSiteModuleComponentBase : BootstrapModuleComponentBase
{
/// <inheritdoc/>
protected override void OnLoadJSModule()

View File

@@ -41,14 +41,16 @@
}
<PopConfirmButton IsAsync IsDisabled=@_importPreviews.Any(it => it.Value.HasError) Color=Color.Warning class="mt-2" OnConfirm=@(SaveDeviceImport)>@Localizer["Import"]</PopConfirmButton>
<Button IsAsync class="mt-2" IsDisabled=@_importPreviews.Any(it => it.Value.HasError) OnClick="() => step.Next()">@Localizer["Next"]</Button>
@*
<Button IsAsync class="mt-2" IsDisabled=@_importPreviews.Any(it => it.Value.HasError) OnClick="() => step.Next()">@Localizer["Next"]</Button> *@
</div>
</StepItem>
<StepItem Text=@Localizer["Third"] Title=@Localizer["Import"]>
@* <StepItem Text=@Localizer["Third"] Title=@Localizer["Import"]>
<PopConfirmButton IsAsync Color=Color.Warning class="mt-2" OnConfirm=@(SaveDeviceImport)>@Localizer["Import"]</PopConfirmButton>
</StepItem>
</StepItem> *@
</Step>
@code {
[NotNull]

View File

@@ -8,6 +8,8 @@
// QQ群605534569
//------------------------------------------------------------------------------
using System.Collections.Concurrent;
namespace ThingsGateway;
/// <summary>
@@ -22,7 +24,7 @@ public static class ParallelExtensions
/// <typeparam name="T">集合元素类型</typeparam>
/// <param name="source">要操作的集合</param>
/// <param name="body">要执行的操作</param>
public static void ParallelForEach<T>(this IEnumerable<T> source, Action<T> body)
public static void ParallelForEach<T>(this IList<T> source, Action<T> body)
{
ParallelOptions options = new();
options.MaxDegreeOfParallelism = Environment.ProcessorCount;
@@ -39,7 +41,7 @@ public static class ParallelExtensions
/// <typeparam name="T">集合元素类型</typeparam>
/// <param name="source">要操作的集合</param>
/// <param name="body">要执行的操作</param>
public static void ParallelForEach<T>(this IEnumerable<T> source, Action<T, ParallelLoopState, long> body)
public static void ParallelForEach<T>(this IList<T> source, Action<T, ParallelLoopState, long> body)
{
ParallelOptions options = new();
options.MaxDegreeOfParallelism = Environment.ProcessorCount;
@@ -57,7 +59,7 @@ public static class ParallelExtensions
/// <param name="source">要操作的集合</param>
/// <param name="body">要执行的操作</param>
/// <param name="parallelCount">最大并行度</param>
public static void ParallelForEach<T>(this IEnumerable<T> source, Action<T> body, int parallelCount)
public static void ParallelForEach<T>(this IList<T> source, Action<T> body, int parallelCount)
{
// 创建并行操作的选项对象,设置最大并行度为指定的值
var options = new ParallelOptions();
@@ -69,6 +71,47 @@ public static class ParallelExtensions
});
}
/// <summary>
/// 使用默认的并行设置执行指定的操作Partitioner 分区)
/// </summary>
public static void ParallelForEachStreamed<T>(this IEnumerable<T> source, Action<T> body)
{
var partitioner = Partitioner.Create<T>(source, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount
}, body);
}
/// <summary>
/// 使用默认的并行设置执行指定的操作(带索引和 LoopStatePartitioner 分区)
/// </summary>
public static void ParallelForEachStreamed<T>(this IEnumerable<T> source, Action<T, ParallelLoopState, long> body)
{
var partitioner = Partitioner.Create<T>(source, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount
}, (item, state, index) => body(item, state, index));
}
/// <summary>
/// 执行指定的操作并指定最大并行度Partitioner 分区)
/// </summary>
public static void ParallelForEachStreamed<T>(this IEnumerable<T> source, Action<T> body, int parallelCount)
{
var options = new ParallelOptions
{
MaxDegreeOfParallelism = parallelCount <= 0 ? 1 : parallelCount
};
var partitioner = Partitioner.Create<T>(source, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, options, body);
}
/// <summary>
/// 异步执行指定的操作,并指定最大并行度和取消标志
/// </summary>
@@ -78,7 +121,7 @@ public static class ParallelExtensions
/// <param name="parallelCount">最大并行度</param>
/// <param name="cancellationToken">取消操作的标志</param>
/// <returns>表示异步操作的任务</returns>
public static Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, CancellationToken, ValueTask> body, int parallelCount, CancellationToken cancellationToken = default)
public static Task ParallelForEachAsync<T>(this IList<T> source, Func<T, CancellationToken, ValueTask> body, int parallelCount, CancellationToken cancellationToken = default)
{
// 创建并行操作的选项对象,设置最大并行度和取消标志
var options = new ParallelOptions();
@@ -95,8 +138,10 @@ public static class ParallelExtensions
/// <param name="body">异步执行的操作</param>
/// <param name="cancellationToken">取消操作的标志</param>
/// <returns>表示异步操作的任务</returns>
public static Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, CancellationToken, ValueTask> body, CancellationToken cancellationToken = default)
public static Task ParallelForEachAsync<T>(this IList<T> source, Func<T, CancellationToken, ValueTask> body, CancellationToken cancellationToken = default)
{
return ParallelForEachAsync(source, body, Environment.ProcessorCount, cancellationToken);
}
}

View File

@@ -21,3 +21,4 @@ global using System.Globalization;
[assembly: SuppressMessage("Reliability", "CA2007", Justification = "<挂起>", Scope = "module")]
[assembly: BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsync(true)]

View File

@@ -5,10 +5,11 @@
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Reflection;
using System.Resources;
using ThingsGateway.NewLife.Collections;
namespace ThingsGateway;
/// <summary>
@@ -107,14 +108,14 @@ internal class JsonStringLocalizer(Assembly assembly, string typeName, string ba
return ret;
}
private readonly ConcurrentDictionary<string, object?> _missingManifestCache = [];
private readonly ConcurrentHashSet<string> _missingManifestCache = [];
private string? GetStringFromJson(string name)
{
// get string from json localization file
var localizerStrings = MegerResolveLocalizers(CacheManager.GetAllStringsByTypeName(Assembly, typeName));
var cacheKey = $"name={name}&culture={CultureInfo.CurrentUICulture.Name}";
string? ret = null;
if (!_missingManifestCache.ContainsKey(cacheKey))
if (!_missingManifestCache.Contain(cacheKey))
{
var l = localizerStrings.Find(i => i.Name == name);
if (l is { ResourceNotFound: false })
@@ -161,6 +162,7 @@ internal class JsonStringLocalizer(Assembly assembly, string typeName, string ba
private List<LocalizedString> MegerResolveLocalizers(IEnumerable<LocalizedString>? localizerStrings)
{
var localizers = new List<LocalizedString>(CacheManager.GetTypeStringsFromResolve(typeName));
if (localizerStrings != null)
{
localizers.AddRange(localizerStrings);
@@ -175,7 +177,7 @@ internal class JsonStringLocalizer(Assembly assembly, string typeName, string ba
{
Logger.LogInformation("{JsonStringLocalizerName} searched for '{Name}' in '{TypeName}' with culture '{CultureName}' not found.", nameof(JsonStringLocalizer), name, typeName, CultureInfo.CurrentUICulture.Name);
}
_missingManifestCache.TryAdd($"name={name}&culture={CultureInfo.CurrentUICulture.Name}", null);
_missingManifestCache.TryAdd($"name={name}&culture={CultureInfo.CurrentUICulture.Name}");
}
private List<LocalizedString>? _allLocalizerdStrings;

View File

@@ -47,7 +47,7 @@ public class Startup : AppStartup
// 缓存
services.AddSingleton<ICache, MemoryCache>();
MachineInfo.RegisterAsync();
MachineInfo.Register();
// 配置雪花Id算法机器码
YitIdHelper.SetIdGenerator(new IdGeneratorOptions

View File

@@ -1,23 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;</TargetFrameworks>
<TargetFrameworks>net8.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BootstrapBlazor.FontAwesome" Version="9.0.2" />
<PackageReference Include="BootstrapBlazor" Version="9.7.3" />
<PackageReference Include="BootstrapBlazor" Version="9.7.4-beta09" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
</ItemGroup>
<ItemGroup>
<Content Remove="Locales\*.json" />
<EmbeddedResource Include="Locales\*.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
@@ -30,6 +28,16 @@
<ProjectReference Include="..\ThingsGateway.Furion\ThingsGateway.Furion.csproj" />
</ItemGroup>
<!--<ItemGroup Condition="'$(Configuration)' != 'Debug' ">
<None Include="..\BlazorSetParametersAsyncGenerator\tools\*.ps1" PackagePath="tools" Pack="true" Visible="false" />
<None Include="..\BlazorSetParametersAsyncGenerator\bin\$(Configuration)\netstandard2.0\BlazorSetParametersAsyncGenerator.dll" PackagePath="analyzers\dotnet\cs" Pack="true" Visible="false" />
</ItemGroup>-->
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,4 @@

@using System.Net.Http
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@@ -16,4 +15,5 @@
@using BootstrapBlazor.Components
@using ThingsGateway.Razor;
@using ThingsGateway.Razor

View File

@@ -7,8 +7,8 @@ namespace ThingsGateway.SqlSugar
/// </summary>
public partial class SqlSugarScope : ISqlSugarClient, ITenant
{
private List<ConnectionConfig> _configs;
private Action<SqlSugarClient> _configAction;
protected List<ConnectionConfig> _configs;
protected Action<SqlSugarClient> _configAction;
protected virtual SqlSugarClient GetContext()
{

View File

@@ -161,7 +161,7 @@ namespace ThingsGateway.SqlSugar
}
else if (db is SqlSugarScope)
{
db = (db as SqlSugarScope).ScopedContext.Context;
db = (db as SqlSugarScope).Context;
}
if (!(db is SqlSugarProvider))
{
@@ -685,17 +685,20 @@ namespace ThingsGateway.SqlSugar
private static Type GetCustomDbType(string className, Type type)
{
if (className.Replace(".", "").Length + 1 == className.Length)
//命名空间相关
if (className.Replace(".", "").Length + 2 == className.Length)
{
var array = className.Split('.');
foreach (var item in UtilMethods.EnumToDictionary<DbType>())
if (array.Length >= 3)
{
if (array.Last().StartsWith(item.Value.ToString()))
foreach (var item in UtilMethods.EnumToDictionary<DbType>())
{
var newName = array.First() + "." + item.Value.ToString() + "." + array.Last();
type = GetCustomTypeByClass(newName);
break;
if (array.Last().StartsWith(item.Value.ToString()))
{
var newName = $"{array[0]}.{array[1]}.{item.Value}.{array.Last()}";
type = GetCustomTypeByClass(newName);
break;
}
}
}

View File

@@ -1,4 +1,6 @@
namespace ThingsGateway.SqlSugar
using ThingsGateway.NewLife.Caching;
namespace ThingsGateway.SqlSugar
{
public class ReflectionInoCacheService : ICacheService
{
@@ -6,6 +8,7 @@
{
ReflectionInoCore<V>.GetInstance().Add(key, value);
}
public void Add<V>(string key, V value, int cacheDurationInSeconds)
{
ReflectionInoCore<V>.GetInstance().Add(key, value, cacheDurationInSeconds);
@@ -38,7 +41,7 @@
}
public class ReflectionInoCore<V>
{
readonly System.Collections.Concurrent.ConcurrentDictionary<string, V> InstanceCache = new System.Collections.Concurrent.ConcurrentDictionary<string, V>();
readonly MemoryCache InstanceCache = new() { Expire = 1800 };
private static ReflectionInoCore<V> _instance = null;
private static readonly object _instanceLock = new object();
private ReflectionInoCore() { }
@@ -58,10 +61,7 @@
public V Get(string key)
{
if (this.ContainsKey(key))
return this.InstanceCache[key];
else
return default(V);
return this.InstanceCache.Get<V>(key);
}
public static ReflectionInoCore<V> GetInstance()
@@ -89,8 +89,7 @@
public void Remove(string key)
{
V val;
this.InstanceCache.TryRemove(key, out val);
this.InstanceCache.Remove(key);
}
public void RemoveAllCache()
@@ -108,13 +107,7 @@
public V GetOrCreate(string cacheKey, Func<V> create)
{
if (this.ContainsKey(cacheKey)) return Get(cacheKey);
else
{
var reval = create();
this.Add(cacheKey, reval);
return reval;
}
return InstanceCache.GetOrAdd<V>(cacheKey, (a) => create());
}
}
public static class ReflectionInoHelper

View File

@@ -28,7 +28,8 @@ namespace ThingsGateway.SqlSugar
_configs = configs;
this._configAction = configAction;
}
public SqlSugarClient ScopedContext { get { return GetContext(); } }
public ISqlSugarClient Context => ScopedContext.Context;
protected SqlSugarClient ScopedContext { get { return GetContext(); } }
public SugarActionType SugarActionType { get => ScopedContext.SugarActionType; set => ScopedContext.SugarActionType = value; }
public MappingTableList MappingTables { get => ScopedContext.MappingTables; set => ScopedContext.MappingTables = value; }
public MappingColumnList MappingColumns { get => ScopedContext.MappingColumns; set => ScopedContext.MappingColumns = value; }

View File

@@ -23,7 +23,7 @@
<ItemGroup>
<PackageReference Include="SqlSugarCore.Dm" Version="8.8.0" />
<PackageReference Include="SqlSugarCore.Kdbndp" Version="9.3.7.605" />
<PackageReference Include="SqlSugarCore.Kdbndp" Version="9.3.7.613" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="$(NET9Version)" />
<PackageReference Include="MySqlConnector" Version="2.4.0" />
<PackageReference Include="Npgsql" Version="9.0.3" />

92
src/Base1.sln Normal file
View File

@@ -0,0 +1,92 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "other", "other", "{0B748352-5D27-4F14-8A20-364034C72867}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
Directory.Build.props = Directory.Build.props
..\git_pull.bat = ..\git_pull.bat
..\README.md = ..\README.md
..\README.zh-CN.md = ..\README.zh-CN.md
Version.props = Version.props
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Foundation", "Foundation", "{2AC600BB-4325-4E0A-93A7-B1F53C8E2CA7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThingsGateway.CSScript", "Foundation\ThingsGateway.CSScript\ThingsGateway.CSScript.csproj", "{506232CE-0FB6-4ACB-96DE-C8C8D075A642}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThingsGateway.Foundation", "Foundation\ThingsGateway.Foundation\ThingsGateway.Foundation.csproj", "{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThingsGateway.Foundation.SourceGenerator", "Foundation\ThingsGateway.Foundation.SourceGenerator\ThingsGateway.Foundation.SourceGenerator.csproj", "{E325A64C-2B72-4DD0-8A6C-229B29FB95EB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThingsGateway.Foundation.Variable", "Foundation\ThingsGateway.Foundation.Variable\ThingsGateway.Foundation.Variable.csproj", "{8EE037EC-ED21-42A0-BE1F-219E9886E43A}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Admin", "Admin", "{72C65578-92A5-4E99-9779-27835B12B32F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThingsGateway.Furion", "Admin\ThingsGateway.Furion\ThingsGateway.Furion.csproj", "{D56A6669-28C5-4A99-89CF-356C7964B8E1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThingsGateway.NewLife.X", "Admin\ThingsGateway.NewLife.X\ThingsGateway.NewLife.X.csproj", "{8198BEEA-AC24-4D70-B3D7-2601A803610B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThingsGateway.Razor", "Admin\ThingsGateway.Razor\ThingsGateway.Razor.csproj", "{93C0CC9A-500E-419A-B896-F36225377D43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorSetParametersAsyncGenerator", "Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj", "{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{506232CE-0FB6-4ACB-96DE-C8C8D075A642}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{506232CE-0FB6-4ACB-96DE-C8C8D075A642}.Debug|Any CPU.Build.0 = Debug|Any CPU
{506232CE-0FB6-4ACB-96DE-C8C8D075A642}.Release|Any CPU.ActiveCfg = Release|Any CPU
{506232CE-0FB6-4ACB-96DE-C8C8D075A642}.Release|Any CPU.Build.0 = Release|Any CPU
{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0}.Release|Any CPU.Build.0 = Release|Any CPU
{E325A64C-2B72-4DD0-8A6C-229B29FB95EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E325A64C-2B72-4DD0-8A6C-229B29FB95EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E325A64C-2B72-4DD0-8A6C-229B29FB95EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E325A64C-2B72-4DD0-8A6C-229B29FB95EB}.Release|Any CPU.Build.0 = Release|Any CPU
{8EE037EC-ED21-42A0-BE1F-219E9886E43A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8EE037EC-ED21-42A0-BE1F-219E9886E43A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8EE037EC-ED21-42A0-BE1F-219E9886E43A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8EE037EC-ED21-42A0-BE1F-219E9886E43A}.Release|Any CPU.Build.0 = Release|Any CPU
{D56A6669-28C5-4A99-89CF-356C7964B8E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D56A6669-28C5-4A99-89CF-356C7964B8E1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D56A6669-28C5-4A99-89CF-356C7964B8E1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D56A6669-28C5-4A99-89CF-356C7964B8E1}.Release|Any CPU.Build.0 = Release|Any CPU
{8198BEEA-AC24-4D70-B3D7-2601A803610B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8198BEEA-AC24-4D70-B3D7-2601A803610B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8198BEEA-AC24-4D70-B3D7-2601A803610B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8198BEEA-AC24-4D70-B3D7-2601A803610B}.Release|Any CPU.Build.0 = Release|Any CPU
{93C0CC9A-500E-419A-B896-F36225377D43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{93C0CC9A-500E-419A-B896-F36225377D43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93C0CC9A-500E-419A-B896-F36225377D43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{93C0CC9A-500E-419A-B896-F36225377D43}.Release|Any CPU.Build.0 = Release|Any CPU
{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{506232CE-0FB6-4ACB-96DE-C8C8D075A642} = {2AC600BB-4325-4E0A-93A7-B1F53C8E2CA7}
{9D49F8E2-A82C-4E36-8F54-4F45BF3E47C0} = {2AC600BB-4325-4E0A-93A7-B1F53C8E2CA7}
{E325A64C-2B72-4DD0-8A6C-229B29FB95EB} = {2AC600BB-4325-4E0A-93A7-B1F53C8E2CA7}
{8EE037EC-ED21-42A0-BE1F-219E9886E43A} = {2AC600BB-4325-4E0A-93A7-B1F53C8E2CA7}
{D56A6669-28C5-4A99-89CF-356C7964B8E1} = {72C65578-92A5-4E99-9779-27835B12B32F}
{8198BEEA-AC24-4D70-B3D7-2601A803610B} = {72C65578-92A5-4E99-9779-27835B12B32F}
{93C0CC9A-500E-419A-B896-F36225377D43} = {72C65578-92A5-4E99-9779-27835B12B32F}
{4C412EC1-8501-8211-5A57-3CEEE7EEA6B3} = {72C65578-92A5-4E99-9779-27835B12B32F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
RESX_NeutralResourcesLanguage = zh-Hans
RESX_Rules = {"EnabledRules":[]}
SolutionGuid = {199B1B96-4F56-4828-9531-813BA02DB282}
EndGlobalSection
EndGlobal

View File

@@ -1,9 +1,10 @@
<Project>
<PropertyGroup>
<PluginVersion>10.7.58</PluginVersion>
<ProPluginVersion>10.7.58</ProPluginVersion>
<AuthenticationVersion>2.6.0</AuthenticationVersion>
<PluginVersion>10.8.10</PluginVersion>
<ProPluginVersion>10.8.10</ProPluginVersion>
<AuthenticationVersion>2.8.0</AuthenticationVersion>
<SourceGeneratorVersion>10.8.2</SourceGeneratorVersion>
<NET8Version>8.0.17</NET8Version>
<NET9Version>9.0.6</NET9Version>
</PropertyGroup>
@@ -24,7 +25,7 @@
<AnalysisModeStyle>None</AnalysisModeStyle>
<NoWarn>
CS8603;CS8618;CS1591;CS8625;CS8602;CS8604;CS8600;CS8601;CS8714;CS8619;CS8629;CS8765;CS8634;CS8621;CS8767;CS8633;CS8620;CS8610;CS8631;CS8605;CS8622;CS8613;NU5100;NU5104;NU1903;NU1902;CA1813;CA1852;CA1822;CA2100;CA2008;CA1812;CA1508;CA1512;CA1513;CA1810;CA1814;CA1815;CA1835;CA1819;CA1823;CA2002;CA5350;CA5351;CA5358;CA5384;CA5392;CA1805;CA1851;CA1510;CA5401;CA2022;CA1848;CA2000;CA5394;CA3003;CA1515;CA1849;CA1863
CS8603;CS8618;CS1591;CS8625;CS8602;CS8604;CS8600;CS8601;CS8714;CS8619;CS8629;CS8765;CS8634;CS8621;CS8767;CS8633;CS8620;CS8610;CS8631;CS8605;CS8622;CS8613;NU5100;NU5104;NU1903;NU1902;CA1813;CA1852;CA1822;CA2100;CA2008;CA1812;CA1508;CA1512;CA1513;CA1810;CA1814;CA1815;CA1835;CA1819;CA1823;CA2002;CA5350;CA5351;CA5358;CA5384;CA5392;CA1805;CA1851;CA1510;CA5401;CA2022;CA1848;CA2000;CA5394;CA3003;CA1515;CA1849;CA1863;CA5400
</NoWarn>
<TargetFrameworks>net8.0;</TargetFrameworks>
<LangVersion>13.0</LangVersion>

View File

@@ -36,6 +36,7 @@
<EditorItem @bind-Field="@context.StopBits" Ignore=@(context.ChannelType!=ChannelTypeEnum.SerialPort) />
<EditorItem @bind-Field="@context.DtrEnable" Ignore=@(context.ChannelType!=ChannelTypeEnum.SerialPort) />
<EditorItem @bind-Field="@context.RtsEnable" Ignore=@(context.ChannelType!=ChannelTypeEnum.SerialPort) />
<EditorItem @bind-Field="@context.StreamAsync" Ignore=@(context.ChannelType!=ChannelTypeEnum.SerialPort) />
<EditorItem @bind-Field="@context.CacheTimeout" Ignore=@(context.ChannelType==ChannelTypeEnum.UdpSession||context.ChannelType==ChannelTypeEnum.Other) />

View File

@@ -1,6 +1,7 @@
@using Microsoft.AspNetCore.Components.Web;
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop;
@using ThingsGateway.Foundation
@using ThingsGateway.NewLife.Threading
@using ThingsGateway.Extension;
@using BootstrapBlazor.Components

View File

@@ -228,15 +228,3 @@ public partial class LogConsole : IDisposable
}
}
}
public class LogMessage
{
public LogMessage(int level, string message)
{
Level = level;
Message = message;
}
public int Level { get; set; }
public string Message { get; set; }
}

View File

@@ -0,0 +1,25 @@
//------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权除特别声明外的代码归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库https://github.com/kimdiego2098/ThingsGateway
// 使用文档https://thingsgateway.cn/
// QQ群605534569
//------------------------------------------------------------------------------
namespace ThingsGateway.Foundation;
/// <inheritdoc/>
public class LogMessage
{
public LogMessage(int level, string message)
{
Level = level;
Message = message;
}
public int Level { get; set; }
public string Message { get; set; }
}

View File

@@ -18,3 +18,5 @@ global using System.Diagnostics.CodeAnalysis;
global using ThingsGateway.Razor;
[assembly: SuppressMessage("Reliability", "CA2007", Justification = "<挂起>", Scope = "module")]
[assembly: BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsync(true)]

View File

@@ -23,6 +23,7 @@
"PortName": "COM Port",
"RemoteUrl": "Remote IP Address",
"RtsEnable": "Rts",
"StreamAsync": "StreamAsync",
"SaveChannel": "Add/Modify Channel",
"StopBits": "Stop Bits"
},
@@ -80,6 +81,7 @@
"PortName": "PortName",
"RemoteUrl": "RemoteUrl",
"RtsEnable": "RtsEnable",
"StreamAsync": "StreamAsync",
"StopBits": "StopBits"
}
}

View File

@@ -23,6 +23,7 @@
"PortName": "COM口",
"RemoteUrl": "远程url",
"RtsEnable": "Rts",
"StreamAsync": "串口流读写",
"SaveChannel": "添加/修改通道",
"StopBits": "停止位"
},
@@ -80,6 +81,7 @@
"PortName": "COM口",
"RemoteUrl": "远程url",
"RtsEnable": "Rts",
"StreamAsync": "串口流读写",
"StopBits": "停止位"
}
}

View File

@@ -4,8 +4,10 @@
<Import Project="$(SolutionDir)PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;</TargetFrameworks>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</PropertyGroup>
<ItemGroup>
<!--<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />-->
<ProjectReference Include="..\..\Admin\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />
<ProjectReference Include="..\ThingsGateway.Foundation\ThingsGateway.Foundation.csproj" />
</ItemGroup>
@@ -20,8 +22,10 @@
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="$(SolutionDir)Version.props" />
<PropertyGroup>
<TargetFrameworks>netstandard2.0;</TargetFrameworks>
<Version>$(SourceGeneratorVersion)</Version>
</PropertyGroup>
<ItemGroup>

View File

@@ -68,6 +68,11 @@ namespace ThingsGateway.Foundation
/// </summary>
public virtual bool DtrEnable { get; set; } = true;
/// <summary>
/// StreamAsync
/// </summary>
public virtual bool StreamAsync { get; set; } = false;
/// <summary>
/// RtsEnable
/// </summary>

View File

@@ -73,6 +73,10 @@ public interface IChannelOptions
/// </summary>
bool RtsEnable { get; set; }
/// <summary>
/// StreamAsync
/// </summary>
bool StreamAsync { get; set; }
#endregion
/// <summary>

View File

@@ -549,7 +549,7 @@ public abstract class DeviceBase : DisposableObject, IDevice
Channel.ChannelReceivedWaitDict.TryAdd(sign, ChannelReceived);
var sendOperResult = await SendAsync(command, clientChannel, endPoint, cancellationToken).ConfigureAwait(false);
if (!sendOperResult.IsSuccess)
throw sendOperResult.Exception ?? new(sendOperResult.ErrorMessage);
throw sendOperResult.Exception ?? new(sendOperResult.ErrorMessage ?? "unknown error");
await waitData.WaitAsync(timeout).ConfigureAwait(false);

View File

@@ -112,11 +112,18 @@ public static partial class DeviceExtension
int index = variable.Index;
try
{
var data = byteConverter.GetDataFormBytes(device, variable.RegisterAddress, buffer, index, dataType, variable.ArrayLength ?? 1);
result = Set(variable, data);
if (exWhenAny)
if (!result.IsSuccess)
return result;
var changed = byteConverter.GetChangedDataFormBytes(device, variable.RegisterAddress, buffer, index, dataType, variable.ArrayLength ?? 1, variable.Value, out var data);
if (changed)
{
result = variable.SetValue(data, time);
if (exWhenAny)
if (!result.IsSuccess)
return result;
}
else
{
variable.SetNoChangedValue(time);
}
}
catch (Exception ex)
{
@@ -124,10 +131,7 @@ public static partial class DeviceExtension
}
}
return result;
OperResult Set(IVariable organizedVariable, object num)
{
return organizedVariable.SetValue(num, time);
}
}
/// <summary>

View File

@@ -20,6 +20,7 @@
"PortName": "PortName",
"RemoteUrl": "RemoteUrl",
"RtsEnable": "RtsEnable",
"StreamAsync": "StreamAsync",
"StopBits": "StopBits"
},
"ThingsGateway.Foundation.ConverterConfig": {

View File

@@ -20,6 +20,7 @@
"PortName": "COM口",
"RemoteUrl": "远程url",
"RtsEnable": "Rts",
"StreamAsync": "串口流读写",
"StopBits": "停止位"
},
"ThingsGateway.Foundation.ConverterConfig": {

View File

@@ -10,8 +10,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="$(NET9Version)" />
<PackageReference Include="TouchSocket" Version="3.1.7" />
<PackageReference Include="TouchSocket.SerialPorts" Version="3.1.7" />
<PackageReference Include="TouchSocket" Version="3.1.8" />
<PackageReference Include="TouchSocket.SerialPorts" Version="3.1.8" />
</ItemGroup>
<ItemGroup>

View File

@@ -241,87 +241,292 @@ public static class ThingsGatewayBitConverterExtension
/// <summary>
/// 根据数据类型获取实际值
/// </summary>
public static object GetDataFormBytes(this IThingsGatewayBitConverter byteConverter, IDevice device, string address, byte[] buffer, int index, DataTypeEnum dataType, int arrayLength)
public static bool GetChangedDataFormBytes(
this IThingsGatewayBitConverter byteConverter,
IDevice device,
string address,
byte[] buffer,
int index,
DataTypeEnum dataType,
int arrayLength,
object? oldValue,
out object? result)
{
switch (dataType)
{
case DataTypeEnum.Boolean:
return arrayLength > 1 ?
byteConverter.ToBoolean(buffer, index, arrayLength, device.BitReverse(address)) :
byteConverter.ToBoolean(buffer, index, device.BitReverse(address));
if (arrayLength > 1)
{
var newVal = byteConverter.ToBoolean(buffer, index, arrayLength, device.BitReverse(address));
if (oldValue is bool[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToBoolean(buffer, index, device.BitReverse(address));
if (oldValue is bool oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Byte:
return
arrayLength > 1 ?
byteConverter.ToByte(buffer, index, arrayLength) :
byteConverter.ToByte(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToByte(buffer, index, arrayLength);
if (oldValue is byte[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToByte(buffer, index);
if (oldValue is byte oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Int16:
return
arrayLength > 1 ?
byteConverter.ToInt16(buffer, index, arrayLength) :
byteConverter.ToInt16(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToInt16(buffer, index, arrayLength);
if (oldValue is short[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToInt16(buffer, index);
if (oldValue is short oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.UInt16:
return
arrayLength > 1 ?
byteConverter.ToUInt16(buffer, index, arrayLength) :
byteConverter.ToUInt16(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToUInt16(buffer, index, arrayLength);
if (oldValue is ushort[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToUInt16(buffer, index);
if (oldValue is ushort oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Int32:
return
arrayLength > 1 ?
byteConverter.ToInt32(buffer, index, arrayLength) :
byteConverter.ToInt32(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToInt32(buffer, index, arrayLength);
if (oldValue is int[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToInt32(buffer, index);
if (oldValue is int oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.UInt32:
return
arrayLength > 1 ?
byteConverter.ToUInt32(buffer, index, arrayLength) :
byteConverter.ToUInt32(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToUInt32(buffer, index, arrayLength);
if (oldValue is uint[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToUInt32(buffer, index);
if (oldValue is uint oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Int64:
return
arrayLength > 1 ?
byteConverter.ToInt64(buffer, index, arrayLength) :
byteConverter.ToInt64(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToInt64(buffer, index, arrayLength);
if (oldValue is long[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToInt64(buffer, index);
if (oldValue is long oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.UInt64:
return
arrayLength > 1 ?
byteConverter.ToUInt64(buffer, index, arrayLength) :
byteConverter.ToUInt64(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToUInt64(buffer, index, arrayLength);
if (oldValue is ulong[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToUInt64(buffer, index);
if (oldValue is ulong oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Single:
return
arrayLength > 1 ?
byteConverter.ToSingle(buffer, index, arrayLength) :
byteConverter.ToSingle(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToSingle(buffer, index, arrayLength);
if (oldValue is float[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToSingle(buffer, index);
if (oldValue is float oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.Double:
return
arrayLength > 1 ?
byteConverter.ToDouble(buffer, index, arrayLength) :
byteConverter.ToDouble(buffer, index);
if (arrayLength > 1)
{
var newVal = byteConverter.ToDouble(buffer, index, arrayLength);
if (oldValue is double[] oldArr && newVal.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
else
{
var newVal = byteConverter.ToDouble(buffer, index);
if (oldValue is double oldVal && oldVal == newVal)
{
result = oldValue;
return false;
}
result = newVal;
return true;
}
case DataTypeEnum.String:
default:
if (arrayLength > 1)
{
List<String> strings = new();
var newArr = new string[arrayLength];
for (int i = 0; i < arrayLength; i++)
{
var data = byteConverter.ToString(buffer, index + i * byteConverter.StringLength ?? 1, byteConverter.StringLength ?? 1);
strings.Add(data);
newArr[i] = byteConverter.ToString(buffer, index + i * (byteConverter.StringLength ?? 1), byteConverter.StringLength ?? 1);
}
return strings.ToArray();
if (oldValue is string[] oldArr && newArr.SequenceEqual(oldArr))
{
result = oldValue;
return false;
}
result = newArr;
return true;
}
else
{
return byteConverter.ToString(buffer, index, byteConverter.StringLength ?? 1);
var str = byteConverter.ToString(buffer, index, byteConverter.StringLength ?? 1);
if (oldValue is string oldStr && oldStr == str)
{
result = oldStr;
return false;
}
result = str;
return true;
}
}
}
#endregion
}

View File

@@ -55,6 +55,8 @@ public interface IVariable
/// </summary>
IVariableSource VariableSource { get; set; }
void SetNoChangedValue(DateTime dateTime);
/// <summary>
/// 赋值变量,返回是否成功,一般在实体内部需要做异常保存
/// </summary>

View File

@@ -8,8 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
namespace ThingsGateway.Foundation;
/// <summary>
@@ -33,9 +31,9 @@ public interface IVariableSource
string RegisterAddress { get; set; }
/// <summary>
/// TimeTick
/// IntervalTime
/// </summary>
TimeTick TimeTick { get; set; }
string IntervalTime { get; set; }
/// <summary>
/// 添加变量

View File

@@ -62,6 +62,10 @@ public class VariableClass : IVariable
/// </summary>
public IVariableSource VariableSource { get; set; }
public void SetNoChangedValue(DateTime dateTime)
{
}
/// <summary>
/// 赋值变量
/// </summary>

View File

@@ -8,8 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
namespace ThingsGateway.Foundation;
/// <summary>
@@ -28,8 +26,10 @@ public class VariableSourceClass : IVariableSource
/// <inheritdoc/>
public string RegisterAddress { get; set; }
/// <inheritdoc/>
public TimeTick TimeTick { get; set; }
/// <summary>
/// IntervalTime
/// </summary>
public string IntervalTime { get; set; }
/// <summary>
/// 已打包变量

View File

@@ -24,7 +24,7 @@ public class KeyboardShortcutsBehavior : Behavior
public KeyboardShortcutsBehavior(Diagram diagram) : base(diagram)
{
_shortcuts = new Dictionary<string, Func<Diagram, ValueTask>>(10000, new CaseInsensitiveComparer());
_shortcuts = new Dictionary<string, Func<Diagram, ValueTask>>(10, new CaseInsensitiveComparer());
SetShortcut("Delete", false, false, false, KeyboardShortcutsDefaults.DeleteSelection);
SetShortcut("g", true, false, true, KeyboardShortcutsDefaults.Grouping);

View File

@@ -11,3 +11,4 @@
global using Microsoft.AspNetCore.Components;
[assembly: BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsync(true)]

View File

@@ -4,6 +4,7 @@
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</PropertyGroup>
<ItemGroup>
@@ -26,7 +27,9 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ThingsGateway.Blazor.Diagrams.Core\ThingsGateway.Blazor.Diagrams.Core.csproj" />
<ProjectReference Include="..\ThingsGateway.Blazor.Diagrams.Core\ThingsGateway.Blazor.Diagrams.Core.csproj" />
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,143 @@
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
namespace ThingsGateway.Gateway.Application;
public class CronScheduledTask : DisposeBase, IScheduledTask
{
private int _interval10MS = 10;
private string _interval;
private readonly Func<object?, CancellationToken, Task> _taskFunc;
private readonly Action<object?, CancellationToken> _taskAction;
private readonly CancellationToken _token;
private TimerX? _timer;
private object? _state;
private ILog LogMessage;
private volatile int _isRunning = 0;
private volatile int _pendingTriggers = 0;
public CronScheduledTask(string interval, Func<object?, CancellationToken, Task> taskFunc, object? state, ILog log, CancellationToken token)
{
_interval = interval;
LogMessage = log;
_state = state;
_taskFunc = taskFunc;
_token = token;
}
public CronScheduledTask(string interval, Action<object?, CancellationToken> taskAction, object? state, ILog log, CancellationToken token)
{
_interval = interval;
LogMessage = log;
_state = state;
_taskAction = taskAction;
_token = token;
}
public void Start()
{
_timer?.Dispose();
if (_token.IsCancellationRequested) return;
if (_taskAction == null)
_timer = new TimerX(TimerCallback, _state, _interval, nameof(IScheduledTask)) { Async = true };
else
_timer = new TimerX(TimerCallbackAsync, _state, _interval, nameof(IScheduledTask)) { Async = true };
}
private async Task TimerCallbackAsync(object? state)
{
if (_token.IsCancellationRequested)
return;
Interlocked.Increment(ref _pendingTriggers);
if (Interlocked.Exchange(ref _isRunning, 1) == 1)
return;
// 减少一个触发次数
Interlocked.Decrement(ref _pendingTriggers);
try
{
await _taskFunc(state, _token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LogMessage.LogWarning(ex);
}
finally
{
Interlocked.Exchange(ref _isRunning, 0);
}
if (Interlocked.Exchange(ref _pendingTriggers, 0) >= 1)
{
if (!_token.IsCancellationRequested)
{
DelayDo();
}
}
}
private void TimerCallback(object? state)
{
if (_token.IsCancellationRequested)
return;
Interlocked.Increment(ref _pendingTriggers);
if (Interlocked.Exchange(ref _isRunning, 1) == 1)
return;
// 减少一个触发次数
Interlocked.Decrement(ref _pendingTriggers);
try
{
_taskAction(state, _token);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LogMessage.LogWarning(ex);
}
finally
{
Interlocked.Exchange(ref _isRunning, 0);
}
if (Interlocked.Exchange(ref _pendingTriggers, 0) >= 1)
{
if (!_token.IsCancellationRequested)
{
DelayDo();
}
}
}
private void DelayDo()
{
// 延迟触发下一次
if (!_token.IsCancellationRequested)
_timer?.SetNext(_interval10MS);
}
public void Stop()
{
_timer?.Dispose();
_timer = null;
}
protected override void Dispose(bool disposing)
{
Stop();
base.Dispose(disposing);
}
}

View File

@@ -23,16 +23,17 @@ public class DoTask
/// 取消令牌
/// </summary>
private CancellationTokenSource? _cancelTokenSource;
private object? _state;
public DoTask(Func<CancellationToken, ValueTask> doWork, ILog logger, string taskName = null)
public DoTask(Func<object?, CancellationToken, Task> doWork, ILog logger, object? state = null, string taskName = null)
{
DoWork = doWork; Logger = logger; TaskName = taskName;
DoWork = doWork; Logger = logger; TaskName = taskName; _state = state;
}
/// <summary>
/// 执行任务方法
/// </summary>
public Func<CancellationToken, ValueTask> DoWork { get; }
public Func<object?, CancellationToken, Task> DoWork { get; }
private ILog Logger { get; }
private Task PrivateTask { get; set; }
private string TaskName { get; }
@@ -74,7 +75,7 @@ public class DoTask
{
if (_cancelTokenSource.IsCancellationRequested)
return;
await DoWork(_cancelTokenSource.Token).ConfigureAwait(false);
await DoWork(_state, _cancelTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{

View File

@@ -0,0 +1,7 @@
namespace ThingsGateway.Gateway.Application
{
public interface IScheduledIntIntervalTask
{
int IntervalMS { get; }
}
}

View File

@@ -0,0 +1,13 @@
namespace ThingsGateway.Gateway.Application
{
public interface IScheduledTask
{
void Start();
void Stop();
}
}

View File

@@ -0,0 +1,93 @@
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
namespace ThingsGateway.Gateway.Application;
public class ScheduledAsyncTask : DisposeBase, IScheduledTask, IScheduledIntIntervalTask
{
private int _interval10MS = 10;
public int IntervalMS { get; }
private readonly Func<object?, CancellationToken, Task> _taskFunc;
private readonly CancellationToken _token;
private TimerX? _timer;
private object? _state;
private ILog LogMessage;
private volatile int _isRunning = 0;
private volatile int _pendingTriggers = 0;
public ScheduledAsyncTask(int interval, Func<object?, CancellationToken, Task> taskFunc, object? state, ILog log, CancellationToken token)
{
IntervalMS = interval;
LogMessage = log;
_state = state;
_taskFunc = taskFunc;
_token = token;
}
public void Start()
{
_timer?.Dispose();
if (!_token.IsCancellationRequested)
_timer = new TimerX(DoAsync, _state, IntervalMS, IntervalMS, nameof(IScheduledTask)) { Async = true };
}
private async Task DoAsync(object? state)
{
if (_token.IsCancellationRequested)
return;
Interlocked.Increment(ref _pendingTriggers);
if (Interlocked.Exchange(ref _isRunning, 1) == 1)
return;
// 减少一个触发次数
Interlocked.Decrement(ref _pendingTriggers);
try
{
await _taskFunc(state, _token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LogMessage.LogWarning(ex);
}
finally
{
Interlocked.Exchange(ref _isRunning, 0);
}
if (Interlocked.Exchange(ref _pendingTriggers, 0) >= 1)
{
if (!_token.IsCancellationRequested)
{
DelayDo();
}
}
}
private void DelayDo()
{
// 延迟触发下一次
if (!_token.IsCancellationRequested)
_timer?.SetNext(_interval10MS);
}
public void Stop()
{
_timer?.Dispose();
_timer = null;
}
protected override void Dispose(bool disposing)
{
Stop();
base.Dispose(disposing);
}
}

View File

@@ -0,0 +1,96 @@
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
namespace ThingsGateway.Gateway.Application;
public class ScheduledSyncTask : DisposeBase, IScheduledTask, IScheduledIntIntervalTask
{
private int _interval10MS = 10;
public int IntervalMS { get; }
private readonly Action<object?, CancellationToken> _taskAction;
private readonly CancellationToken _token;
private TimerX? _timer;
private object? _state;
private ILog LogMessage;
private volatile int _isRunning = 0;
private volatile int _pendingTriggers = 0;
public ScheduledSyncTask(int interval, Action<object?, CancellationToken> taskFunc, object? state, ILog log, CancellationToken token)
{
IntervalMS = interval;
LogMessage = log;
_state = state;
_taskAction = taskFunc;
_token = token;
}
public void Start()
{
_timer?.Dispose();
if (!_token.IsCancellationRequested)
_timer = new TimerX(TimerCallback, _state, IntervalMS, IntervalMS, nameof(IScheduledTask)) { Async = true };
}
private void TimerCallback(object? state)
{
if (_token.IsCancellationRequested)
return;
Interlocked.Increment(ref _pendingTriggers);
if (Interlocked.Exchange(ref _isRunning, 1) == 1)
return;
Do(state);
}
private void Do(object? state)
{
// 减少一个触发次数
Interlocked.Decrement(ref _pendingTriggers);
try
{
_taskAction(state, _token);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LogMessage.LogWarning(ex);
}
finally
{
Interlocked.Exchange(ref _isRunning, 0);
}
if (Interlocked.Exchange(ref _pendingTriggers, 0) >= 1)
{
if (!_token.IsCancellationRequested)
{
DelayDo();
}
}
}
private void DelayDo()
{
// 延迟触发下一次
if (!_token.IsCancellationRequested)
_timer?.SetNext(_interval10MS);
}
public void Stop()
{
_timer?.Dispose();
_timer = null;
}
protected override void Dispose(bool disposing)
{
Stop();
base.Dispose(disposing);
}
}

View File

@@ -0,0 +1,29 @@
namespace ThingsGateway.Gateway.Application;
public static class ScheduledTaskHelper
{
public static IScheduledTask GetTask(string interval, Func<object?, CancellationToken, Task> func, object? state, TouchSocket.Core.ILog log, CancellationToken cancellationToken)
{
if (int.TryParse(interval, out int intervalV))
{
var intervalMilliseconds = intervalV < 10 ? 10 : intervalV;
return new ScheduledAsyncTask(intervalMilliseconds, func, state, log, cancellationToken);
}
else
{
return new CronScheduledTask(interval, func, state, log, cancellationToken);
}
}
public static IScheduledTask GetTask(string interval, Action<object?, CancellationToken> action, object? state, TouchSocket.Core.ILog log, CancellationToken cancellationToken)
{
if (int.TryParse(interval, out int intervalV))
{
var intervalMilliseconds = intervalV < 10 ? 10 : intervalV;
return new ScheduledSyncTask(intervalMilliseconds, action, state, log, cancellationToken);
}
else
{
return new CronScheduledTask(interval, action, state, log, cancellationToken);
}
}
}

View File

@@ -41,7 +41,7 @@ public class SmartTriggerScheduler
// 否则启动执行任务
_isRunning = true;
_ = Task.Run(ExecuteLoop); // 开启异步执行循环(非阻塞)
_ = Task.Run(ExecuteLoop);
}
}

View File

@@ -0,0 +1,32 @@
namespace ThingsGateway.Gateway.Application;
public class TaskSchedulerLoop
{
private readonly List<IScheduledTask> Tasks;
public TaskSchedulerLoop(List<IScheduledTask> tasks)
{
Tasks = tasks;
}
public int Count()
{
return Tasks.Count;
}
public void Start()
{
foreach (var task in Tasks)
{
task.Start();
}
}
public void Stop()
{
foreach (var task in Tasks)
{
task.Stop();
}
}
}

View File

@@ -317,6 +317,11 @@ public class ChannelInput
/// </summary>
public virtual bool RtsEnable { get; set; }
/// <summary>
/// StreamAsync
/// </summary>
public virtual bool StreamAsync { get; set; } = false;
/// <summary>
/// 缓存超时
/// </summary>

View File

@@ -11,7 +11,6 @@
using BootstrapBlazor.Components;
using ThingsGateway.Extension.Generic;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension;
using ThingsGateway.NewLife.Threading;
@@ -96,87 +95,42 @@ public abstract class BusinessBase : DriverBase
return Task.CompletedTask;
}
/// <summary>
/// 循环任务
/// 获取任务
/// </summary>
/// <param name="cancellationToken">取消操作的令牌。</param>
/// <returns>表示异步操作结果的枚举。</returns>
internal override async ValueTask<ThreadRunReturnTypeEnum> ExecuteAsync(CancellationToken cancellationToken)
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
try
var setDeviceStatusTask = new ScheduledSyncTask(3000, SetDeviceStatus, null, LogMessage, cancellationToken);
var executeTask = ScheduledTaskHelper.GetTask(CurrentDevice.IntervalTime, ProtectedExecuteAsync, null, LogMessage, cancellationToken);
return new List<IScheduledTask>()
{
setDeviceStatusTask,
executeTask
};
}
/// <summary>
/// 间隔执行
/// </summary>
protected abstract Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken);
private void SetDeviceStatus(object? state, CancellationToken cancellationToken)
{
// 获取设备连接状态并更新设备活动时间
if (IsConnected())
{
// 如果取消操作被请求,则返回中断状态
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 如果标志为停止,则暂停执行
if (Pause)
{
// 暂停
return ThreadRunReturnTypeEnum.Continue;
}
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 获取设备连接状态并更新设备活动时间
if (IsConnected())
{
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 执行任务操作
if (TimeTick.IsTickHappen())
await ProtectedExecuteAsync(cancellationToken).ConfigureAwait(false);
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 正常返回None状态
return ThreadRunReturnTypeEnum.None;
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
catch (OperationCanceledException)
else
{
return ThreadRunReturnTypeEnum.Break;
}
catch (ObjectDisposedException)
{
return ThreadRunReturnTypeEnum.Break;
}
catch (Exception ex)
{
// 记录异常信息,并更新设备状态为异常
LogMessage?.LogError(ex, "Execute");
CurrentDevice.SetDeviceStatus(TimerX.Now, true, ex.Message);
return ThreadRunReturnTypeEnum.None;
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
}
internal override ValueTask StartAsync(CancellationToken cancellationToken)
{
TimeTick = new TimeTick(CurrentDevice.IntervalTime);
return base.StartAsync(cancellationToken);
}
private TimeTick TimeTick;
}

View File

@@ -11,7 +11,6 @@
using Mapster;
using ThingsGateway.Extension.Generic;
using ThingsGateway.NewLife;
using TouchSocket.Core;
@@ -22,9 +21,6 @@ namespace ThingsGateway.Gateway.Application;
/// </summary>
public abstract class BusinessBaseWithCacheIntervalAlarmModel<VarModel, DevModel, AlarmModel> : BusinessBaseWithCacheAlarmModel<VarModel, DevModel, AlarmModel>
{
protected TimeTick _exT2TimerTick; // 用于设备上传的时间间隔定时器
protected TimeTick _exTTimerTick; // 用于变量上传的时间间隔定时器
/// <summary>
/// 业务属性
/// </summary>
@@ -37,10 +33,6 @@ public abstract class BusinessBaseWithCacheIntervalAlarmModel<VarModel, DevModel
protected internal override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
// 初始化
_exTTimerTick = new(_businessPropertyWithCacheInterval.BusinessInterval);
_exT2TimerTick = new(_businessPropertyWithCacheInterval.BusinessInterval);
GlobalData.AlarmChangedEvent -= AlarmValueChange;
GlobalData.ReadOnlyRealAlarmIdVariables?.ForEach(a =>
{
@@ -49,8 +41,7 @@ public abstract class BusinessBaseWithCacheIntervalAlarmModel<VarModel, DevModel
GlobalData.AlarmChangedEvent += AlarmValueChange;
// 解绑全局数据的事件
GlobalData.VariableValueChangeEvent -= VariableValueChange;
GlobalData.DeviceStatusChangeEvent -= DeviceStatusChange;
// 根据业务属性的缓存是否为间隔上传来决定事件绑定
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Interval)
@@ -129,6 +120,7 @@ public abstract class BusinessBaseWithCacheIntervalAlarmModel<VarModel, DevModel
/// </summary>
protected override void Dispose(bool disposing)
{
// 解绑事件
GlobalData.AlarmChangedEvent -= AlarmValueChange;
GlobalData.VariableValueChangeEvent -= VariableValueChange;
@@ -145,69 +137,55 @@ public abstract class BusinessBaseWithCacheIntervalAlarmModel<VarModel, DevModel
/// <summary>
/// 间隔上传数据的方法
/// </summary>
protected virtual async Task IntervalInsert(CancellationToken cancellationToken)
protected void IntervalInsert(object? state, CancellationToken cancellationToken)
{
while (!DisposedValue)
if (CurrentDevice.Pause == true)
{
if (CurrentDevice.Pause == true)
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
continue;
}
// 如果业务属性的缓存为间隔上传,则根据定时器间隔执行相应操作
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (_exTTimerTick.IsTickHappen())
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
// 间隔推送全部变量
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
try
{
if (_exT2TimerTick.IsTickHappen())
{
if (CollectDevices != null)
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(DevModel).Name} data, count {CollectDevices.Count}");
// 间隔推送全部设备
foreach (var deviceRuntime in CollectDevices.Select(a => a.Value))
{
DeviceTimeInterval(deviceRuntime, deviceRuntime.Adapt<DeviceBasicData>());
}
}
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertDeviceFail);
}
}
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
return;
}
// 如果业务属性的缓存为间隔上传,则根据定时器间隔执行相应操作
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
// 间隔推送全部变量
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
try
{
if (CollectDevices != null)
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(DevModel).Name} data, count {CollectDevices.Count}");
// 间隔推送全部设备
foreach (var deviceRuntime in CollectDevices.Select(a => a.Value))
{
DeviceTimeInterval(deviceRuntime, deviceRuntime.Adapt<DeviceBasicData>());
}
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertDeviceFail);
}
}
}
/// <summary>
/// 启动前异步方法
/// </summary>
protected override Task ProtectedStartAsync(CancellationToken cancellationToken)
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
// 启动间隔上传的数据获取线程
_ = IntervalInsert(cancellationToken);
return base.ProtectedStartAsync(cancellationToken);
var list = base.ProtectedGetTasks(cancellationToken);
list.Add(ScheduledTaskHelper.GetTask(_businessPropertyWithCacheInterval.BusinessInterval, IntervalInsert, null, LogMessage, cancellationToken));
return list;
}
/// <summary>

View File

@@ -11,7 +11,6 @@
using Mapster;
using ThingsGateway.Extension.Generic;
using ThingsGateway.NewLife;
using TouchSocket.Core;
@@ -24,12 +23,6 @@ namespace ThingsGateway.Gateway.Application;
/// <typeparam name="DevModel">设备数据类型</typeparam>
public abstract class BusinessBaseWithCacheIntervalDeviceModel<VarModel, DevModel> : BusinessBaseWithCacheDeviceModel<VarModel, DevModel>
{
// 用于控制设备上传的定时器
protected TimeTick _exT2TimerTick;
// 用于控制变量上传的定时器
protected TimeTick _exTTimerTick;
/// <summary>
/// 获取具体业务属性的缓存设置。
/// </summary>
@@ -44,16 +37,6 @@ public abstract class BusinessBaseWithCacheIntervalDeviceModel<VarModel, DevMode
protected internal override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
// 初始化设备和变量上传的定时器
_exTTimerTick = new(_businessPropertyWithCacheInterval.BusinessInterval);
_exT2TimerTick = new(_businessPropertyWithCacheInterval.BusinessInterval);
// 注销全局变量值改变事件和设备状态改变事件的订阅,以防止重复订阅
GlobalData.VariableValueChangeEvent -= VariableValueChange;
GlobalData.DeviceStatusChangeEvent -= DeviceStatusChange;
// 如果不是间隔上传,则订阅全局变量值改变事件和设备状态改变事件,并触发一次事件处理
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Interval)
{
@@ -130,77 +113,59 @@ public abstract class BusinessBaseWithCacheIntervalDeviceModel<VarModel, DevMode
base.Dispose(disposing);
}
/// <summary>
/// 执行间隔插入任务的方法,用于定期上传设备和变量信息。
/// </summary>
/// <returns>异步任务</returns>
protected virtual async Task IntervalInsert(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
/// <summary>
/// 间隔上传数据的方法
/// </summary>
protected void IntervalInsert(object? state, CancellationToken cancellationToken)
{
if (CurrentDevice.Pause == true)
{
if (CurrentDevice.Pause == true)
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
continue;
}
// 如果是间隔上传,根据定时器触发事件上传设备和变量信息
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (_exTTimerTick.IsTickHappen())
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
// 上传所有变量信息
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
try
{
if (_exT2TimerTick.IsTickHappen())
{
if (CollectDevices != null)
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(DevModel).Name} data, count {CollectDevices.Count}");
// 上传所有设备信息
foreach (var deviceRuntime in CollectDevices.Select(a => a.Value))
{
DeviceTimeInterval(deviceRuntime, deviceRuntime.Adapt<DeviceBasicData>());
}
}
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertDeviceFail);
}
}
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
return;
}
// 如果业务属性的缓存为间隔上传,则根据定时器间隔执行相应操作
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
// 上传所有变量信息
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
try
{
if (CollectDevices != null)
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(DevModel).Name} data, count {CollectDevices.Count}");
// 上传所有设备信息
foreach (var deviceRuntime in CollectDevices.Select(a => a.Value))
{
DeviceTimeInterval(deviceRuntime, deviceRuntime.Adapt<DeviceBasicData>());
}
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertDeviceFail);
}
}
}
/// <summary>
/// 在开始前的保护方法,异步执行间隔插入任务。
/// </summary>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>异步任务</returns>
protected override Task ProtectedStartAsync(CancellationToken cancellationToken)
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
_ = IntervalInsert(cancellationToken);
return base.ProtectedStartAsync(cancellationToken);
var list = base.ProtectedGetTasks(cancellationToken);
list.Add(ScheduledTaskHelper.GetTask(_businessPropertyWithCacheInterval.BusinessInterval, IntervalInsert, null, LogMessage, cancellationToken));
return list;
}
/// <summary>
/// 变量状态变化时发生的虚拟方法,用于处理变量状态变化事件。
/// </summary>

View File

@@ -11,7 +11,6 @@
using Mapster;
using ThingsGateway.Extension.Generic;
using ThingsGateway.NewLife;
using TouchSocket.Core;
@@ -23,10 +22,6 @@ namespace ThingsGateway.Gateway.Application;
/// <typeparam name="VarModel">变量模型类型</typeparam>
public abstract class BusinessBaseWithCacheIntervalVariableModel<VarModel> : BusinessBaseWithCacheVariableModel<VarModel>
{
/// <summary>
/// 用于定时触发的时间间隔。
/// </summary>
protected TimeTick _exTTimerTick;
/// <summary>
/// 获取具体业务属性的缓存设置。
@@ -40,11 +35,7 @@ public abstract class BusinessBaseWithCacheIntervalVariableModel<VarModel> : Bus
protected internal override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
// 初始化定时器
_exTTimerTick = new TimeTick(_businessPropertyWithCacheInterval.BusinessInterval);
// 注册变量值变化事件处理程序
GlobalData.VariableValueChangeEvent -= VariableValueChange;
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Interval)
{
GlobalData.VariableValueChangeEvent += VariableValueChange;
@@ -91,54 +82,39 @@ public abstract class BusinessBaseWithCacheIntervalVariableModel<VarModel> : Bus
}
/// <summary>
/// 间隔插入操作,用于周期性地插入变量。
/// 间隔上传数据的方法
/// </summary>
/// <returns>表示异步操作的任务</returns>
protected virtual async Task IntervalInsert(CancellationToken cancellationToken)
protected void IntervalInsert(object? state, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
if (CurrentDevice.Pause == true)
{
if (CurrentDevice.Pause == true)
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
continue;
}
//间隔上传
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (_exTTimerTick.IsTickHappen())
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
//间隔推送全部变量
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
}
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
return;
}
// 如果业务属性的缓存为间隔上传,则根据定时器间隔执行相应操作
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Change)
{
try
{
if (LogMessage?.LogLevel <= LogLevel.Debug)
LogMessage?.LogDebug($"Interval {typeof(VarModel).Name} data, count {IdVariableRuntimes.Count}");
// 上传所有变量信息
var variableRuntimes = IdVariableRuntimes.Select(a => a.Value);
VariableTimeInterval(variableRuntimes, variableRuntimes.Adapt<List<VariableBasicData>>());
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, AppResource.IntervalInsertVariableFail);
}
}
}
/// <summary>
/// 在启动前执行的异步操作。
/// </summary>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>表示异步操作的任务</returns>
protected override Task ProtectedStartAsync(CancellationToken cancellationToken)
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
// 启动间隔插入操作
_ = IntervalInsert(cancellationToken);
return base.ProtectedStartAsync(cancellationToken);
var list = base.ProtectedGetTasks(cancellationToken);
list.Add(ScheduledTaskHelper.GetTask(_businessPropertyWithCacheInterval.BusinessInterval, IntervalInsert, null, LogMessage, cancellationToken));
return list;
}
/// <summary>
@@ -164,7 +140,7 @@ public abstract class BusinessBaseWithCacheIntervalVariableModel<VarModel> : Bus
/// </summary>
/// <param name="variableRuntime">变量运行时对象</param>
/// <param name="variable">变量数据</param>
private void VariableValueChange(VariableRuntime variableRuntime, VariableBasicData variable)
protected void VariableValueChange(VariableRuntime variableRuntime, VariableBasicData variable)
{
if (CurrentDevice.Pause == true)
return;

View File

@@ -53,7 +53,7 @@ public abstract class CollectBase : DriverBase, IRpcDriver
//预热脚本,加速编译
IdVariableRuntimes.Where(a => !string.IsNullOrWhiteSpace(a.Value.ReadExpressions))
.Select(b => b.Value.ReadExpressions).ToHashSet().ParallelForEach(script =>
.Select(b => b.Value.ReadExpressions).Distinct().ToArray().ParallelForEach(script =>
{
try
{
@@ -89,7 +89,7 @@ public abstract class CollectBase : DriverBase, IRpcDriver
{
var data = new VariableScriptRead();
data.VariableRuntime = a;
data.TimeTick = new(a.IntervalTime ?? currentDevice.IntervalTime);
data.IntervalTime = a.IntervalTime ?? currentDevice.IntervalTime;
return data;
}).ToList();
@@ -164,352 +164,245 @@ public abstract class CollectBase : DriverBase, IRpcDriver
{
return string.Empty;
}
/// <summary>
/// 循环任务
/// </summary>
/// <param name="cancellationToken">取消操作的令牌。</param>
/// <returns>表示异步操作结果的枚举。</returns>
internal override async ValueTask<ThreadRunReturnTypeEnum> ExecuteAsync(CancellationToken cancellationToken)
protected virtual bool VariableSourceReadsEnable => true;
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
try
var tasks = new List<IScheduledTask>();
var setDeviceStatusTask = new ScheduledSyncTask(3000, SetDeviceStatus, null, LogMessage, cancellationToken);
tasks.Add(setDeviceStatusTask);
var testOnline = new ScheduledAsyncTask(30000, TestOnline, null, LogMessage, cancellationToken);
tasks.Add(testOnline);
if (VariableSourceReadsEnable)
{
// 如果取消操作被请求,则返回中断状态
if (cancellationToken.IsCancellationRequested)
for (int i = 0; i < CurrentDevice.VariableSourceReads.Count; i++)
{
return ThreadRunReturnTypeEnum.Break;
}
var variableSourceRead = CurrentDevice.VariableSourceReads[i];
// 如果标志为停止,则暂停执行
if (Pause)
var executeTask = ScheduledTaskHelper.GetTask(variableSourceRead.IntervalTime, ReadVariableSource, variableSourceRead, LogMessage, cancellationToken);
tasks.Add(executeTask);
}
}
for (int i = 0; i < CurrentDevice.ReadVariableMethods.Count; i++)
{
var variableMethod = CurrentDevice.ReadVariableMethods[i];
var executeTask = ScheduledTaskHelper.GetTask(variableMethod.IntervalTime, ReadVariableMed, variableMethod, LogMessage, cancellationToken);
tasks.Add(executeTask);
}
for (int i = 0; i < CurrentDevice.VariableScriptReads.Count; i++)
{
var variableScriptRead = CurrentDevice.VariableScriptReads[i];
var executeTask = ScheduledTaskHelper.GetTask(variableScriptRead.IntervalTime, ScriptVariableRun, variableScriptRead, LogMessage, cancellationToken);
tasks.Add(executeTask);
}
return tasks;
}
private void SetDeviceStatus(object? state, CancellationToken cancellationToken)
{
if (IsConnected())
{
if (CurrentDevice.DeviceStatus == DeviceStatusEnum.OffLine)
{
// 暂停
return ThreadRunReturnTypeEnum.Continue;
if (IdVariableRuntimes.Any(a => a.Value.IsOnline))
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 获取设备连接状态并更新设备活动时间
if (IsConnected())
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now);
}
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 执行任务操作
await ProtectedExecuteAsync(cancellationToken).ConfigureAwait(false);
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 正常返回None状态
return ThreadRunReturnTypeEnum.None;
}
catch (OperationCanceledException)
else if (IsStarted)
{
return ThreadRunReturnTypeEnum.Break;
}
catch (ObjectDisposedException)
{
return ThreadRunReturnTypeEnum.Break;
}
catch (Exception ex)
{
if (cancellationToken.IsCancellationRequested)
return ThreadRunReturnTypeEnum.Break;
// 记录异常信息,并更新设备状态为异常
LogMessage?.LogError(ex, "Execute");
CurrentDevice.SetDeviceStatus(TimerX.Now, true, ex.Message);
return ThreadRunReturnTypeEnum.None;
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
}
/// <summary>
/// 执行读取等方法,如果插件不支持读取,而是自更新值的话,需重写此方法
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
{
try
{
ReadResultCount readResultCount = new();
if (cancellationToken.IsCancellationRequested)
return;
if (CollectProperties.MaxConcurrentCount > 1)
{
// 并行处理每个变量读取
await CurrentDevice.VariableSourceReads.ParallelForEachAsync(async (variableSourceRead, cancellationToken) =>
{
if (cancellationToken.IsCancellationRequested)
return;
if (await ReadVariableSource(readResultCount, variableSourceRead, cancellationToken).ConfigureAwait(false))
return;
}
, CollectProperties.MaxConcurrentCount, cancellationToken).ConfigureAwait(false);
}
else
{
for (int i = 0; i < CurrentDevice.VariableSourceReads.Count; i++)
{
if (cancellationToken.IsCancellationRequested)
return;
if (await ReadVariableSource(readResultCount, CurrentDevice.VariableSourceReads[i], cancellationToken).ConfigureAwait(false))
return;
}
}
if (CollectProperties.MaxConcurrentCount > 1)
{
// 并行处理每个方法调用
await CurrentDevice.ReadVariableMethods.ParallelForEachAsync(async (readVariableMethods, cancellationToken) =>
{
if (cancellationToken.IsCancellationRequested)
return;
if (await ReadVariableMed(readResultCount, readVariableMethods, cancellationToken).ConfigureAwait(false))
return;
}
, CollectProperties.MaxConcurrentCount, cancellationToken).ConfigureAwait(false);
}
else
{
for (int i = 0; i < CurrentDevice.ReadVariableMethods.Count; i++)
{
if (cancellationToken.IsCancellationRequested)
return;
if (await ReadVariableMed(readResultCount, CurrentDevice.ReadVariableMethods[i], cancellationToken).ConfigureAwait(false))
return;
}
}
// 如果所有方法和变量读取都成功,则清零错误计数器
if (readResultCount.deviceMethodsVariableFailedNum == 0 && readResultCount.deviceSourceVariableFailedNum == 0 && (readResultCount.deviceMethodsVariableSuccessNum != 0 || readResultCount.deviceSourceVariableSuccessNum != 0))
{
//只有成功读取一次,失败次数都会清零
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
}
finally
{
ScriptVariableRun(cancellationToken);
}
}
#region private
#region
async ValueTask<bool> ReadVariableMed(ReadResultCount readResultCount, VariableMethod readVariableMethods, CancellationToken cancellationToken)
async Task ReadVariableMed(object? state, CancellationToken cancellationToken)
{
if (state is not VariableMethod readVariableMethods) return;
if (Pause)
return true;
return;
if (cancellationToken.IsCancellationRequested)
return true;
return;
// 如果请求更新时间已到,则执行方法调用
if (readVariableMethods.CheckIfRequestAndUpdateTime())
var readErrorCount = 0;
//if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
// LogMessage?.Trace(string.Format("{0} - Executing method [{1}]", DeviceName, readVariableMethods.MethodInfo.Name));
var readResult = await InvokeMethodAsync(readVariableMethods, cancellationToken: cancellationToken).ConfigureAwait(false);
// 方法调用失败时重试一定次数
while (!readResult.IsSuccess && readErrorCount < CollectProperties.RetryCount)
{
if (Pause)
return;
if (cancellationToken.IsCancellationRequested)
return;
readErrorCount++;
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - failed - {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
//if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
// LogMessage?.Trace(string.Format("{0} - Executing method [{1}]", DeviceName, readVariableMethods.MethodInfo.Name));
readResult = await InvokeMethodAsync(readVariableMethods, cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (readResult.IsSuccess)
{
// 方法调用成功时记录日志并增加成功计数器
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - Succeeded {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.Content?.ToSystemTextJsonString()));
CurrentDevice.SetDeviceStatus(TimerX.Now, null);
}
else
{
if (cancellationToken.IsCancellationRequested)
return true;
if (cancellationToken.IsCancellationRequested)
return true;
if (await TestOnline(cancellationToken).ConfigureAwait(false))
return true;
var readErrorCount = 0;
return;
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Executing method [{1}]", DeviceName, readVariableMethods.MethodInfo.Name));
var readResult = await InvokeMethodAsync(readVariableMethods, cancellationToken: cancellationToken).ConfigureAwait(false);
// 方法调用失败时重试一定次数
while (!readResult.IsSuccess && readErrorCount < CollectProperties.RetryCount)
// 方法调用失败时记录日志并增加失败计数器,更新错误信息
if (readVariableMethods.LastErrorMessage != readResult.ErrorMessage)
{
if (Pause)
return true;
if (cancellationToken.IsCancellationRequested)
return true;
if (await TestOnline(cancellationToken).ConfigureAwait(false))
return true;
readErrorCount++;
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - failed - {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Executing method [{1}]", DeviceName, readVariableMethods.MethodInfo.Name));
readResult = await InvokeMethodAsync(readVariableMethods, cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (readResult.IsSuccess)
{
// 方法调用成功时记录日志并增加成功计数器
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - Succeeded {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.Content?.ToSystemTextJsonString()));
readResultCount.deviceMethodsVariableSuccessNum++;
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
if (!cancellationToken.IsCancellationRequested)
LogMessage?.LogWarning(readResult.Exception, string.Format(AppResource.MethodFail, DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
}
else
{
if (cancellationToken.IsCancellationRequested)
return true;
// 方法调用失败时记录日志并增加失败计数器,更新错误信息
if (readVariableMethods.LastErrorMessage != readResult.ErrorMessage)
if (!cancellationToken.IsCancellationRequested)
{
if (!cancellationToken.IsCancellationRequested)
LogMessage?.LogWarning(readResult.Exception, string.Format(AppResource.MethodFail, DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - failed - {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
}
else
{
if (!cancellationToken.IsCancellationRequested)
{
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Execute method [{1}] - failed - {2}", DeviceName, readVariableMethods.MethodInfo.Name, readResult.ErrorMessage));
}
}
readResultCount.deviceMethodsVariableFailedNum++;
readVariableMethods.LastErrorMessage = readResult.ErrorMessage;
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
readVariableMethods.LastErrorMessage = readResult.ErrorMessage;
CurrentDevice.SetDeviceStatus(TimerX.Now, null);
}
return false;
return;
}
#endregion
#region
async ValueTask<bool> ReadVariableSource(ReadResultCount readResultCount, VariableSourceRead? variableSourceRead, CancellationToken cancellationToken)
async Task ReadVariableSource(object? state, CancellationToken cancellationToken)
{
if (state is not VariableSourceRead variableSourceRead) return;
if (Pause)
return true;
return;
if (cancellationToken.IsCancellationRequested)
return true;
// 如果请求更新时间已到,则执行变量读取
if (variableSourceRead.CheckIfRequestAndUpdateTime())
return;
var readErrorCount = 0;
//if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
// LogMessage?.Trace(string.Format("{0} - Collecting [{1} - {2}]", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length));
var readResult = await ReadSourceAsync(variableSourceRead, cancellationToken).ConfigureAwait(false);
// 读取失败时重试一定次数
while (!readResult.IsSuccess && readErrorCount < CollectProperties.RetryCount)
{
if (cancellationToken.IsCancellationRequested)
return true;
if (Pause)
return true;
if (await TestOnline(cancellationToken).ConfigureAwait(false))
return true;
var readErrorCount = 0;
return;
if (cancellationToken.IsCancellationRequested)
return;
readErrorCount++;
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collecting [{1} - {2}]", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length));
var readResult = await ReadSourceAsync(variableSourceRead, cancellationToken).ConfigureAwait(false);
// 读取失败时重试一定次数
while (!readResult.IsSuccess && readErrorCount < CollectProperties.RetryCount)
{
if (Pause)
return true;
if (cancellationToken.IsCancellationRequested)
return true;
if (await TestOnline(cancellationToken).ConfigureAwait(false))
return true;
readErrorCount++;
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] failed - {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] failed - {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collecting [{1} - {2}]", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length));
readResult = await ReadSourceAsync(variableSourceRead, cancellationToken).ConfigureAwait(false);
}
if (readResult.IsSuccess)
{
// 读取成功时记录日志并增加成功计数器
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] data succeeded {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.Content?.ToHexString(' ')));
readResultCount.deviceSourceVariableSuccessNum++;
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
else
{
{
if (cancellationToken.IsCancellationRequested)
return true;
// 读取失败时记录日志并增加失败计数器,更新错误信息并清除变量状态
if (variableSourceRead.LastErrorMessage != readResult.ErrorMessage)
{
if (!cancellationToken.IsCancellationRequested)
LogMessage?.LogWarning(readResult.Exception, string.Format(AppResource.CollectFail, DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
}
else
{
if (!cancellationToken.IsCancellationRequested)
{
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] data failed - {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
}
}
readResultCount.deviceSourceVariableFailedNum++;
variableSourceRead.LastErrorMessage = readResult.ErrorMessage;
CurrentDevice.SetDeviceStatus(TimerX.Now, true, readResult.ErrorMessage);
var time = DateTime.Now;
variableSourceRead.VariableRuntimes.ForEach(a => a.SetValue(null, time, isOnline: false));
}
}
//if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
// LogMessage?.Trace(string.Format("{0} - Collecting [{1} - {2}]", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length));
readResult = await ReadSourceAsync(variableSourceRead, cancellationToken).ConfigureAwait(false);
}
return false;
}
#endregion
#endregion
protected virtual ValueTask<bool> TestOnline(CancellationToken cancellationToken)
{
return ValueTask.FromResult(false);
}
protected void ScriptVariableRun(CancellationToken cancellationToken)
{
DateTime dateTime = TimerX.Now;
//特殊地址变量
for (int i = 0; i < CurrentDevice.VariableScriptReads.Count; i++)
if (readResult.IsSuccess)
{
// 读取成功时记录日志并增加成功计数器
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] data succeeded {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.Content?.ToHexString(' ')));
CurrentDevice.SetDeviceStatus(TimerX.Now, null);
}
else
{
if (cancellationToken.IsCancellationRequested)
return;
if (CurrentDevice.VariableScriptReads[i].CheckIfRequestAndUpdateTime())
// 读取失败时记录日志并增加失败计数器,更新错误信息并清除变量状态
if (variableSourceRead.LastErrorMessage != readResult.ErrorMessage)
{
var variableRuntime = CurrentDevice.VariableScriptReads[i].VariableRuntime;
if (variableRuntime.RegisterAddress.Equals(nameof(DeviceRuntime.DeviceStatus), StringComparison.OrdinalIgnoreCase))
{
variableRuntime.SetValue(variableRuntime.DeviceRuntime.DeviceStatus, dateTime);
}
else if (variableRuntime.RegisterAddress.Equals("ScriptRead", StringComparison.OrdinalIgnoreCase))
{
variableRuntime.SetValue(variableRuntime.Value, dateTime);
}
if (!cancellationToken.IsCancellationRequested)
LogMessage?.LogWarning(readResult.Exception, string.Format(AppResource.CollectFail, DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
}
else
{
if (!cancellationToken.IsCancellationRequested)
{
if (LogMessage?.LogLevel <= TouchSocket.Core.LogLevel.Trace)
LogMessage?.Trace(string.Format("{0} - Collection [{1} - {2}] data failed - {3}", DeviceName, variableSourceRead?.RegisterAddress, variableSourceRead?.Length, readResult.ErrorMessage));
}
}
variableSourceRead.LastErrorMessage = readResult.ErrorMessage;
CurrentDevice.SetDeviceStatus(TimerX.Now, null, readResult.ErrorMessage);
var time = DateTime.Now;
variableSourceRead.VariableRuntimes.ForEach(a => a.SetValue(null, time, isOnline: false));
}
}
#endregion
#endregion
protected virtual Task TestOnline(object? state, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
protected void ScriptVariableRun(object? state, CancellationToken cancellationToken)
{
DateTime dateTime = TimerX.Now;
if (state is not VariableScriptRead variableScriptRead) return;
//特殊地址变量
if (cancellationToken.IsCancellationRequested)
return;
{
var variableRuntime = variableScriptRead.VariableRuntime;
if (variableRuntime.RegisterAddress.Equals(nameof(DeviceRuntime.DeviceStatus), StringComparison.OrdinalIgnoreCase))
{
variableRuntime.SetValue(variableRuntime.DeviceRuntime.DeviceStatus, dateTime);
}
else if (variableRuntime.RegisterAddress.Equals("ScriptRead", StringComparison.OrdinalIgnoreCase))
{
variableRuntime.SetValue(variableRuntime.Value, dateTime);
}
}
}
/// <summary>
/// 连读打包,返回实际通讯包信息<see cref="VariableSourceRead"/>
/// <br></br>每个驱动打包方法不一样,所以需要实现这个接口
@@ -539,14 +432,6 @@ public abstract class CollectBase : DriverBase, IRpcDriver
}
private sealed class ReadResultCount
{
public int deviceMethodsVariableFailedNum = 0;
public int deviceMethodsVariableSuccessNum = 0;
public int deviceSourceVariableFailedNum = 0;
public int deviceSourceVariableSuccessNum = 0;
}
#region
/// <summary>
@@ -590,11 +475,11 @@ public abstract class CollectBase : DriverBase, IRpcDriver
try
{
// 使用并发方式遍历写入信息列表,并进行异步写入操作
await writeInfoLists
var list = writeInfoLists
.Where(a => !results.Any(b => b.Key == a.Key.Name))
.ToDictionary(item => item.Key, item => item.Value).ParallelForEachAsync(async (writeInfo, cancellationToken) =>
.ToDictionary(item => item.Key, item => item.Value).ToArray();
// 使用并发方式遍历写入信息列表,并进行异步写入操作
await list.ParallelForEachAsync(async (writeInfo, cancellationToken) =>
{
try
{

View File

@@ -68,10 +68,8 @@ public abstract class CollectFoundationBase : CollectBase
}
protected override async ValueTask<bool> TestOnline(CancellationToken cancellationToken)
protected override async Task TestOnline(object? state, CancellationToken cancellationToken)
{
//设备无法连接时
// 检查协议是否为空,如果为空则抛出异常
if (FoundationDevice != null)
{
if (FoundationDevice.OnLine == false)
@@ -79,7 +77,6 @@ public abstract class CollectFoundationBase : CollectBase
Exception exception = null;
try
{
await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
if (!cancellationToken.IsCancellationRequested)
{
await FoundationDevice.Channel.ConnectAsync(FoundationDevice.Channel.ChannelOptions.ConnectTimeout, cancellationToken).ConfigureAwait(false);
@@ -91,7 +88,7 @@ public abstract class CollectFoundationBase : CollectBase
}
if (cancellationToken.IsCancellationRequested)
{
return true;
return;
}
if (FoundationDevice.OnLine == false && exception != null)
{
@@ -103,7 +100,7 @@ public abstract class CollectFoundationBase : CollectBase
LogMessage?.LogWarning(exception, string.Format(AppResource.CollectFail, DeviceName, item?.RegisterAddress, item?.Length, exception.Message));
}
item.LastErrorMessage = exception.Message;
CurrentDevice.SetDeviceStatus(TimerX.Now, true, exception.Message);
CurrentDevice.SetDeviceStatus(TimerX.Now, null, exception.Message);
var time = DateTime.Now;
item.VariableRuntimes.ForEach(a => a.SetValue(null, time, isOnline: false));
}
@@ -115,18 +112,17 @@ public abstract class CollectFoundationBase : CollectBase
LogMessage?.LogWarning(exception, string.Format(AppResource.MethodFail, DeviceName, item.MethodInfo.Name, exception.Message));
}
item.LastErrorMessage = exception.Message;
CurrentDevice.SetDeviceStatus(TimerX.Now, true, exception.Message);
CurrentDevice.SetDeviceStatus(TimerX.Now, null, exception.Message);
var time = DateTime.Now;
item.Variable.SetValue(null, time, isOnline: false);
}
await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
return true;
return;
}
}
}
return false;
return;
}
@@ -144,9 +140,6 @@ public abstract class CollectFoundationBase : CollectBase
// 从协议读取数据
var read = await FoundationDevice.ReadAsync(variableSourceRead.RegisterAddress, variableSourceRead.Length, cancellationToken).ConfigureAwait(false);
// 增加变量源的读取次数
Interlocked.Increment(ref variableSourceRead.ReadCount);
// 如果读取成功且有有效内容,则解析结构化内容
if (read.IsSuccess)
{
@@ -177,9 +170,9 @@ public abstract class CollectFoundationBase : CollectBase
// 创建用于存储操作结果的并发字典
ConcurrentDictionary<string, OperResult> operResults = new();
var list = writeInfoLists.ToArray();
// 使用并发方式遍历写入信息列表,并进行异步写入操作
await writeInfoLists.ParallelForEachAsync(async (writeInfo, cancellationToken) =>
await list.ParallelForEachAsync(async (writeInfo, cancellationToken) =>
{
try
{
@@ -216,12 +209,4 @@ public abstract class CollectFoundationBase : CollectBase
}
}
private sealed class ReadResultCount
{
public int deviceMethodsVariableFailedNum = 0;
public int deviceMethodsVariableSuccessNum = 0;
public int deviceSourceVariableFailedNum = 0;
public int deviceSourceVariableSuccessNum = 0;
}
}

View File

@@ -40,12 +40,6 @@ public abstract class CollectPropertyBase : DriverPropertyBase
/// </summary>
public abstract class CollectPropertyRetryBase : CollectPropertyBase
{
/// <summary>
/// 离线后恢复运行的间隔时间
/// </summary>
[DynamicProperty]
public override int ReIntervalTime { get; set; } = 0;
/// <summary>
/// 失败重试次数默认3
/// </summary>

View File

@@ -11,6 +11,7 @@
using BootstrapBlazor.Components;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text;
@@ -20,6 +21,8 @@ using ThingsGateway.Razor;
using TouchSocket.Core;
using LogLevel = TouchSocket.Core.LogLevel;
namespace ThingsGateway.Gateway.Application;
/// <summary>
@@ -124,6 +127,11 @@ public abstract class DriverBase : DisposableObject, IDriver
if (CurrentDevice == null) return;
LogMessage?.LogInformation(pause == true ? string.Format(AppResource.DeviceTaskPause, DeviceName) : string.Format(AppResource.DeviceTaskContinue, DeviceName));
CurrentDevice.Pause = pause;
if (CurrentDevice.Pause)
TaskSchedulerLoop.Stop();
else
TaskSchedulerLoop.Start();
}
}
@@ -233,11 +241,11 @@ public abstract class DriverBase : DisposableObject, IDriver
}
/// <summary>
/// 在循环任务开始之前
/// 在任务开始之前
/// </summary>
/// <param name="cancellationToken">取消操作的令牌。</param>
/// <returns>表示异步操作的任务。</returns>
internal virtual async ValueTask StartAsync(CancellationToken cancellationToken)
internal virtual async Task StartAsync(CancellationToken cancellationToken)
{
// 如果已经执行过初始化,则直接返回
if (IsStarted)
@@ -274,7 +282,7 @@ public abstract class DriverBase : DisposableObject, IDriver
}
// 设置设备状态为当前时间
CurrentDevice.SetDeviceStatus(TimerX.Now);
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
catch (Exception ex)
{
@@ -289,15 +297,36 @@ public abstract class DriverBase : DisposableObject, IDriver
}
}
protected internal TaskSchedulerLoop TaskSchedulerLoop;
/// <summary>
/// 循环任务
/// 获取任务
/// </summary>
/// <param name="cancellationToken">取消操作的令牌。</param>
/// <returns>表示异步操作结果的枚举。</returns>
internal abstract ValueTask<ThreadRunReturnTypeEnum> ExecuteAsync(CancellationToken cancellationToken);
internal virtual TaskSchedulerLoop GetTasks(CancellationToken cancellationToken)
{
TaskSchedulerLoop = new(ProtectedGetTasks(cancellationToken));
//var count = GlobalData.ChannelThreadManage.DeviceThreadManages.Select(a => a.Value.TaskCount).Sum();
//ThreadPool.GetMinThreads(out var wt, out var io);
//if (wt < count + 128)
//{
// wt = count + 256;
// ThreadPool.SetMinThreads(wt, io);
// GlobalData.GatewayMonitorHostedService.Logger.LogInformation($"set min threads count {wt}, device tasks count {count}");
//}
return TaskSchedulerLoop;
}
protected abstract List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken);
/// <summary>
/// 已停止循环任务,释放插件
/// 已停止任务,释放插件
/// </summary>
internal virtual void Stop()
{
@@ -423,12 +452,5 @@ public abstract class DriverBase : DisposableObject, IDriver
/// </summary>
public abstract Task AfterVariablesChangedAsync(CancellationToken cancellationToken);
/// <summary>
/// 间隔执行
/// </summary>
protected abstract ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken);
#endregion
}

View File

@@ -137,6 +137,13 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[AutoGenerateColumn(Visible = false, Filterable = true, Sortable = true)]
public override bool RtsEnable { get; set; }
/// <summary>
/// StreamAsync
/// </summary>
[SugarColumn(ColumnDescription = "StreamAsync", IsNullable = true)]
[AutoGenerateColumn(Visible = false, Filterable = true, Sortable = true)]
public override bool StreamAsync { get; set; } = false;
/// <summary>
/// 缓存超时
/// </summary>
@@ -203,7 +210,7 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[SugarColumn(ColumnDescription = "创建时间", IsOnlyIgnoreUpdate = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Visible = false, IsVisibleWhenAdd = false, IsVisibleWhenEdit = false)]
public virtual DateTime? CreateTime { get; set; }
public virtual DateTime CreateTime { get; set; }
/// <summary>
/// 创建人
@@ -237,7 +244,7 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[SugarColumn(ColumnDescription = "更新时间", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Visible = false, IsVisibleWhenAdd = false, IsVisibleWhenEdit = false)]
public virtual DateTime? UpdateTime { get; set; }
public virtual DateTime UpdateTime { get; set; }
/// <summary>
/// 更新人
@@ -245,7 +252,7 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[SugarColumn(ColumnDescription = "更新人", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual string? UpdateUser { get; set; }
public virtual string UpdateUser { get; set; }
/// <summary>
/// 修改者Id
@@ -253,7 +260,7 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[SugarColumn(ColumnDescription = "修改者Id", IsOnlyIgnoreInsert = true, IsNullable = true)]
[IgnoreExcel]
[AutoGenerateColumn(Ignore = true)]
public virtual long? UpdateUserId { get; set; }
public virtual long UpdateUserId { get; set; }
/// <summary>
/// 排序码
@@ -261,7 +268,7 @@ public class Channel : ChannelOptionsBase, IPrimaryIdEntity, IBaseDataEntity, IB
[SugarColumn(ColumnDescription = "排序码", IsNullable = true)]
[AutoGenerateColumn(Visible = false, DefaultSort = true, Sortable = true, DefaultSortOrder = SortOrder.Asc)]
[IgnoreExcel]
public int? SortCode { get; set; }
public int SortCode { get; set; }
/// <summary>
/// 导入验证专用

Some files were not shown because too many files have changed in this diff Show More