Compare commits

...

15 Commits

Author SHA1 Message Date
Diego
4e9f02b48c 更新依赖包 2025-06-24 09:03:34 +08:00
2248356998 qq.com
9ae7602cb4 配置最大连接数 2025-06-24 00:09:07 +08:00
2248356998 qq.com
aa8aa36aef build: 10.8.19
fix: s7 复用地址对象导致读取异常
feat: 规则引擎node添加内部异常捕获
feat: 变量增加属性: 写入后再次读取检查值是否一致
2025-06-23 21:21:27 +08:00
2248356998 qq.com
0174f7c6f2 更新依赖 2025-06-22 23:05:12 +08:00
2248356998 qq.com
df9e7d6ff1 10.8.17 2025-06-22 21:11:37 +08:00
Diego
b40ca920d3 fix: 变量自动刷新运行态 2025-06-20 16:58:45 +08:00
Diego
5a4b0a0e93 修改插件过期提示 2025-06-20 14:43:13 +08:00
Diego
a879edd68b 10.8.12 2025-06-20 13:52:42 +08:00
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
183 changed files with 2318 additions and 1840 deletions

View File

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

View File

@@ -2,7 +2,7 @@
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace BlazorSetParametersAsyncGenerator;
namespace Microsoft.AspNetCore.Components;
[Generator]
public partial class SetParametersAsyncGenerator : ISourceGenerator
@@ -11,7 +11,7 @@ public partial class SetParametersAsyncGenerator : ISourceGenerator
private string m_DoNotGenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
internal sealed class DoNotGenerateSetParametersAsyncAttribute : Attribute
@@ -25,7 +25,7 @@ public partial class SetParametersAsyncGenerator : ISourceGenerator
private string m_GenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
internal sealed class GenerateSetParametersAsyncAttribute : Attribute
@@ -40,7 +40,7 @@ public partial class SetParametersAsyncGenerator : ISourceGenerator
private string m_GlobalGenerateSetParametersAsyncAttribute = """
using System;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
internal sealed class GlobalGenerateSetParametersAsyncAttribute : Attribute
@@ -445,8 +445,8 @@ namespace {namespaceName}
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");
var positiveAttributeSymbol = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Components.GenerateSetParametersAsyncAttribute");
var negativeAttributeSymbol = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Components.DoNotGenerateSetParametersAsyncAttribute");
// loop over the candidate methods, and keep the ones that are actually annotated
@@ -454,7 +454,7 @@ namespace {namespaceName}
var assemblyAttributes = compilation.Assembly.GetAttributes();
var enableAttr = assemblyAttributes.FirstOrDefault(attr =>
attr.AttributeClass?.ToDisplayString() == "BlazorSetParametersAsyncGenerator.GlobalGenerateSetParametersAsyncAttribute");
attr.AttributeClass?.ToDisplayString() == "Microsoft.AspNetCore.Components.GlobalGenerateSetParametersAsyncAttribute");
var globalEnable = false;
if (enableAttr != null)

View File

@@ -3,7 +3,7 @@ using Microsoft.CodeAnalysis.Text;
using System.Text;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
internal static class SourceGeneratorContextExtension
{

View File

@@ -1,7 +1,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
internal static class StringExtension
{

View File

@@ -1,6 +1,6 @@
using Microsoft.CodeAnalysis;
namespace BlazorSetParametersAsyncGenerator
namespace Microsoft.AspNetCore.Components
{
public static class TypeSymbolExtension
{

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

@@ -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

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
@@ -18,7 +18,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Rougamo.Fody" Version="5.0.0" />
<PackageReference Include="Rougamo.Fody" Version="5.0.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" />
@@ -41,12 +41,20 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
<None Include="..\README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ThingsGateway.DB\ThingsGateway.DB.csproj" />
</ItemGroup>
<!--<Target Name="Mapster" AfterTargets="AfterBuild">
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet tool restore" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster extension -o MapsterGenerator -a &quot;$(TargetDir)$(ProjectName).dll&quot;" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster mapper -o MapsterGenerator -a &quot;$(TargetDir)$(ProjectName).dll&quot;" />
</Target>-->
</Project>

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

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<ItemGroup>
<ProjectReference Include="..\ThingsGateway.Admin.Application\ThingsGateway.Admin.Application.csproj" />
@@ -30,9 +30,15 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
<None Include="..\README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="..\..\Version.props" />
<PropertyGroup>

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
@@ -11,19 +11,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BootstrapBlazor.TableExport" Version="9.2.5" />
<PackageReference Include="BootstrapBlazor.TableExport" Version="9.2.6" />
</ItemGroup>
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
<None Include="..\README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />
<!--<ProjectReference Include="..\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />-->
<!--<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" />-->
</ItemGroup>

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

@@ -15,6 +15,7 @@ using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Log;
namespace ThingsGateway.Logging;
@@ -33,7 +34,7 @@ public sealed class DatabaseLoggerProvider : ILoggerProvider, ISupportExternalSc
/// <summary>
/// 日志消息队列(线程安全)
/// </summary>
private readonly BlockingCollection<LogMessage> _logMessageQueue = new(12000);
private readonly BlockingCollection<LogMessage> _logMessageQueue = new(20000);
/// <summary>
/// 日志作用域提供器
@@ -135,7 +136,10 @@ public sealed class DatabaseLoggerProvider : ILoggerProvider, ISupportExternalSc
{
try
{
_logMessageQueue.Add(logMsg);
if (!_logMessageQueue.TryAdd(logMsg, 5000))
{
XTrace.Log.Warn($"{nameof(DatabaseLoggerProvider)} queue add fail");
}
return;
}
catch (InvalidOperationException) { }
@@ -160,8 +164,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

@@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Log;
namespace ThingsGateway.Logging;
@@ -32,7 +33,7 @@ public sealed class FileLoggerProvider : ILoggerProvider, ISupportExternalScope
/// <summary>
/// 日志消息队列(线程安全)
/// </summary>
private readonly BlockingCollection<LogMessage> _logMessageQueue = new(12000);
private readonly BlockingCollection<LogMessage> _logMessageQueue = new(20000);
/// <summary>
/// 日志作用域提供器
@@ -90,8 +91,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>
@@ -171,8 +171,10 @@ public sealed class FileLoggerProvider : ILoggerProvider, ISupportExternalScope
{
try
{
_logMessageQueue.Add(logMsg);
return;
if (!_logMessageQueue.TryAdd(logMsg, 5000))
{
XTrace.Log.Warn($"{nameof(DatabaseLoggerProvider)} queue add fail");
}
}
catch (InvalidOperationException) { }
catch { }

View File

@@ -46,6 +46,8 @@ public static class ObjectMapperServiceCollectionExtensions
// 获取全局映射配置
var config = TypeAdapterConfig.GlobalSettings;
//config.Compiler = exp => exp.CompileFast();
// 扫描所有继承 IRegister 接口的对象映射配置
if (assemblies?.Length > 0) config.Scan(assemblies);

View File

@@ -76,7 +76,7 @@ internal sealed partial class SchedulerFactory : ISchedulerFactory
/// <summary>
/// 作业持久化记录消息队列(线程安全)
/// </summary>
private readonly BlockingCollection<PersistenceContext> _persistenceMessageQueue = new(12000);
private readonly BlockingCollection<PersistenceContext> _persistenceMessageQueue = new(20000);
/// <summary>
/// 不受控的作业 Id 集合
@@ -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

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0;</TargetFrameworks>
@@ -36,6 +36,7 @@
<ItemGroup>
<PackageReference Include="Ben.Demystifier" Version="0.4.1" />
<!--<PackageReference Include="FastExpressionCompiler" Version="5.3.0" />-->
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.5.4" />
@@ -61,8 +62,8 @@
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
</Project>

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

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net462;netstandard2.0;net6.0;net6.0-windows;net8.0;net8.0-windows;</TargetFrameworks>
@@ -16,8 +16,8 @@
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net462' or '$(TargetFramework)'=='net5.0-windows' or '$(TargetFramework)'=='net6.0-windows' or '$(TargetFramework)'=='net7.0-windows' or '$(TargetFramework)'=='net8.0-windows'">

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

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0;</TargetFrameworks>

View File

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

View File

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

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,14 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<Version>$(SourceGeneratorVersion)</Version>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</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>
@@ -22,8 +20,8 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
<None Include="..\README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
@@ -31,10 +29,10 @@
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' != 'Debug' ">
<!--<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>-->
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />

View File

@@ -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,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
@@ -13,8 +13,8 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
<None Include="..\README.zh-CN.md" Pack="true" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.md" Pack="false" PackagePath="\" />
<None Remove="..\..\..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
@@ -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" />

View File

@@ -1,12 +1,13 @@
<Project>
<PropertyGroup>
<PluginVersion>10.8.1</PluginVersion>
<ProPluginVersion>10.8.1</ProPluginVersion>
<AuthenticationVersion>2.8.0</AuthenticationVersion>
<SourceGeneratorVersion>10.8.0</SourceGeneratorVersion>
<PluginVersion>10.8.20</PluginVersion>
<ProPluginVersion>10.8.20</ProPluginVersion>
<AuthenticationVersion>2.8.4</AuthenticationVersion>
<SourceGeneratorVersion>10.8.6</SourceGeneratorVersion>
<NET8Version>8.0.17</NET8Version>
<NET9Version>9.0.6</NET9Version>
<SatelliteResourceLanguages>zh-Hans;en-US</SatelliteResourceLanguages>
</PropertyGroup>
<PropertyGroup>
@@ -41,7 +42,7 @@
</PropertyGroup>
<ItemGroup>
<None Include="$(SolutionDir)Directory.Build.props" Pack="true" PackagePath="\" />
<None Include="$(MSBuildThisFileDirectory)Directory.Build.props" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup>

View File

@@ -4,6 +4,6 @@
</PropertyGroup>
<ItemGroup>
<None Include="$(SolutionDir)Foundation.props" Pack="true" PackagePath="\" />
<None Include="$(MSBuildThisFileDirectory)Foundation.props" Pack="true" PackagePath="\" />
</ItemGroup>
</Project>

View File

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

View File

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

View File

@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\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" />-->
<!--<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />-->
<ProjectReference Include="..\..\Admin\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />
<ProjectReference Include="..\ThingsGateway.Foundation\ThingsGateway.Foundation.csproj" />
</ItemGroup>
@@ -22,8 +22,10 @@
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

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

View File

@@ -85,6 +85,7 @@ public static class ChannelOptionsExtensions
channelOptions.ThrowIfNull(nameof(IChannelOptions));
var channelType = channelOptions.ChannelType;
channelType.ThrowIfNull(nameof(ChannelTypeEnum));
config.SetMaxCount(channelOptions.MaxClientCount);
switch (channelType)
{
case ChannelTypeEnum.TcpClient:

View File

@@ -509,18 +509,11 @@ public abstract class DeviceBase : DisposableObject, IDevice
}
/// <inheritdoc/>
protected virtual async ValueTask<MessageBase> SendThenReturnMessageBaseAsync(ISendMessage command, IClientChannel clientChannel = default, CancellationToken cancellationToken = default)
protected virtual ValueTask<MessageBase> SendThenReturnMessageBaseAsync(ISendMessage command, IClientChannel clientChannel = default, CancellationToken cancellationToken = default)
{
try
{
return await GetResponsedDataAsync(command, clientChannel, Timeout, cancellationToken).ConfigureAwait(false);
return GetResponsedDataAsync(command, clientChannel, Timeout, cancellationToken);
}
catch (Exception ex)
{
return new(ex);
}
}
/// <summary>
@@ -549,7 +542,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);
@@ -996,4 +989,6 @@ public abstract class DeviceBase : DisposableObject, IDevice
}
return a => { };
}
public abstract ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default);
}

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

@@ -466,4 +466,5 @@ public interface IDevice : IDisposable
/// <param name="channel">通道</param>
/// <param name="deviceLog">单独设备日志</param>
void InitChannel(IChannel channel, ILog? deviceLog = null);
ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default);
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Foundation.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="$(SolutionDir)Version.props" />
<Import Project="..\..\Foundation.props" />
<Import Project="..\..\PackNuget.props" />
<Import Project="..\..\Version.props" />
<PropertyGroup>
<Description>工业设备通讯协议-基础类库</Description>
@@ -10,8 +10,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="$(NET9Version)" />
<PackageReference Include="TouchSocket" Version="3.1.8" />
<PackageReference Include="TouchSocket.SerialPorts" Version="3.1.8" />
<PackageReference Include="TouchSocket" Version="3.1.10" />
<PackageReference Include="TouchSocket.SerialPorts" Version="3.1.10" />
</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,14 @@ public interface IVariableSource
string RegisterAddress { get; set; }
/// <summary>
/// TimeTick
/// 变量地址
/// </summary>
TimeTick TimeTick { get; set; }
object AddressObject { get; set; }
/// <summary>
/// IntervalTime
/// </summary>
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,14 +26,18 @@ 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>
/// 已打包变量
/// </summary>
public IEnumerable<IVariable> VariableRuntimes => _variableRuntimes;
public object AddressObject { get; set; }
/// <inheritdoc/>
public virtual void AddVariable(IVariable variable)
{

View File

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
@@ -8,8 +8,8 @@
<ItemGroup>
<None Remove="$(SolutionDir)..\README.md" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" />
<None Remove="..\..\..\README.md" />
<None Remove="..\..\..\README.zh-CN.md" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="README.zh-CN.md" Pack="true" PackagePath="\" />

View File

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

View File

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
@@ -9,8 +9,8 @@
<ItemGroup>
<None Remove="$(SolutionDir)..\README.md" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" />
<None Remove="..\..\..\README.md" />
<None Remove="..\..\..\README.zh-CN.md" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="README.zh-CN.md" Pack="true" PackagePath="\" />

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,41 @@
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();
}
}
public void Add(IScheduledTask task)
{
Tasks.Add(task);
}
public void Remove(IScheduledTask task)
{
Tasks.Remove(task);
}
}

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

@@ -435,8 +435,10 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
try
{
if (_memoryVarModelsQueue.TryDequeue(out var cacheDBItem))
while (_memoryVarModelsQueue.TryDequeue(out var cacheDBItem))
{
if (cancellationToken.IsCancellationRequested)
break;
var list = cacheDBItem.Value;
var data = list.ChunkBetter(_businessPropertyWithCache.SplitSize);
foreach (var item in data)

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

@@ -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();
@@ -127,6 +127,24 @@ public abstract class CollectBase : DriverBase, IRpcDriver
LogMessage?.LogWarning(ex, string.Format(AppResource.GetMethodError, ex.Message));
}
if (VariableTasks.Count > 0)
{
foreach (var item in VariableTasks)
{
item.Stop();
TaskSchedulerLoop.Remove(item);
}
VariableTasks = AddVariableTask(cancellationToken);
foreach (var item in VariableTasks)
{
TaskSchedulerLoop.Add(item);
item.Start();
}
}
// 根据标签获取方法信息的局部函数
List<VariableMethod> GetMethod(IEnumerable<VariableRuntime> tag)
{
@@ -164,352 +182,259 @@ 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 List<IScheduledTask> VariableTasks = new List<IScheduledTask>();
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
try
{
// 如果取消操作被请求,则返回中断状态
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
var tasks = new List<IScheduledTask>();
// 如果标志为停止,则暂停执行
if (Pause)
{
// 暂停
return ThreadRunReturnTypeEnum.Continue;
}
var setDeviceStatusTask = new ScheduledSyncTask(10000, SetDeviceStatus, null, LogMessage, cancellationToken);
tasks.Add(setDeviceStatusTask);
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
var testOnline = new ScheduledAsyncTask(30000, TestOnline, null, LogMessage, cancellationToken);
tasks.Add(testOnline);
// 获取设备连接状态并更新设备活动时间
if (IsConnected())
{
CurrentDevice.SetDeviceStatus(TimerX.Now);
}
VariableTasks = AddVariableTask(cancellationToken);
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
tasks.AddRange(VariableTasks);
return tasks;
// 执行任务操作
await ProtectedExecuteAsync(cancellationToken).ConfigureAwait(false);
// 再次检查取消操作是否被请求
if (cancellationToken.IsCancellationRequested)
{
return ThreadRunReturnTypeEnum.Break;
}
// 正常返回None状态
return ThreadRunReturnTypeEnum.None;
}
catch (OperationCanceledException)
{
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;
}
}
/// <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)
protected List<IScheduledTask> AddVariableTask(CancellationToken cancellationToken)
{
List<IScheduledTask> variableTasks = new();
if (VariableSourceReadsEnable)
{
for (int i = 0; i < CurrentDevice.VariableSourceReads.Count; i++)
{
// 并行处理每个变量读取
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);
var variableSourceRead = CurrentDevice.VariableSourceReads[i];
var executeTask = ScheduledTaskHelper.GetTask(variableSourceRead.IntervalTime, ReadVariableSource, variableSourceRead, LogMessage, cancellationToken);
variableTasks.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);
variableTasks.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);
variableTasks.Add(executeTask);
}
return variableTasks;
}
private void SetDeviceStatus(object? state, CancellationToken cancellationToken)
{
if (IsConnected())
{
if (CurrentDevice.DeviceStatus == DeviceStatusEnum.OffLine)
{
if (IdVariableRuntimes.Any(a => a.Value.IsOnline))
CurrentDevice.SetDeviceStatus(TimerX.Now, 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);
if (IdVariableRuntimes.All(a => !a.Value.IsOnline))
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
}
finally
else if (IsStarted)
{
ScriptVariableRun(cancellationToken);
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
}
#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;
await ReadWriteLock.ReaderLockAsync(cancellationToken).ConfigureAwait(false);
//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>每个驱动打包方法不一样,所以需要实现这个接口
@@ -537,14 +462,39 @@ public abstract class CollectBase : DriverBase, IRpcDriver
{
throw new NotImplementedException();
}
private sealed class ReadResultCount
protected async Task Check(Dictionary<VariableRuntime, JToken> writeInfoLists, ConcurrentDictionary<string, OperResult> operResults, CancellationToken cancellationToken)
{
public int deviceMethodsVariableFailedNum = 0;
public int deviceMethodsVariableSuccessNum = 0;
public int deviceSourceVariableFailedNum = 0;
public int deviceSourceVariableSuccessNum = 0;
if (VariableSourceReadsEnable)
{
// 如果成功,每个变量都读取一次最新值,再次比较写入值
var successfulWriteNames = operResults.Where(a => a.Value.IsSuccess).Select(a => a.Key).ToHashSet();
var groups = writeInfoLists.Select(a => a.Key).Where(a => a.RpcWriteCheck && a.ProtectType != ProtectTypeEnum.WriteOnly && successfulWriteNames.Contains(a.Name) && a.VariableSource != null).GroupBy(a => a.VariableSource as VariableSourceRead).Where(a => a.Key != null).ToList();
await groups.ParallelForEachAsync(async (varRead, token) =>
{
var result = await ReadSourceAsync(varRead.Key, token).ConfigureAwait(false);
if (result.IsSuccess)
{
foreach (var item in varRead)
{
if (!item.Value.Equals(writeInfoLists[item].ToObject(item.Value?.GetType())))
{
// 如果写入值与读取值不同,则更新操作结果为失败
operResults[item.Name] = new OperResult($"The write value is inconsistent with the read value, Write value: {writeInfoLists[item].ToObject(item.Value?.GetType())}, read value: {item.Value}");
}
}
}
else
{
foreach (var item in varRead)
{
// 如果写入值与读取值不同,则更新操作结果为失败
operResults[item.Name] = new OperResult($"Reading and rechecking resulted in an error: {result.ErrorMessage}", result.Exception);
}
}
}, cancellationToken).ConfigureAwait(false);
}
}
#region

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;
}
@@ -137,15 +133,12 @@ public abstract class CollectFoundationBase : CollectBase
{
try
{
await ReadWriteLock.ReaderLockAsync(cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
return new(new OperationCanceledException());
// 从协议读取数据
var read = await FoundationDevice.ReadAsync(variableSourceRead.RegisterAddress, variableSourceRead.Length, cancellationToken).ConfigureAwait(false);
// 增加变量源的读取次数
Interlocked.Increment(ref variableSourceRead.ReadCount);
// 从协议读取数据
var read = await FoundationDevice.ReadAsync(variableSourceRead.AddressObject, cancellationToken).ConfigureAwait(false);
// 如果读取成功且有有效内容,则解析结构化内容
if (read.IsSuccess)
@@ -208,6 +201,8 @@ public abstract class CollectFoundationBase : CollectBase
}
}, CollectProperties.MaxConcurrentCount, cancellationToken).ConfigureAwait(false);
await Check(writeInfoLists, operResults, cancellationToken).ConfigureAwait(false);
// 返回包含操作结果的字典
return new Dictionary<string, OperResult>(operResults);
}
@@ -216,12 +211,5 @@ 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()
{
@@ -370,6 +399,7 @@ public abstract class DriverBase : DisposableObject, IDriver
stringBuilder.Append(" ");
if (expireTime.HasValue && (DateTime.Now - expireTime.Value).TotalHours > -72)
{
stringBuilder.Append(',');
stringBuilder.Append(Localizer["ExpireTime", expireTime.Value.ToString("yyyy-MM-dd HH")]);
}
@@ -423,12 +453,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

@@ -30,9 +30,6 @@ namespace ThingsGateway.Gateway.Application;
[SugarIndex("unique_deviceid_variable_name", nameof(Variable.Name), OrderByType.Asc, nameof(Variable.DeviceId), OrderByType.Asc, true)]
public class Variable : BaseDataEntity, IValidatableObject
{
/// <summary>
/// 导入验证专用
/// </summary>
@@ -68,6 +65,8 @@ public class Variable : BaseDataEntity, IValidatableObject
private bool lLAlarmEnable;
private bool lAlarmEnable;
private bool customAlarmEnable;
private bool businessGroupUpdateTrigger = true;
private bool rpcWriteCheck;
private object _value;
private string name;
@@ -143,6 +142,20 @@ public class Variable : BaseDataEntity, IValidatableObject
[AutoGenerateColumn(Visible = true, Filterable = true, Sortable = true, Order = 1)]
public virtual string BusinessGroup { get => businessGroup; set => businessGroup = value; }
/// <summary>
/// 分组上传触发变量
/// </summary>
[SugarColumn(ColumnDescription = "分组上传触发变量", IsNullable = true)]
[AutoGenerateColumn(Visible = true, Filterable = true, Sortable = true, Order = 1)]
public virtual bool BusinessGroupUpdateTrigger { get => businessGroupUpdateTrigger; set => businessGroupUpdateTrigger = value; }
/// <summary>
/// 写入后再次读取检查值是否一致
/// </summary>
[SugarColumn(ColumnDescription = "写入后再次读取检查值是否一致", IsNullable = true)]
[AutoGenerateColumn(Visible = true, Filterable = true, Sortable = true, Order = 1)]
public virtual bool RpcWriteCheck { get => rpcWriteCheck; set => rpcWriteCheck = value; }
/// <summary>
/// 描述
/// </summary>

View File

@@ -52,17 +52,7 @@
"RulesId": "Name"
},
"ThingsGateway.Management.Authentication": {
"AuthName": "AuthName",
"Authorized": "Authorized",
"ExpireTime": "ExpireTime",
"Password": "Password",
"Register": "Register",
"RegisterStatus": "RegisterStatus",
"Unauthorized": "Unauthorized",
"Unregister": "Unregister",
"UUID": "UUID"
},
"ThingsGateway.Management.AutoUpdateController": {
"AutoUpdateController": "AutoUpdate",
"Update": "Update"
@@ -298,11 +288,9 @@
},
"ThingsGateway.Gateway.Application.CollectPropertyBase": {
"ConcurrentCount": "ConcurrentCount",
"ReIntervalTime": "ReIntervalTime",
"RetryCount": "RetryCount"
},
"ThingsGateway.Gateway.Application.CollectPropertyRetryBase": {
"ReIntervalTime": "ReIntervalTime",
"RetryCount": "RetryCount"
},
"ThingsGateway.Gateway.Application.ControlController": {
@@ -375,7 +363,7 @@
"ThingsGateway.Gateway.Application.DriverBase": {
"Authorized": "Authorized",
"ExpireTime": "ExpireTime",
"ExpireTime": "ExpireTime {0}",
"Unauthorized": "Unauthorized"
},
"ThingsGateway.Gateway.Application.ExportString": {
@@ -450,6 +438,8 @@
"BoolOpenAlarmText": "BoolOpenAlarmText",
"BoolOpenRestrainExpressions": "BoolOpenRestrainExpressions",
"BusinessGroup": "BusinessGroup",
"BusinessGroupUpdateTrigger": "BusinessGroupUpdateTrigger",
"RpcWriteCheck": "RpcWriteCheck",
"ClearVariable": "Clear Variable",
"CollectGroup": "CollectGroup",
"CopyVariable": "Copy Variable",
@@ -458,7 +448,7 @@
"CustomAlarmText": "CustomAlarmText",
"CustomRestrainExpressions": "CustomRestrainExpressions",
"DataType": "DataType",
"DeleteVariable": "Copy Variable",
"DeleteVariable": "Delete Variable",
"Description": "Description",
"DeviceId": "CollectionDevice",
"DeviceId.MinValue": "{0} cannot be empty",

View File

@@ -50,17 +50,7 @@
"LogConsole": "日志",
"RulesId": "名称"
},
"ThingsGateway.Management.Authentication": {
"AuthName": "公司名称",
"Authorized": "已授权",
"ExpireTime": "过期时间",
"Password": "注册码",
"Register": "注册",
"RegisterStatus": "注册状态",
"Unauthorized": "未授权",
"Unregister": "取消注册",
"UUID": "唯一编码"
},
"ThingsGateway.Management.AutoUpdateController": {
"AutoUpdateController": "程序更新",
"Update": "更新"
@@ -297,11 +287,9 @@
},
"ThingsGateway.Gateway.Application.CollectPropertyBase": {
"ConcurrentCount": "最大并发数量",
"ReIntervalTime": "离线恢复时间",
"RetryCount": "失败重试次数"
},
"ThingsGateway.Gateway.Application.CollectPropertyRetryBase": {
"ReIntervalTime": "离线恢复时间",
"RetryCount": "失败重试次数"
},
"ThingsGateway.Gateway.Application.ControlController": {
@@ -376,7 +364,7 @@
"ThingsGateway.Gateway.Application.DriverBase": {
"Authorized": "已授权",
"ExpireTime": "过期时间",
"ExpireTime": "过期时间 {0}",
"Unauthorized": "未授权"
},
"ThingsGateway.Gateway.Application.ExportString": {
@@ -451,6 +439,8 @@
"BoolOpenAlarmText": "布尔开报警文本",
"BoolOpenRestrainExpressions": "布尔开报警约束",
"BusinessGroup": "业务组",
"BusinessGroupUpdateTrigger": "分组上传触发",
"RpcWriteCheck": "写入后再次读取检查值是否一致",
"ClearVariable": "清空变量",
"CollectGroup": "采集组",
"CopyVariable": "复制变量",

View File

@@ -101,6 +101,9 @@ public class VariableBasicData
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public string BusinessGroup => VariableRuntime.BusinessGroup;
/// <inheritdoc cref="Variable.BusinessGroupUpdateTrigger"/>
public bool BusinessGroupUpdateTrigger => VariableRuntime.BusinessGroupUpdateTrigger;
/// <inheritdoc cref="VariableRuntime.DeviceName"/>
public string DeviceName => VariableRuntime.DeviceName;

View File

@@ -8,8 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
using TouchSocket.Core;
namespace ThingsGateway.Gateway.Application;
@@ -19,16 +17,14 @@ namespace ThingsGateway.Gateway.Application;
/// </summary>
public class VariableMethod
{
/// <summary>
/// 间隔时间实现
/// </summary>
private readonly TimeTick _timeTick;
public readonly string IntervalTime;
private object?[]? OS;
public VariableMethod(Method method, VariableRuntime variable, string delay)
{
_timeTick = new TimeTick(delay);
IntervalTime = delay;
MethodInfo = method;
Variable = variable;
variable.VariableMethod = this;
@@ -49,12 +45,6 @@ public class VariableMethod
/// </summary>
public VariableRuntime Variable { get; }
/// <summary>
/// 检测是否达到读取间隔
/// </summary>
/// <returns></returns>
public bool CheckIfRequestAndUpdateTime() => _timeTick.IsTickHappen();
/// <summary>
/// 执行方法
/// </summary>

View File

@@ -102,6 +102,17 @@ public partial class VariableRuntime : Variable, IVariable, IDisposable
return new();
}
/// <summary>
/// 设置变量值与时间/质量戳
/// </summary>
/// <param name="dateTime"></param>
public void SetNoChangedValue(DateTime dateTime)
{
DateTime time = dateTime != default ? dateTime : DateTime.Now;
CollectTime = time;
GlobalData.VariableCollectChange(this);
}
private void Set(object data, DateTime dateTime)
{
DateTime time = dateTime != default ? dateTime : DateTime.Now;
@@ -159,7 +170,6 @@ public partial class VariableRuntime : Variable, IVariable, IDisposable
GlobalData.VariableCollectChange(this);
}
public void Init(DeviceRuntime deviceRuntime)
{

View File

@@ -8,8 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
namespace ThingsGateway.Gateway.Application;
/// <summary>
@@ -17,28 +15,13 @@ namespace ThingsGateway.Gateway.Application;
/// </summary>
public class VariableScriptRead
{
public long ReadCount { get; set; }
/// <summary>
/// 间隔时间实现
/// </summary>
public TimeTick TimeTick { get; set; }
public string IntervalTime { get; set; }
/// <summary>
/// 需分配的变量列表
/// </summary>
public VariableRuntime VariableRuntime;
/// <summary>
/// 检测是否达到读取间隔
/// </summary>
/// <returns></returns>
public bool CheckIfRequestAndUpdateTime()
{
var result = TimeTick.IsTickHappen();
if (result)
{
ReadCount++;
}
return result;
}
}

View File

@@ -8,8 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
namespace ThingsGateway.Gateway.Application;
/// <summary>
@@ -17,10 +15,6 @@ namespace ThingsGateway.Gateway.Application;
/// </summary>
public class VariableSourceRead : IVariableSource
{
/// <summary>
/// 读取次数
/// </summary>
public ulong ReadCount;
private List<IVariable> _variableRuntimes = new List<IVariable>();
@@ -38,11 +32,9 @@ public class VariableSourceRead : IVariableSource
/// 读取地址
/// </summary>
public string RegisterAddress { get; set; }
public object AddressObject { get; set; }
/// <summary>
/// 间隔时间实现
/// </summary>
public TimeTick TimeTick { get; set; }
public string IntervalTime { get; set; }
/// <summary>
/// 需分配的变量列表
@@ -66,17 +58,4 @@ public class VariableSourceRead : IVariableSource
}
/// <summary>
/// 检测是否达到读取间隔
/// </summary>
/// <returns></returns>
public bool CheckIfRequestAndUpdateTime()
{
var result = TimeTick.IsTickHappen();
if (result)
{
ReadCount++;
}
return result;
}
}

View File

@@ -15,11 +15,8 @@ namespace ThingsGateway.Gateway.Application;
public sealed class ChannelThreadOptions : IConfigurableOptions
{
public int MinCycleInterval { get; set; } = 10;
public int MaxCycleInterval { get; set; } = 200;
public int CheckInterval { get; set; } = 1800000;
public int MaxChannelCount { get; set; } = 1000;
public int MaxDeviceCount { get; set; } = 1000;
public int MaxVariableCount { get; set; } = 1000000;

View File

@@ -30,60 +30,6 @@ namespace ThingsGateway.Gateway.Application;
internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
{
#region
/// <summary>
/// 线程等待间隔时间
/// </summary>
public static volatile int CycleInterval = ManageHelper.ChannelThreadOptions.MaxCycleInterval;
static DeviceThreadManage()
{
Task.Factory.StartNew(async () => await SetCycleInterval().ConfigureAwait(false), TaskCreationOptions.LongRunning);
}
private static async Task SetCycleInterval()
{
var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!;
var hardwareJob = GlobalData.HardwareJob;
List<float> cpus = new();
while (!appLifetime.ApplicationStopping.IsCancellationRequested)
{
try
{
if (hardwareJob?.HardwareInfo?.MachineInfo?.CpuRate == null) continue;
cpus.Add((float)(hardwareJob.HardwareInfo.MachineInfo.CpuRate * 100));
if (cpus.Count == 1 || cpus.Count > 5)
{
var avg = cpus.Average();
cpus.RemoveAt(0);
//Console.WriteLine($"CPU平均值{avg}");
if (avg > 80)
{
CycleInterval = Math.Max(CycleInterval, (int)(ManageHelper.ChannelThreadOptions.MaxCycleInterval * avg / 100));
}
else if (avg < 50)
{
CycleInterval = Math.Min(CycleInterval, ManageHelper.ChannelThreadOptions.MinCycleInterval);
}
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
NewLife.Log.XTrace.WriteException(ex);
}
finally
{
await Task.Delay(30000, appLifetime?.ApplicationStopping ?? default).ConfigureAwait(false);
}
}
}
#endregion
Microsoft.Extensions.Logging.ILogger? _logger;
/// <summary>
@@ -207,8 +153,9 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
/// <summary>
/// 任务
/// </summary>
internal ConcurrentDictionary<long, DoTask> DriverTasks { get; set; } = new();
internal ConcurrentDictionary<long, TaskSchedulerLoop> DriverTasks { get; } = new();
public int TaskCount => DriverTasks.Count;
/// <summary>
/// 取消令箭列表
/// </summary>
@@ -385,14 +332,10 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
}
}
// 初始化业务线程
var driverTask = new DoTask(t => DoWork(driver, IsCollectChannel, t), driver.LogMessage, null);
DriverTasks.TryAdd(driver.DeviceId, driverTask);
token.Register(driver.Stop);
driverTask.Start(token);
_ = Task.Factory.StartNew((state) => DriverStart(state, token), driver, token);
}).ConfigureAwait(false);
@@ -460,28 +403,35 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
try
{
ConcurrentList<VariableRuntime> saveVariableRuntimes = new();
await deviceIds.ParallelForEachAsync(async (deviceId, cancellationToken) =>
{
// 查找具有指定设备ID的驱动程序对象
if (!Drivers.TryRemove(deviceId, out var driver)) return;
if (!DriverTasks.TryRemove(deviceId, out var task)) return;
deviceIds.ParallelForEach((deviceId) =>
{
// 查找具有指定设备ID的驱动程序对象
if (Drivers.TryRemove(deviceId, out var driver))
{
if (IsCollectChannel == true)
{
saveVariableRuntimes.AddRange(driver.IdVariableRuntimes.Where(a => a.Value.SaveValue && !a.Value.DynamicVariable).Select(a => a.Value));
}
}
if (IsCollectChannel == true)
{
saveVariableRuntimes.AddRange(driver.IdVariableRuntimes.Where(a => a.Value.SaveValue && !a.Value.DynamicVariable).Select(a => a.Value));
}
// 取消驱动程序的操作
if (CancellationTokenSources.TryRemove(deviceId, out var token))
{
if (token != null)
{
token.Cancel();
token.Dispose();
}
}
await task.StopAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
if (DriverTasks.TryRemove(deviceId, out var task))
{
task.Stop();
}
// 取消驱动程序的操作
if (CancellationTokenSources.TryRemove(deviceId, out var token))
{
if (token != null)
{
token.Cancel();
token.Dispose();
}
}
});
await Task.Delay(100).ConfigureAwait(false);
@@ -532,52 +482,23 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
return driver;
}
private static async ValueTask DoWork(DriverBase driver, bool? isCollectChannel, CancellationToken token)
private async Task DriverStart(object? state, CancellationToken token)
{
try
{
if (state is not DriverBase driver) return;
// 只有当驱动成功初始化后才执行操作
if (driver.IsInitSuccess)
{
if (!driver.IsStarted)
await driver.StartAsync(token).ConfigureAwait(false); // 调用驱动的启动前异步方法,如果已经执行,会直接返回
await driver.StartAsync(token).ConfigureAwait(false);
var result = await driver.ExecuteAsync(token).ConfigureAwait(false); // 执行驱动的异步执行操作
var driverTask = driver.GetTasks(token); // 执行驱动的异步执行操作
DriverTasks.TryAdd(driver.DeviceId, driverTask);
driverTask.Start();
// 根据执行结果进行不同的处理
if (result == ThreadRunReturnTypeEnum.None)
{
// 如果驱动处于离线状态且为采集驱动,则根据配置的间隔时间进行延迟
if (driver.CurrentDevice.DeviceStatus == DeviceStatusEnum.OffLine && isCollectChannel == true)
{
var collectBase = (CollectBase)driver;
if (collectBase.CollectProperties.ReIntervalTime > 0)
{
await Task.Delay(Math.Max(Math.Min(collectBase.CollectProperties.ReIntervalTime, ManageHelper.ChannelThreadOptions.CheckInterval / 2) - CycleInterval, 3000), token).ConfigureAwait(false);
}
else
{
await Task.Delay(CycleInterval, token).ConfigureAwait(false);
}
}
else
{
await Task.Delay(CycleInterval, token).ConfigureAwait(false);
}
}
else if (result == ThreadRunReturnTypeEnum.Continue)
{
await Task.Delay(1000, token).ConfigureAwait(false); // 如果执行结果为继续,则延迟一段较短的时间后再继续执行
}
else if (result == ThreadRunReturnTypeEnum.Break && token.IsCancellationRequested)
{
return;
}
}
else
{
await Task.Delay(60000, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -815,10 +736,14 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
{
try
{
//检测设备线程假死
await Task.Delay(ManageHelper.ChannelThreadOptions.CheckInterval, cancellationToken).ConfigureAwait(false);
if (Disposed) return;
var num = Drivers.Count;
foreach (var driver in Drivers.Select(a => a.Value).ToList())
{

View File

@@ -21,6 +21,7 @@ public interface IDeviceThreadManage : IAsyncDisposable
string LogPath { get; }
IChannelThreadManage ChannelThreadManage { get; }
IChannel? Channel { get; }
int TaskCount { get; }
Task SetLogAsync(LogLevel? logLevel = null, bool upDataBase = true);
Task RestartDeviceAsync(DeviceRuntime deviceRuntime, bool deleteCache);

View File

@@ -21,11 +21,11 @@ namespace ThingsGateway.Gateway.Application;
/// </summary>
internal sealed class GatewayMonitorHostedService : BackgroundService, IGatewayMonitorHostedService
{
private readonly ILogger _logger;
public ILogger Logger { get; }
/// <inheritdoc cref="AlarmHostedService"/>
public GatewayMonitorHostedService(ILogger<GatewayMonitorHostedService> logger, IStringLocalizer<GatewayMonitorHostedService> localizer, IChannelThreadManage channelThreadManage)
{
_logger = logger;
Logger = logger;
Localizer = localizer;
ChannelThreadManage = channelThreadManage;
}
@@ -67,7 +67,7 @@ internal sealed class GatewayMonitorHostedService : BackgroundService, IGatewayM
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Init Channel");
Logger.LogWarning(ex, "Init Channel");
}
}
@@ -80,7 +80,7 @@ internal sealed class GatewayMonitorHostedService : BackgroundService, IGatewayM
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Start error");
Logger.LogWarning(ex, "Start error");
}

View File

@@ -9,9 +9,11 @@
// ------------------------------------------------------------------------------
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ThingsGateway.Gateway.Application;
public interface IGatewayMonitorHostedService : IHostedService
{
public ILogger Logger { get; }
}

View File

@@ -134,11 +134,7 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
/// <summary>
/// 主站
/// </summary>
/// <param name="tcpDmtpService">服务</param>
/// <param name="syncInterval">同步间隔</param>
/// <param name="log">log</param>
/// <param name="stoppingToken">取消任务的 CancellationToken</param>
private static async ValueTask DoMasterWork(TcpDmtpService tcpDmtpService, int syncInterval, ILog log, CancellationToken stoppingToken)
private async Task DoMasterWork(object? state, CancellationToken stoppingToken)
{
// 延迟一段时间,避免过于频繁地执行任务
await Task.Delay(500, stoppingToken).ConfigureAwait(false);
@@ -155,7 +151,7 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
try
{
if (tcpDmtpService.Clients.Count != 0)
if (TcpDmtpService.Clients.Count != 0)
{
online = true;
}
@@ -164,12 +160,12 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
{
var deviceRunTimes = GlobalData.ReadOnlyIdDevices.Where(a => a.Value.IsCollect == true).Select(a => a.Value).Adapt<List<DeviceDataWithValue>>();
foreach (var item in tcpDmtpService.Clients)
foreach (var item in TcpDmtpService.Clients)
{
// 将 GlobalData.CollectDevices 和 GlobalData.Variables 同步到从站
await item.GetDmtpRpcActor().InvokeAsync(
nameof(ReverseCallbackServer.UpData), null, waitInvoke, deviceRunTimes).ConfigureAwait(false);
log?.LogTrace($"{item.GetIPPort()} Update StandbyStation data success");
LogMessage?.LogTrace($"{item.GetIPPort()} Update StandbyStation data success");
}
}
@@ -177,9 +173,9 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
catch (Exception ex)
{
// 输出警告日志,指示同步数据到从站时发生错误
log?.LogWarning(ex, "Synchronize data to standby site error");
LogMessage?.LogWarning(ex, "Synchronize data to standby site error");
}
await Task.Delay(syncInterval, stoppingToken).ConfigureAwait(false);
await Task.Delay(RedundancyOptions.SyncInterval, stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -189,17 +185,14 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
}
catch (Exception ex)
{
log?.LogWarning(ex, "Execute");
LogMessage?.LogWarning(ex, "Execute");
}
}
/// <summary>
/// 从站
/// </summary>
/// <param name="tcpDmtpClient">服务</param>
/// <param name="redundancy">冗余配置</param>
/// <param name="stoppingToken">取消任务的 CancellationToken</param>
private async ValueTask DoSlaveWork(TcpDmtpClient tcpDmtpClient, RedundancyOptions redundancy, CancellationToken stoppingToken)
private async Task DoSlaveWork(object? state, CancellationToken stoppingToken)
{
// 延迟一段时间,避免过于频繁地执行任务
await Task.Delay(5000, stoppingToken).ConfigureAwait(false);
@@ -216,31 +209,31 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
try
{
await tcpDmtpClient.TryConnectAsync().ConfigureAwait(false);
await TcpDmtpClient.TryConnectAsync().ConfigureAwait(false);
{
// 初始化读取错误计数器
var readErrorCount = 0;
// 当读取错误次数小于最大错误计数时循环执行
while (readErrorCount < redundancy.MaxErrorCount)
while (readErrorCount < RedundancyOptions.MaxErrorCount)
{
try
{
// 发送 Ping 请求以检查设备是否在线,超时时间为 10000 毫秒
online = await tcpDmtpClient.PingAsync(10000).ConfigureAwait(false);
online = await TcpDmtpClient.PingAsync(10000).ConfigureAwait(false);
if (online)
break;
else
{
readErrorCount++;
await Task.Delay(redundancy.SyncInterval, stoppingToken).ConfigureAwait(false);
await Task.Delay(RedundancyOptions.SyncInterval, stoppingToken).ConfigureAwait(false);
}
}
catch
{
// 捕获异常,增加读取错误计数器
readErrorCount++;
await Task.Delay(redundancy.SyncInterval, stoppingToken).ConfigureAwait(false);
await Task.Delay(RedundancyOptions.SyncInterval, stoppingToken).ConfigureAwait(false);
}
}
}
@@ -255,7 +248,7 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
else
{
// 如果设备在线
LogMessage?.LogTrace($"Ping ActiveStation {redundancy.MasterUri} success");
LogMessage?.LogTrace($"Ping ActiveStation {RedundancyOptions.MasterUri} success");
await StandbyAsync().ConfigureAwait(false);
}
}
@@ -350,12 +343,11 @@ internal sealed class RedundancyHostedService : BackgroundService, IRedundancyHo
{
if (RedundancyOptions.IsMaster)
{
RedundancyTask = new DoTask(a => DoMasterWork(TcpDmtpService, RedundancyOptions.SyncInterval, LogMessage, a), LogMessage); // 创建新的任务
RedundancyTask = new DoTask(DoMasterWork, LogMessage); // 创建新的任务
}
else
{
RedundancyTask = new DoTask(a => DoSlaveWork(TcpDmtpClient, RedundancyOptions, a), LogMessage); // 创建新的任务
RedundancyTask = new DoTask(DoSlaveWork, LogMessage); // 创建新的任务
}
RedundancyTask?.Start(default); // 启动任务

View File

@@ -35,7 +35,7 @@ internal sealed class RpcService : IRpcService
public RpcService(IStringLocalizer<RpcService> localizer)
{
Localizer = localizer;
Task.Factory.StartNew(async () => await RpcLogInsertAsync().ConfigureAwait(false), TaskCreationOptions.LongRunning);
Task.Factory.StartNew(RpcLogInsertAsync, TaskCreationOptions.LongRunning);
_rpcLogOptions = App.GetOptions<RpcLogOptions>();
}

View File

@@ -104,12 +104,21 @@ public class ExecuteScriptNode : TextNode, IActuatorNode, IExexcuteExpressionsBa
}
}
Task<NodeOutput> IActuatorNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
Task<OperResult<NodeOutput>> IActuatorNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
{
Logger?.Trace($"Execute script");
var exexcuteExpressions = CSharpScriptEngineExtension.Do<IExexcuteExpressions>(Text);
exexcuteExpressions.Logger = Logger;
return exexcuteExpressions.ExecuteAsync(input, cancellationToken);
try
{
Logger?.Trace($"Execute script");
var exexcuteExpressions = CSharpScriptEngineExtension.Do<IExexcuteExpressions>(Text);
exexcuteExpressions.Logger = Logger;
return exexcuteExpressions.ExecuteAsync(input, cancellationToken);
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
return Task.FromResult(new OperResult<NodeOutput>(ex));
}
}

View File

@@ -12,22 +12,32 @@ public class VariableRpcNode : VariableNode, IActuatorNode
public VariableRpcNode(string id, Point? position = null) : base(id, position)
{ Title = "VariableRpcNode"; }
async Task<NodeOutput> IActuatorNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
async Task<OperResult<NodeOutput>> IActuatorNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
{
if ((!DeviceText.IsNullOrWhiteSpace()) && GlobalData.ReadOnlyDevices.TryGetValue(DeviceText, out var device))
try
{
if (device.ReadOnlyVariableRuntimes.TryGetValue(Text, out var value))
if ((!DeviceText.IsNullOrWhiteSpace()) && GlobalData.ReadOnlyDevices.TryGetValue(DeviceText, out var device))
{
var data = await value.RpcAsync(input.JToken.ToString(), $"RulesEngine: {RulesEngineName}", cancellationToken).ConfigureAwait(false);
if (data.IsSuccess)
Logger?.Trace($" VariableRpcNode - VariableName {Text} : execute success");
else
Logger?.Warning($" VariableRpcNode - VariableName {Text} : {data.ErrorMessage}");
return new NodeOutput() { Value = data };
if (device.ReadOnlyVariableRuntimes.TryGetValue(Text, out var value))
{
var data = await value.RpcAsync(input.JToken.ToString(), $"RulesEngine: {RulesEngineName}", cancellationToken).ConfigureAwait(false);
if (data.IsSuccess)
Logger?.Trace($" VariableRpcNode - VariableName {Text} : execute success");
else
Logger?.Warning($" VariableRpcNode - VariableName {Text} : {data.ErrorMessage}");
return new OperResult<NodeOutput>() { Content = new NodeOutput() { Value = data } };
}
}
Logger?.Warning($" VariableRpcNode - VariableName {Text} : not found");
return new OperResult<NodeOutput>() { Content = new NodeOutput() { } };
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
return new OperResult<NodeOutput>(ex);
}
Logger?.Warning($" VariableRpcNode - VariableName {Text} : not found");
return new NodeOutput() { };
}

View File

@@ -16,12 +16,21 @@ public class DataNode : TextNode, IExpressionNode
}
Task<NodeOutput> IExpressionNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
Task<OperResult<NodeOutput>> IExpressionNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
{
var value = Text.GetExpressionsResult(input.Value, Logger);
NodeOutput nodeOutput = new();
nodeOutput.Value = value;
Logger?.Trace($"Data result: {nodeOutput.JToken?.ToString(Newtonsoft.Json.Formatting.Indented)}");
return Task.FromResult(nodeOutput);
try
{
var value = Text.GetExpressionsResult(input.Value, Logger);
NodeOutput nodeOutput = new();
nodeOutput.Value = value;
Logger?.Trace($"Data result: {nodeOutput.JToken?.ToString(Newtonsoft.Json.Formatting.Indented)}");
return Task.FromResult(new OperResult<NodeOutput>() { Content = nodeOutput });
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
return Task.FromResult(new OperResult<NodeOutput>(ex));
}
}
}

View File

@@ -10,11 +10,20 @@ public class DelayNode : NumberNode, IExpressionNode
{
public DelayNode(string id, Point? position = null) : base(id, position) { Title = "DelayNode"; Placeholder = "DelayNode.Placeholder"; }
async Task<NodeOutput> IExpressionNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
async Task<OperResult<NodeOutput>> IExpressionNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
{
Logger?.Trace($"Delay {Number} ms");
await Task.Delay(Number ?? 0, cancellationToken).ConfigureAwait(false);
return new NodeOutput();
try
{
Logger?.Trace($"Delay {Number} ms");
await Task.Delay(Number ?? 0, cancellationToken).ConfigureAwait(false);
return new OperResult<NodeOutput>() { Content = new NodeOutput() };
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
return new OperResult<NodeOutput>(ex);
}
}
}

View File

@@ -13,16 +13,16 @@ public interface IConditionNode : INode
public interface IExpressionNode : INode
{
public Task<NodeOutput> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
public Task<OperResult<NodeOutput>> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
}
public interface IActuatorNode : INode
{
public Task<NodeOutput> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
public Task<OperResult<NodeOutput>> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
}
public interface ITriggerNode : INode
{
public Task StartAsync(Func<NodeOutput, Task> func);
public Task StartAsync(Func<NodeOutput, CancellationToken, Task> func, CancellationToken cancellationToken);
}
public interface IExexcuteExpressionsBase
{
@@ -30,6 +30,6 @@ public interface IExexcuteExpressionsBase
public interface IExexcuteExpressions : IExexcuteExpressionsBase
{
public TouchSocket.Core.ILog Logger { get; set; }
Task<NodeOutput> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
Task<OperResult<NodeOutput>> ExecuteAsync(NodeInput input, CancellationToken cancellationToken);
}

View File

@@ -13,8 +13,8 @@ public class AlarmChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
public AlarmChangedTriggerNode(string id, Point? position = null) : base(id, position) { Title = "AlarmChangedTriggerNode"; }
private Func<NodeOutput, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, Task> func)
private Func<NodeOutput, CancellationToken, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, CancellationToken, Task> func, CancellationToken cancellationToken)
{
Func = func;
FuncDict.TryAdd(this, func);
@@ -43,12 +43,12 @@ public class AlarmChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
public static ConcurrentDictionary<string, ConcurrentDictionary<string, ConcurrentList<AlarmChangedTriggerNode>>> AlarmChangedTriggerNodeDict = new();
public static ConcurrentDictionary<AlarmChangedTriggerNode, Func<NodeOutput, Task>> FuncDict = new();
public static ConcurrentDictionary<AlarmChangedTriggerNode, Func<NodeOutput, CancellationToken, Task>> FuncDict = new();
public static BlockingCollection<AlarmVariable> AlarmVariables = new();
static AlarmChangedTriggerNode()
{
_ = RunAsync();
Task.Factory.StartNew(RunAsync);
GlobalData.AlarmChangedEvent -= AlarmHostedService_OnAlarmChanged;
GlobalData.ReadOnlyRealAlarmIdVariables?.ForEach(a =>
{
@@ -88,7 +88,7 @@ public class AlarmChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
if (FuncDict.TryGetValue(item, out var func))
{
item.Logger?.Trace($"Alarm changed: {item.Text}");
await func.Invoke(new NodeOutput() { Value = alarmVariable }).ConfigureAwait(false);
await func.Invoke(new NodeOutput() { Value = alarmVariable }, token).ConfigureAwait(false);
}
}
catch (Exception ex)

View File

@@ -13,8 +13,8 @@ public class DeviceChangedTriggerNode : TextNode, ITriggerNode, IDisposable
public DeviceChangedTriggerNode(string id, Point? position = null) : base(id, position) { Title = "DeviceChangedTriggerNode"; Placeholder = "Device.Placeholder"; }
private Func<NodeOutput, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, Task> func)
private Func<NodeOutput, CancellationToken, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, CancellationToken, Task> func, CancellationToken cancellationToken)
{
Func = func;
FuncDict.Add(this, func);
@@ -31,13 +31,13 @@ public class DeviceChangedTriggerNode : TextNode, ITriggerNode, IDisposable
return Task.CompletedTask;
}
public static Dictionary<string, ConcurrentList<DeviceChangedTriggerNode>> DeviceChangedTriggerNodeDict = new();
public static Dictionary<DeviceChangedTriggerNode, Func<NodeOutput, Task>> FuncDict = new();
public static Dictionary<DeviceChangedTriggerNode, Func<NodeOutput, CancellationToken, Task>> FuncDict = new();
public static BlockingCollection<DeviceBasicData> DeviceDatas = new();
static DeviceChangedTriggerNode()
{
_ = RunAsync();
Task.Factory.StartNew(RunAsync);
GlobalData.DeviceStatusChangeEvent += GlobalData_DeviceStatusChangeEvent;
}
@@ -71,7 +71,7 @@ public class DeviceChangedTriggerNode : TextNode, ITriggerNode, IDisposable
if (FuncDict.TryGetValue(item, out var func))
{
item.Logger?.Trace($"Device changed: {item.Text}");
await func.Invoke(new NodeOutput() { Value = deviceDatas }).ConfigureAwait(false);
await func.Invoke(new NodeOutput() { Value = deviceDatas }, token).ConfigureAwait(false);
}
}

View File

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

using ThingsGateway.Blazor.Diagrams.Core.Geometry;
using ThingsGateway.Blazor.Diagrams.Core.Geometry;
using ThingsGateway.NewLife;
using TouchSocket.Core;
@@ -9,12 +8,15 @@ namespace ThingsGateway.Gateway.Application;
[CategoryNode(Category = "Trigger", ImgUrl = "_content/ThingsGateway.Gateway.Razor/img/TimeInterval.svg", Desc = nameof(TimeIntervalTriggerNode), LocalizerType = typeof(ThingsGateway.Gateway.Application.DefaultDiagram), WidgetType = "ThingsGateway.Gateway.Razor.TextWidget,ThingsGateway.Gateway.Razor")]
public class TimeIntervalTriggerNode : TextNode, ITriggerNode, IDisposable
{
~TimeIntervalTriggerNode()
{
this.SafeDispose();
}
public TimeIntervalTriggerNode(string id, Point? position = null) : base(id, position) { Title = "TimeIntervalTriggerNode"; Placeholder = "TimeIntervalTriggerNode.Placeholder"; }
private TimeTick TimeTick;
private Func<NodeOutput, Task> Func { get; set; }
private bool Disposed;
Task ITriggerNode.StartAsync(Func<NodeOutput, Task> func)
private IScheduledTask _task;
private Func<NodeOutput, CancellationToken, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, CancellationToken, Task> func, CancellationToken cancellationToken)
{
Func = func;
if (int.TryParse(Text, out int delay))
@@ -22,40 +24,32 @@ public class TimeIntervalTriggerNode : TextNode, ITriggerNode, IDisposable
if (delay <= 500)
Text = "500";
}
TimeTick = new TimeTick(Text);
_ = Timer();
_task = ScheduledTaskHelper.GetTask(Text, Timer, null, Logger, cancellationToken);
return Task.CompletedTask;
}
private async Task Timer()
private async Task Timer(object? state, CancellationToken cancellationToken)
{
while (!Disposed)
try
{
try
if (Func != null)
{
if (TimeTick.IsTickHappen())
{
if (Func != null)
{
Logger?.Trace($"Timer: {Text}");
await Func.Invoke(new NodeOutput() { Value = TimeTick.LastTime }).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
}
finally
{
await Task.Delay(100).ConfigureAwait(false);
Logger?.Trace($"Timer: {Text}");
await Func.Invoke(new NodeOutput() { }, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
}
}
public void Dispose()
{
Disposed = true;
_task?.Stop();
_task.TryDispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -12,8 +12,8 @@ public class ValueChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
{
public ValueChangedTriggerNode(string id, Point? position = null) : base(id, position) { Title = "ValueChangedTriggerNode"; }
private Func<NodeOutput, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, Task> func)
private Func<NodeOutput, CancellationToken, Task> Func { get; set; }
Task ITriggerNode.StartAsync(Func<NodeOutput, CancellationToken, Task> func, CancellationToken cancellationToken)
{
Func = func;
FuncDict.TryAdd(this, func);
@@ -40,12 +40,12 @@ public class ValueChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
return Task.CompletedTask;
}
public static ConcurrentDictionary<string, ConcurrentDictionary<string, ConcurrentList<ValueChangedTriggerNode>>> ValueChangedTriggerNodeDict = new();
public static ConcurrentDictionary<ValueChangedTriggerNode, Func<NodeOutput, Task>> FuncDict = new();
public static ConcurrentDictionary<ValueChangedTriggerNode, Func<NodeOutput, CancellationToken, Task>> FuncDict = new();
public static BlockingCollection<VariableBasicData> VariableBasicDatas = new();
static ValueChangedTriggerNode()
{
_ = RunAsync();
Task.Factory.StartNew(RunAsync);
GlobalData.VariableValueChangeEvent += GlobalData_VariableValueChangeEvent;
}
private static void GlobalData_VariableValueChangeEvent(VariableRuntime variableRuntime, VariableBasicData variableData)
@@ -81,7 +81,7 @@ public class ValueChangedTriggerNode : VariableNode, ITriggerNode, IDisposable
if (FuncDict.TryGetValue(item, out var func))
{
item.Logger?.Trace($"Variable changed: {item.Text}");
await func.Invoke(new NodeOutput() { Value = variableBasicData }).ConfigureAwait(false);
await func.Invoke(new NodeOutput() { Value = variableBasicData }, token).ConfigureAwait(false);
}
}

View File

@@ -65,7 +65,7 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
if (rules.Status)
{
var data = Init(rules);
await Start(data.rulesLog, data.blazorDiagram, TokenSource.Token).ConfigureAwait(false);
Start(data.rulesLog, data.blazorDiagram, TokenSource.Token);
dispatchService.Dispatch(null);
}
@@ -115,7 +115,7 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
return result;
}
private static Task Start(RulesLog rulesLog, DefaultDiagram item, CancellationToken cancellationToken)
private static void Start(RulesLog rulesLog, DefaultDiagram item, CancellationToken cancellationToken)
{
rulesLog.Log.Trace("Start");
var startNodes = item.Nodes.Where(a => a is IStartNode);
@@ -123,7 +123,6 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
{
_ = Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput(), rulesLog, cancellationToken);
}
return Task.CompletedTask;
}
private static async Task Analysis(NodeModel targetNode, NodeInput input, RulesLog rulesLog, CancellationToken cancellationToken)
@@ -152,30 +151,37 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
else if (targetNode is IExpressionNode expressionNode)
{
var nodeOutput = await expressionNode.ExecuteAsync(input, cancellationToken).ConfigureAwait(false);
foreach (var link in targetNode.PortLinks.Where(a => ((a.Target.Model as PortModel)?.Parent) != targetNode))
if (nodeOutput.IsSuccess)
{
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = nodeOutput.Value, }, rulesLog, cancellationToken).ConfigureAwait(false);
foreach (var link in targetNode.PortLinks.Where(a => ((a.Target.Model as PortModel)?.Parent) != targetNode))
{
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = nodeOutput.Content.Value, }, rulesLog, cancellationToken).ConfigureAwait(false);
}
}
}
else if (targetNode is IActuatorNode actuatorNode)
{
var nodeOutput = await actuatorNode.ExecuteAsync(input, cancellationToken).ConfigureAwait(false);
foreach (var link in targetNode.PortLinks.Where(a => ((a.Target.Model as PortModel)?.Parent) != targetNode))
if (nodeOutput.IsSuccess)
{
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = nodeOutput.Value }, rulesLog, cancellationToken).ConfigureAwait(false);
foreach (var link in targetNode.PortLinks.Where(a => ((a.Target.Model as PortModel)?.Parent) != targetNode))
{
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = nodeOutput.Content.Value }, rulesLog, cancellationToken).ConfigureAwait(false);
}
}
}
else if (targetNode is ITriggerNode triggerNode)
{
Func<NodeOutput, Task> func = (async a =>
Func<NodeOutput, CancellationToken, Task> func = (async (a, token) =>
{
foreach (var link in targetNode.PortLinks.Where(a => ((a.Target.Model as PortModel)?.Parent) != targetNode))
{
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = a.Value }, rulesLog, cancellationToken).ConfigureAwait(false);
await Analysis((link.Target.Model as PortModel)?.Parent, new NodeInput() { Value = a.Value }, rulesLog, token).ConfigureAwait(false);
}
});
await triggerNode.StartAsync(func).ConfigureAwait(false);
await triggerNode.StartAsync(func, cancellationToken).ConfigureAwait(false);
}
@@ -200,16 +206,19 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
foreach (var rules in Rules.Where(a => a.Status))
{
var item = Init(rules);
await Start(item.rulesLog, item.blazorDiagram, cancellationToken).ConfigureAwait(false);
Start(item.rulesLog, item.blazorDiagram, cancellationToken);
}
dispatchService.Dispatch(null);
_ = Task.Factory.StartNew(async () =>
_ = Task.Factory.StartNew(async (state) =>
{
if (state is not Dictionary<RulesLog, Diagram> diagrams)
{
return;
}
while (!cancellationToken.IsCancellationRequested)
{
foreach (var item in Diagrams?.Values?.SelectMany(a => a.Nodes) ?? new List<NodeModel>())
foreach (var item in diagrams?.Values?.SelectMany(a => a.Nodes) ?? new List<NodeModel>())
{
if (item is IExexcuteExpressionsBase)
{
@@ -218,7 +227,7 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
}
await Task.Delay(60000, cancellationToken).ConfigureAwait(false);
}
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
}, Diagrams, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
}

View File

@@ -176,20 +176,20 @@ public class VariableRuntimeService : IVariableRuntimeService
var datas = await GlobalData.VariableService.InsertTestDataAsync(testVariableCount, testDeviceCount, slaveUrl, businessEnable).ConfigureAwait(false);
{
var newChannelRuntimes = (datas.Item1).Adapt<List<ChannelRuntime>>();
var newChannelRuntimes = datas.Item1.Adapt<List<ChannelRuntime>>();
//批量修改之后,需要重新加载通道
RuntimeServiceHelper.Init(newChannelRuntimes);
{
var newDeviceRuntimes = (datas.Item2).Adapt<List<DeviceRuntime>>();
var newDeviceRuntimes = datas.Item2.Adapt<List<DeviceRuntime>>();
RuntimeServiceHelper.Init(newDeviceRuntimes);
}
{
var newVariableRuntimes = (datas.Item3).Adapt<List<VariableRuntime>>();
var newVariableRuntimes = datas.Item3.Adapt<List<VariableRuntime>>();
RuntimeServiceHelper.Init(newVariableRuntimes);
}

View File

@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<Import Project="..\..\Version.props" />
<Import Project="..\..\PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0;</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Portable.BouncyCastle" Version="1.9.0" />
<PackageReference Include="Rougamo.Fody" Version="5.0.0" />
<PackageReference Include="TouchSocket.Dmtp" Version="3.1.8" />
<PackageReference Include="TouchSocket.WebApi.Swagger" Version="3.1.8" />
<PackageReference Include="Rougamo.Fody" Version="5.0.1" />
<PackageReference Include="TouchSocket.Dmtp" Version="3.1.10" />
<PackageReference Include="TouchSocket.WebApi.Swagger" Version="3.1.10" />
<PackageReference Include="ThingsGateway.Authentication" Version="$(AuthenticationVersion)" />
<!--<ProjectReference Include="..\..\PluginPro\ThingsGateway.Authentication\ThingsGateway.Authentication.csproj" />-->

View File

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

View File

@@ -1,4 +1,16 @@
{
"ThingsGateway.Management.Authentication": {
"AuthName": "AuthName",
"Authorized": "Authorized",
"ExpireTime": "ExpireTime",
"Password": "Password",
"Register": "Register",
"RegisterStatus": "RegisterStatus",
"Unauthorized": "Unauthorized",
"Unregister": "Unregister",
"UUID": "UUID"
},
"ThingsGateway.Gateway.Razor._Imports": {
"Actuator": "Actuator",

View File

@@ -1,4 +1,16 @@
{
"ThingsGateway.Management.Authentication": {
"AuthName": "公司名称",
"Authorized": "已授权",
"ExpireTime": "过期时间",
"Password": "注册码",
"Register": "注册",
"RegisterStatus": "注册状态",
"Unauthorized": "未授权",
"Unregister": "取消注册",
"UUID": "唯一编码"
},
"ThingsGateway.Gateway.Razor._Imports": {
"Actuator": "执行",

View File

@@ -16,7 +16,7 @@
<span style="color:var(--bs-body-color)" class="text-h6 mb-2">@GatewayLocalizer["DeviceList"]</span>
<ContextMenuZone title="Right click operation">
<TreeView TItem="ChannelDeviceTreeItem" Items="Items" ShowIcon="false" ShowSearch IsAccordion=false IsVirtualize="true" OnTreeItemClick="OnTreeItemClick" OnSearchAsync="OnClickSearch" ModelEqualityComparer=ModelEqualityComparer>
<TreeView TItem="ChannelDeviceTreeItem" Items="Items" ShowIcon="false" ShowSearch IsAccordion=false IsVirtualize="true" OnTreeItemClick="OnTreeItemClick" OnSearchAsync="OnClickSearch" ModelEqualityComparer=ModelEqualityComparer>
</TreeView>

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