Compare commits

...

17 Commits

Author SHA1 Message Date
Diego
6510c3e289 feat: 增加一个变量读写表达式常用转换的友好编辑界面 2025-06-24 16:14:35 +08:00
Diego
920e407d05 恢复规则引擎脚本接口 2025-06-24 10:52:00 +08:00
Diego
7314c8901d fix: 用户编辑框初始刷新职位 2025-06-24 09:15:33 +08:00
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
180 changed files with 2500 additions and 1769 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

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

@@ -39,6 +39,7 @@ public partial class SysUserEdit
var items = await SysPositionService.SelectorAsync(new PositionSelectorInput() { });
Items = PositionUtil.BuildCascaderItemList(items);
ModuleSelectedItems = ResourceUtil.BuildModuleSelectList((await SysResourceService.GetAllAsync())).ToList();
await InvokeAsync(StateHasChanged);
await base.OnInitializedAsync();
}

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,8 +30,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>

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,14 +11,14 @@
</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>

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) { }

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>
/// 日志作用域提供器
@@ -170,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 集合

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

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

@@ -18,8 +18,6 @@ namespace ThingsGateway.Extension.Generic;
[ThingsGateway.DependencyInjection.SuppressSniffer]
public static class GenericExtensions
{
private static MemoryCache Instance { get; set; } = new MemoryCache();
/// <summary>
/// 把已修改的属性赋值到列表中,并返回字典
/// </summary>

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

@@ -1,12 +1,12 @@
<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>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BootstrapBlazor.FontAwesome" Version="9.0.2" />
<PackageReference Include="BootstrapBlazor" Version="9.7.3" />
<PackageReference Include="BootstrapBlazor" Version="9.7.4" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
</ItemGroup>
@@ -20,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>

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>

View File

@@ -1,12 +1,13 @@
<Project>
<PropertyGroup>
<PluginVersion>10.8.2</PluginVersion>
<ProPluginVersion>10.8.2</ProPluginVersion>
<AuthenticationVersion>2.8.0</AuthenticationVersion>
<SourceGeneratorVersion>10.8.2</SourceGeneratorVersion>
<PluginVersion>10.8.23</PluginVersion>
<ProPluginVersion>10.8.23</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,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" />
<PropertyGroup>
<TargetFrameworks>net8.0;</TargetFrameworks>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->

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

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

@@ -1,26 +1,27 @@
using TouchSocket.Core;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
namespace ThingsGateway.Gateway.Application;
public class ScheduledTask
public class ScheduledAsyncTask : DisposeBase, IScheduledTask, IScheduledIntIntervalTask
{
private TimeSpan _interval { get; }
private TimeSpan _interval10 = TimeSpan.FromMilliseconds(10);
private double _intervalMS { get; }
private int _interval10MS = 10;
public int IntervalMS { get; }
private readonly Func<object?, CancellationToken, Task> _taskFunc;
private readonly CancellationToken _token;
private Timer? _timer;
private TimerX? _timer;
private object? _state;
private ILog LogMessage;
private volatile int _isRunning = 0;
private volatile int _pendingTriggers = 0;
public ScheduledTask(TimeSpan interval, Func<object?, CancellationToken, Task> taskFunc, object? state, ILog log, CancellationToken token)
public ScheduledAsyncTask(int interval, Func<object?, CancellationToken, Task> taskFunc, object? state, ILog log, CancellationToken token)
{
IntervalMS = interval;
LogMessage = log;
_state = state;
_interval = interval;
_intervalMS = interval.TotalMilliseconds;
_taskFunc = taskFunc;
_token = token;
}
@@ -28,24 +29,23 @@ public class ScheduledTask
public void Start()
{
_timer?.Dispose();
_timer = new Timer(TimerCallback, _state, TimeSpan.Zero, _interval);
if (!_token.IsCancellationRequested)
_timer = new TimerX(DoAsync, _state, IntervalMS, IntervalMS, nameof(IScheduledTask)) { Async = true };
}
private void TimerCallback(object? state)
{
_ = Do(state);
}
private async Task Do(object? state)
private async Task DoAsync(object? state)
{
if (_token.IsCancellationRequested)
return;
Interlocked.Exchange(ref _pendingTriggers, 1);
Interlocked.Increment(ref _pendingTriggers);
if (Interlocked.Exchange(ref _isRunning, 1) == 1)
return;
// 减少一个触发次数
Interlocked.Decrement(ref _pendingTriggers);
try
{
await _taskFunc(state, _token).ConfigureAwait(false);
@@ -62,7 +62,7 @@ public class ScheduledTask
Interlocked.Exchange(ref _isRunning, 0);
}
if (Interlocked.Exchange(ref _pendingTriggers, 0) == 1)
if (Interlocked.Exchange(ref _pendingTriggers, 0) >= 1)
{
if (!_token.IsCancellationRequested)
{
@@ -74,13 +74,10 @@ public class ScheduledTask
private void DelayDo()
{
// 延迟触发下一次
_timer?.Change(_interval10, _interval);
if (!_token.IsCancellationRequested)
_timer?.SetNext(_interval10MS);
}
public void Change(int dueTime, int period)
{
_timer?.Change(dueTime, period);
}
public void Stop()
{
@@ -88,4 +85,9 @@ public class ScheduledTask
_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

@@ -2,12 +2,16 @@
public class TaskSchedulerLoop
{
public readonly List<ScheduledTask> Tasks;
private readonly List<IScheduledTask> Tasks;
public TaskSchedulerLoop(List<ScheduledTask> tasks)
public TaskSchedulerLoop(List<IScheduledTask> tasks)
{
Tasks = tasks;
}
public int Count()
{
return Tasks.Count;
}
public void Start()
{
@@ -24,11 +28,14 @@ public class TaskSchedulerLoop
task.Stop();
}
}
public void Change(int dueTime, int period)
public void Add(IScheduledTask task)
{
foreach (var task in Tasks)
{
task.Change(dueTime, period);
}
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 Task 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 =>
{
@@ -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,12 +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);
// 如果不是间隔上传,则订阅全局变量值改变事件和设备状态改变事件,并触发一次事件处理
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Interval)
{
@@ -126,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,9 +35,6 @@ public abstract class BusinessBaseWithCacheIntervalVariableModel<VarModel> : Bus
protected internal override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
// 初始化定时器
_exTTimerTick = new TimeTick(_businessPropertyWithCacheInterval.BusinessInterval);
// 注册变量值变化事件处理程序
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum != BusinessUpdateEnum.Interval)
{
@@ -90,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>

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,353 +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;
}
}
ReadResultCount readResultCount = new();
/// <summary>
/// 执行读取等方法,如果插件不支持读取,而是自更新值的话,需重写此方法
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task ProtectedExecuteAsync(CancellationToken cancellationToken)
{
try
{
readResultCount.Reset();
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>每个驱动打包方法不一样,所以需要实现这个接口
@@ -538,20 +462,38 @@ 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;
public void Reset()
if (VariableSourceReadsEnable)
{
deviceMethodsVariableFailedNum = 0;
deviceMethodsVariableSuccessNum = 0;
deviceSourceVariableFailedNum = 0;
deviceSourceVariableSuccessNum = 0;
// 如果成功,每个变量都读取一次最新值,再次比较写入值
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);
}
}

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,7 +241,7 @@ public abstract class DriverBase : DisposableObject, IDriver
}
/// <summary>
/// 在循环任务开始之前
/// 在任务开始之前
/// </summary>
/// <param name="cancellationToken">取消操作的令牌。</param>
/// <returns>表示异步操作的任务。</returns>
@@ -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 Task 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(SetCycleInterval, 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>
@@ -388,17 +335,7 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
token.Register(driver.Stop);
if (driver.IsInitSuccess)
{
// 初始化业务线程
var driverTask = new DoTask(DoWork, driver.LogMessage, driver);
DriverTasks.TryAdd(driver.DeviceId, driverTask);
driverTask.Start(token);
}
_ = Task.Factory.StartNew((state) => DriverStart(state, token), driver, token);
}).ConfigureAwait(false);
@@ -466,33 +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))
{
if (IsCollectChannel == true)
{
saveVariableRuntimes.AddRange(driver.IdVariableRuntimes.Where(a => a.Value.SaveValue && !a.Value.DynamicVariable).Select(a => a.Value));
}
}
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 (CancellationTokenSources.TryRemove(deviceId, out var token))
{
if (token != null)
{
token.Cancel();
token.Dispose();
}
}
if (DriverTasks.TryRemove(deviceId, out var task))
{
await task.StopAsync().ConfigureAwait(false);
}
if (DriverTasks.TryRemove(deviceId, out var task))
{
task.Stop();
}
}).ConfigureAwait(false);
// 取消驱动程序的操作
if (CancellationTokenSources.TryRemove(deviceId, out var token))
{
if (token != null)
{
token.Cancel();
token.Dispose();
}
}
});
await Task.Delay(100).ConfigureAwait(false);
@@ -543,7 +482,7 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
return driver;
}
private static async Task DoWork(object? state, CancellationToken token)
private async Task DriverStart(object? state, CancellationToken token)
{
try
{
@@ -554,41 +493,12 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
if (!driver.IsStarted)
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 && driver.IsCollectDevice == 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)
@@ -826,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

@@ -104,12 +104,22 @@ public class ExecuteScriptNode : TextNode, IActuatorNode, IExexcuteExpressionsBa
}
}
Task<NodeOutput> IActuatorNode.ExecuteAsync(NodeInput input, CancellationToken cancellationToken)
async 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;
var data = await exexcuteExpressions.ExecuteAsync(input, cancellationToken).ConfigureAwait(false);
return new OperResult<NodeOutput>() { Content = data };
}
catch (Exception ex)
{
Logger?.LogWarning(ex);
return 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
{

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,11 +206,10 @@ 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 (state) =>
{
if (state is not Dictionary<RulesLog, Diagram> diagrams)

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,34 @@
{
"ThingsGateway.Gateway.Razor.ValueTransformType": {
"None": "None",
"Linear": "Linear",
"Sqrt": "Sqrt"
},
"ThingsGateway.Gateway.Razor.ValueTransformConfig": {
"TransformType": "TransformType",
"MinMax": "MinMax",
"ClampToRawRange": "ClampToRawRange",
"DecimalPlaces": "DecimalPlaces",
"RawMin": "RawMin",
"RawMax": "RawMax",
"ActualMin": "ActualMin",
"ActualMax": "ActualMax"
},
"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,32 @@
{
"ThingsGateway.Gateway.Razor.ValueTransformType": {
"None": "无",
"Linear": "线性",
"Sqrt": "开方"
},
"ThingsGateway.Gateway.Razor.ValueTransformConfig": {
"TransformType": "转换方式",
"MinMax": "最小最大值",
"ClampToRawRange": "限制范围",
"DecimalPlaces": "保留小数位",
"RawMin": "原始最小值",
"RawMax": "原始最大值",
"ActualMin": "实际最小值",
"ActualMax": "实际最大值"
},
"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>

View File

@@ -1469,27 +1469,22 @@ EventCallback.Factory.Create<MouseEventArgs>(this, async e =>
private static bool ModelEqualityComparer(ChannelDeviceTreeItem x, ChannelDeviceTreeItem y)
{
if (x.ChannelDevicePluginType == y.ChannelDevicePluginType)
{
if (x.ChannelDevicePluginType == ChannelDevicePluginTypeEnum.Device)
{
return x.DeviceRuntime.Id == y.DeviceRuntime.Id; ;
}
else if (x.ChannelDevicePluginType == ChannelDevicePluginTypeEnum.PluginType)
{
return x.PluginType == y.PluginType;
if (x.ChannelDevicePluginType != y.ChannelDevicePluginType)
return false;
}
else if (x.ChannelDevicePluginType == ChannelDevicePluginTypeEnum.Channel)
{
switch (x.ChannelDevicePluginType)
{
case ChannelDevicePluginTypeEnum.Device:
return x.DeviceRuntime.Id == y.DeviceRuntime.Id;
case ChannelDevicePluginTypeEnum.PluginType:
return x.PluginType == y.PluginType;
case ChannelDevicePluginTypeEnum.Channel:
return x.ChannelRuntime.Id == y.ChannelRuntime.Id;
}
else if (x.ChannelDevicePluginType == ChannelDevicePluginTypeEnum.PluginName)
{
case ChannelDevicePluginTypeEnum.PluginName:
return x.PluginName == y.PluginName;
}
default:
return false;
}
return false;
}
private bool Disposed;
protected override ValueTask DisposeAsync(bool disposing)

View File

@@ -31,27 +31,22 @@ public class ChannelDeviceTreeItem : IEqualityComparer<ChannelDeviceTreeItem>
{
if (obj is ChannelDeviceTreeItem item)
{
if (ChannelDevicePluginType == item.ChannelDevicePluginType)
if (ChannelDevicePluginType != item.ChannelDevicePluginType)
return false;
switch (ChannelDevicePluginType)
{
if (ChannelDevicePluginType == ChannelDevicePluginTypeEnum.Device)
{
case ChannelDevicePluginTypeEnum.Device:
return DeviceRuntime == item.DeviceRuntime;
}
else if (ChannelDevicePluginType == ChannelDevicePluginTypeEnum.PluginType)
{
case ChannelDevicePluginTypeEnum.PluginType:
return PluginType == item.PluginType;
}
else if (ChannelDevicePluginType == ChannelDevicePluginTypeEnum.Channel)
{
case ChannelDevicePluginTypeEnum.Channel:
return ChannelRuntime == item.ChannelRuntime;
}
else if (ChannelDevicePluginType == ChannelDevicePluginTypeEnum.PluginName)
{
case ChannelDevicePluginTypeEnum.PluginName:
return PluginName == item.PluginName;
}
default:
return false;
}
}
return false;

View File

@@ -0,0 +1,62 @@
//------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权除特别声明外的代码归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库https://github.com/kimdiego2098/ThingsGateway
// 使用文档https://thingsgateway.cn/
// QQ群605534569
//------------------------------------------------------------------------------
namespace ThingsGateway.Gateway.Razor;
public class ValueTransformConfig
{
/// <summary>
/// 保留小数位
/// </summary>
public int DecimalPlaces { get; set; } = 2;
/// <summary>
/// 限制范围
/// </summary>
public bool ClampToRawRange { get; set; }
public ValueTransformType TransformType { get; set; }
/// <summary>
/// 原始低
/// </summary>
public decimal RawMin { get; set; }
/// <summary>
/// 原始高
/// </summary>
public decimal RawMax { get; set; }
/// <summary>
/// 实际低
/// </summary>
public decimal ActualMin { get; set; }
/// <summary>
/// 实际高
/// </summary>
public decimal ActualMax { get; set; }
}
public enum ValueTransformType
{
/// <summary>
/// 不转换,仅保留小数位
/// </summary>
None,
/// <summary>
/// 线性转换
/// </summary>
Linear,
/// <summary>
/// 开方转换
/// </summary>
Sqrt
}

View File

@@ -0,0 +1,31 @@
@namespace ThingsGateway.Gateway.Razor
@using ThingsGateway.Admin.Application
@using ThingsGateway.Admin.Razor
@using ThingsGateway.Foundation
@using ThingsGateway.Gateway.Application
@inherits ComponentDefault
<ValidateForm class="p-4 h-100" Model="@ValueTransformConfig" OnValidSubmit="OnSave">
<EditorForm AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=1 LabelWidth=150 Model="ValueTransformConfig">
<FieldItems>
<EditorItem @bind-Field="@context.TransformType" GroupName=@(ValueTransformConfigLocalizer["TransformType"]) Cols="4" />
<EditorItem @bind-Field="@context.ClampToRawRange" GroupName=@(ValueTransformConfigLocalizer["TransformType"]) Cols="4" />
<EditorItem @bind-Field="@context.DecimalPlaces" GroupName=@(ValueTransformConfigLocalizer["TransformType"]) Cols="4" />
<EditorItem @bind-Field="@context.RawMin" GroupName=@(ValueTransformConfigLocalizer["MinMax"]) GroupOrder=2 Cols="6" />
<EditorItem @bind-Field="@context.RawMax" GroupName=@(ValueTransformConfigLocalizer["MinMax"]) GroupOrder=2 Cols="6" />
<EditorItem @bind-Field="@context.ActualMin" GroupName=@(ValueTransformConfigLocalizer["MinMax"]) GroupOrder=2 Cols="6" />
<EditorItem @bind-Field="@context.ActualMax" GroupName=@(ValueTransformConfigLocalizer["MinMax"]) GroupOrder=2 Cols="6" />
</FieldItems>
<Buttons>
<Button ButtonType="ButtonType.Submit" Icon="fa-solid fa-floppy-disk" IsAsync Text=@RazorLocalizer["Save"] />
</Buttons>
</EditorForm>
</ValidateForm>

View File

@@ -0,0 +1,215 @@
//------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权除特别声明外的代码归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库https://github.com/kimdiego2098/ThingsGateway
// 使用文档https://thingsgateway.cn/
// QQ群605534569
//------------------------------------------------------------------------------
using Microsoft.AspNetCore.Components.Forms;
using System.Globalization;
using System.Text.RegularExpressions;
using ThingsGateway.NewLife.Extension;
namespace ThingsGateway.Gateway.Razor;
public partial class ValueTransformConfigPage
{
private ValueTransformConfig ValueTransformConfig = new();
[Inject]
[NotNull]
private IStringLocalizer<ValueTransformConfig>? ValueTransformConfigLocalizer { get; set; }
[Parameter]
public string Expressions { get; set; }
[Parameter]
public EventCallback<string> ExpressionsChanged { get; set; }
public static bool TryParseLinearFormula(string formula, out ValueTransformConfig config)
{
config = new ValueTransformConfig();
var dec = @"[\d]+(?:\.[\d]+)?";
try
{
// None + clamp actual
var m = Regex.Match(formula, $@"^Math\.Round\(\s*
Math\.Min\(\s*
Math\.Max\(\s*
raw\.ToDecimal\(\)\s*,\s*({dec})\s*\)\s*,\s*({dec})\s*\)\s*,\s*(\d+)\s*\)$", RegexOptions.IgnorePatternWhitespace);
if (m.Success)
{
config.TransformType = ValueTransformType.None;
config.ClampToRawRange = true;
config.ActualMin = decimal.Parse(m.Groups[1].Value);
config.ActualMax = decimal.Parse(m.Groups[2].Value);
config.DecimalPlaces = int.Parse(m.Groups[3].Value);
return true;
}
// None pure
m = Regex.Match(formula, $@"^Math\.Round\(\s*raw\.ToDecimal\(\)\s*,\s*(\d+)\s*\)$");
if (m.Success)
{
config.TransformType = ValueTransformType.None;
config.ClampToRawRange = false;
config.DecimalPlaces = int.Parse(m.Groups[1].Value);
return true;
}
// Linear + clamp actual
m = Regex.Match(formula, $@"^Math\.Round\(\s*
Math\.Min\(\s*
Math\.Max\(\s*
\(\(raw\.ToDecimal\(\)\s*-\s*({dec})\)\s*/\s*
\(({dec})\s*-\s*({dec})\)\s*\*\s*
\(({dec})\s*-\s*({dec})\)\s*\+\s*
({dec})\)\s*,\s*({dec})\)\s*,\s*({dec})\)\s*,\s*(\d+)\s*\)$", RegexOptions.IgnorePatternWhitespace);
if (m.Success)
{
config.TransformType = ValueTransformType.Linear;
config.ClampToRawRange = true;
config.RawMin = decimal.Parse(m.Groups[1].Value);
config.RawMax = decimal.Parse(m.Groups[2].Value);
config.ActualMax = decimal.Parse(m.Groups[4].Value);
config.ActualMin = decimal.Parse(m.Groups[5].Value);
config.DecimalPlaces = int.Parse(m.Groups[9].Value);
return true;
}
// Linear pure
m = Regex.Match(formula, $@"^Math\.Round\(\s*
\(\(raw\.ToDecimal\(\)\s*-\s*({dec})\)\s*/\s*
\(({dec})\s*-\s*({dec})\)\s*\*\s*
\(({dec})\s*-\s*({dec})\)\s*\+\s*({dec})\)\s*,\s*(\d+)\s*\)$", RegexOptions.IgnorePatternWhitespace);
if (m.Success)
{
config.TransformType = ValueTransformType.Linear;
config.ClampToRawRange = false;
config.RawMin = decimal.Parse(m.Groups[1].Value); // raw减数0
config.RawMax = decimal.Parse(m.Groups[2].Value); // 分母第一个数10
config.ActualMax = decimal.Parse(m.Groups[4].Value); // 乘数第一个数1
config.ActualMin = decimal.Parse(m.Groups[6].Value); // 加数0
config.DecimalPlaces = int.Parse(m.Groups[7].Value); // 小数位2
return true;
}
// Sqrt + clamp actual
m = Regex.Match(formula, $@"^Math\.Round\(\s*
Math\.Min\(\s*
Math\.Max\(\s*
Math\.Sqrt\(Math\.Max\(raw\.ToDecimal\(\),\s*0\)\)\s*\*\s*({dec})\s*,\s*({dec})\)\s*,\s*({dec})\)\s*,\s*(\d+)\s*\)$", RegexOptions.IgnorePatternWhitespace);
if (m.Success)
{
config.TransformType = ValueTransformType.Sqrt;
config.ClampToRawRange = true;
config.ActualMax = decimal.Parse(m.Groups[1].Value);
config.ActualMin = decimal.Parse(m.Groups[2].Value);
config.DecimalPlaces = int.Parse(m.Groups[4].Value);
return true;
}
// Sqrt pure
m = Regex.Match(formula, $@"^Math\.Round\(\s*
Math\.Sqrt\(Math\.Max\(raw\.ToDecimal\(\),\s*0\)\)\s*\*\s*({dec})\s*,\s*(\d+)\s*\)$", RegexOptions.IgnorePatternWhitespace);
if (m.Success)
{
config.TransformType = ValueTransformType.Sqrt;
config.ClampToRawRange = false;
config.DecimalPlaces = int.Parse(m.Groups[2].Value);
return true;
}
}
catch
{
// ignore
}
return false;
}
public static string GenerateFormula(ValueTransformConfig config)
{
// 只有 ClampToRawRange 为 true 时才包裹实际值范围限制
string clampActual(string expr)
{
if (config.ClampToRawRange)
return $"Math.Min(Math.Max({expr}, {config.ActualMin}), {config.ActualMax})";
else
return expr;
}
string rawExpr = "raw.ToDecimal()"; // 这里不做 raw clamp
switch (config.TransformType)
{
case ValueTransformType.None:
return $"Math.Round({clampActual(rawExpr)}, {config.DecimalPlaces})";
case ValueTransformType.Linear:
var linearExpr = $"(({rawExpr} - {config.RawMin}) / ({config.RawMax} - {config.RawMin}) * ({config.ActualMax} - {config.ActualMin}) + {config.ActualMin})";
return $"Math.Round({clampActual(linearExpr)}, {config.DecimalPlaces})";
case ValueTransformType.Sqrt:
var sqrtExpr = $"Math.Sqrt(Math.Max({rawExpr}, 0)) * {config.ActualMax}";
return $"Math.Round({clampActual(sqrtExpr)}, {config.DecimalPlaces})";
default:
throw new NotSupportedException($"Unsupported transform type: {config.TransformType}");
}
}
protected override void OnParametersSet()
{
if (!Expressions.IsNullOrWhiteSpace())
{
if (TryParseLinearFormula(Expressions, out var config))
{
ValueTransformConfig = config;
}
}
base.OnParametersSet();
}
#region
[CascadingParameter]
private Func<Task>? OnCloseAsync { get; set; }
private async Task OnSave(EditContext editContext)
{
try
{
var result = GenerateFormula(ValueTransformConfig);
Expressions = result;
if (ExpressionsChanged.HasDelegate)
{
await ExpressionsChanged.InvokeAsync(result);
}
else
{
Expressions = result;
}
if (OnCloseAsync != null)
await OnCloseAsync();
}
catch (Exception ex)
{
await ToastService.Warn(ex);
}
}
#endregion
}

View File

@@ -0,0 +1,7 @@
.appconfig ::deep .tabs-body-content {
height: 100% !important;
}
.appconfig {
height: 100% !important;
}

View File

@@ -28,225 +28,247 @@
RenderFragment renderFragment =>
@<Tab>
<TabItem Text=@GatewayLocalizer["VariableInformation"]>
<TabItem Text=@GatewayLocalizer["VariableInformation"]>
<EditorForm class="p-2" AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 LabelWidth=200 Model="Model">
<EditorForm class="p-2" AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 LabelWidth=200 Model="Model">
<FieldItems>
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Name">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["BasicInformation"]</h6>
</div>
</EditTemplate>
</EditorItem>
<FieldItems>
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Name">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["BasicInformation"]</h6>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.Name" Readonly=BatchEditEnable />
<EditorItem @bind-Field="@context.Name" Readonly=BatchEditEnable />
<EditorItem @bind-Field="@context.Description" />
<EditorItem @bind-Field="@context.CollectGroup" />
<EditorItem @bind-Field="@context.BusinessGroup" />
<EditorItem @bind-Field="@context.Description" />
<EditorItem @bind-Field="@context.CollectGroup" />
<EditorItem @bind-Field="@context.BusinessGroup" />
<EditorItem @bind-Field="@context.BusinessGroupUpdateTrigger" />
<EditorItem @bind-Field="@context.RpcWriteCheck" />
<EditorItem @bind-Field="@context.Unit" />
<EditorItem @bind-Field="@context.ProtectType" />
<EditorItem @bind-Field="@context.Enable" />
<EditorItem @bind-Field="@context.RpcWriteEnable" />
<EditorItem @bind-Field="@context.Unit" />
<EditorItem @bind-Field="@context.ProtectType" />
<EditorItem @bind-Field="@context.Enable" />
<EditorItem @bind-Field="@context.RpcWriteEnable" />
<EditorItem @bind-Field="@context.InitValue">
<EditTemplate Context="value">
<div class="col-12 col-md-6 ">
<BootstrapInput @bind-Value="@value.InitValue" DisplayText="@(context.Description(a=>a.InitValue))" ShowLabel="true" Formatter=@(JsonFormatter) />
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.InitValue">
<EditTemplate Context="value">
<div class="col-12 col-md-6 ">
<BootstrapInput @bind-Value="@value.InitValue" DisplayText="@(context.Description(a => a.InitValue))" ShowLabel="true" Formatter=@(JsonFormatter) />
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.SaveValue" />
<EditorItem @bind-Field="@context.SaveValue" />
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Name">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["Connection"]</h6>
</div>
</EditTemplate>
</EditorItem>
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Name">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["Connection"]</h6>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.DeviceId">
<EditTemplate Context="value">
<div class="col-12 col-md-6 ">
<BootstrapInputGroup>
<Select IsVirtualize @bind-Value="@value.DeviceId" DefaultVirtualizeItemText=@(GlobalData.ReadOnlyIdDevices.TryGetValue(value.DeviceId,out var deviceRuntime)?deviceRuntime.Name:string.Empty) IsDisabled=BatchEditEnable Items="@CollectDeviceItems" OnSelectedItemChanged=OnDeviceChanged ShowSearch="true" ShowLabel="true" />
<Button class="text-end" Icon="fa-solid fa-plus" OnClick="AddDevice" IsDisabled=BatchEditEnable></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.DeviceId">
<EditTemplate Context="value">
<div class="col-12 col-md-6 ">
<BootstrapInputGroup>
<Select IsVirtualize @bind-Value="@value.DeviceId" DefaultVirtualizeItemText=@(GlobalData.ReadOnlyIdDevices.TryGetValue(value.DeviceId, out var deviceRuntime) ? deviceRuntime.Name : string.Empty) IsDisabled=BatchEditEnable Items="@CollectDeviceItems" OnSelectedItemChanged=OnDeviceChanged ShowSearch="true" ShowLabel="true" />
<Button class="text-end" Icon="fa-solid fa-plus" OnClick="AddDevice" IsDisabled=BatchEditEnable></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.DataType" />
<EditorItem @bind-Field="@context.IntervalTime" />
<EditorItem @bind-Field="@context.DataType" />
<EditorItem @bind-Field="@context.IntervalTime" />
<EditorItem @bind-Field="@context.OtherMethod">
<EditTemplate Context="value">
<div class="col-12 col-md-6">
<Select IsVirtualize DefaultVirtualizeItemText=@(OtherMethods.TryGetValue(value.OtherMethod??string.Empty,out var desc)?desc:value.OtherMethod) @bind-Value="@value.OtherMethod" Items="@OtherMethodSelectedItems" ShowSearch="true" />
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.OtherMethod">
<EditTemplate Context="value">
<div class="col-12 col-md-6">
<Select IsVirtualize DefaultVirtualizeItemText=@(OtherMethods.TryGetValue(value.OtherMethod ?? string.Empty, out var desc) ? desc : value.OtherMethod) @bind-Value="@value.OtherMethod" Items="@OtherMethodSelectedItems" ShowSearch="true" />
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.RegisterAddress">
<EditTemplate Context="value">
<div class="col-12">
<BootstrapInputGroup>
@if(GlobalData.ReadOnlyIdDevices.TryGetValue(value.DeviceId,out var device)&&device.Driver is CollectBase collectBase)
{
<Textarea rows="1" title=@collectBase.GetAddressDescription() @bind-Value="value.RegisterAddress" ShowLabel="true"></Textarea>
}
else
<EditorItem @bind-Field="@context.RegisterAddress">
<EditTemplate Context="value">
<div class="col-12">
<BootstrapInputGroup>
@if(GlobalData.ReadOnlyIdDevices.TryGetValue(value.DeviceId,out var device)&&device.Driver is CollectBase collectBase)
{
<Textarea rows="1" title=@collectBase.GetAddressDescription() @bind-Value="value.RegisterAddress" ShowLabel="true"></Textarea>
}
else
{
<Textarea rows="1" @bind-Value="value.RegisterAddress" ShowLabel="true"></Textarea>
}
<Button IsDisabled=@(AddressUIType==null) Icon="fa-solid fa-bars" OnClick="ShowAddressUI"></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.ArrayLength" />
<Button IsDisabled=@(AddressUIType == null) Icon="fa-solid fa-bars" OnClick="ShowAddressUI"></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.ArrayLength" />
<EditorItem @bind-Field="@context.ReadExpressions" Rows="1" />
<EditorItem @bind-Field="@context.WriteExpressions" Rows="1" />
<EditorItem @bind-Field="@context.ReadExpressions">
<EditTemplate Context="value">
<div class="col-12">
<BootstrapInputGroup>
<Textarea rows="1" @bind-Value="value.ReadExpressions" ShowLabel="true"></Textarea>
<Button Icon="fa-solid fa-bars" OnClick="() => ShowExpressionsUI(true)"></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.WriteExpressions">
<EditTemplate Context="value">
<div class="col-12">
<BootstrapInputGroup>
<Textarea rows="1" @bind-Value="value.WriteExpressions" ShowLabel="true"></Textarea>
<Button Icon="fa-solid fa-bars" OnClick="() => ShowExpressionsUI(false)"></Button>
</BootstrapInputGroup>
</div>
</EditTemplate>
</EditorItem>
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Description">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["Remark"]</h6>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.Remark1" />
<EditorItem @bind-Field="@context.Remark2" />
<EditorItem @bind-Field="@context.Remark3" />
<EditorItem @bind-Field="@context.Remark4" />
<EditorItem @bind-Field="@context.Remark5" />
<EditorItem TValue="string" TModel="Variable" @bind-Field="@context.Description">
<EditTemplate Context="value">
<div class="col-12">
<h6>@GatewayLocalizer["Remark"]</h6>
</div>
</EditTemplate>
</EditorItem>
<EditorItem @bind-Field="@context.Remark1" />
<EditorItem @bind-Field="@context.Remark2" />
<EditorItem @bind-Field="@context.Remark3" />
<EditorItem @bind-Field="@context.Remark4" />
<EditorItem @bind-Field="@context.Remark5" />
</FieldItems>
</FieldItems>
</EditorForm>
</TabItem>
</EditorForm>
</TabItem>
<TabItem Text=@GatewayLocalizer["AlarmInformation"]>
<EditorForm class="p-2" AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 LabelWidth=250 Model="Model">
<FieldItems>
<TabItem Text=@GatewayLocalizer["AlarmInformation"]>
<EditorForm class="p-2" AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 LabelWidth=250 Model="Model">
<FieldItems>
<EditorItem @bind-Field="@context.BoolCloseAlarmText" />
<EditorItem @bind-Field="@context.BoolCloseRestrainExpressions" />
<EditorItem @bind-Field="@context.BoolCloseAlarmEnable" Rows="1" />
<EditorItem @bind-Field="@context.BoolOpenAlarmText" />
<EditorItem @bind-Field="@context.BoolOpenRestrainExpressions" />
<EditorItem @bind-Field="@context.BoolOpenAlarmEnable" Rows="1" />
<EditorItem @bind-Field="@context.HHAlarmText" />
<EditorItem @bind-Field="@context.HHAlarmCode" />
<EditorItem @bind-Field="@context.HHRestrainExpressions" />
<EditorItem @bind-Field="@context.HHAlarmEnable" />
<EditorItem @bind-Field="@context.HAlarmText" />
<EditorItem @bind-Field="@context.HAlarmCode" />
<EditorItem @bind-Field="@context.HRestrainExpressions" />
<EditorItem @bind-Field="@context.HAlarmEnable" />
<EditorItem @bind-Field="@context.LAlarmText" />
<EditorItem @bind-Field="@context.LAlarmCode" />
<EditorItem @bind-Field="@context.LRestrainExpressions" />
<EditorItem @bind-Field="@context.LAlarmEnable" />
<EditorItem @bind-Field="@context.LLAlarmText" />
<EditorItem @bind-Field="@context.LLAlarmCode" />
<EditorItem @bind-Field="@context.LLRestrainExpressions" />
<EditorItem @bind-Field="@context.LLAlarmEnable" />
<EditorItem @bind-Field="@context.CustomAlarmText" />
<EditorItem @bind-Field="@context.CustomAlarmCode" />
<EditorItem @bind-Field="@context.CustomRestrainExpressions" />
<EditorItem @bind-Field="@context.CustomAlarmEnable" />
<EditorItem @bind-Field="@context.AlarmDelay" />
</FieldItems>
</EditorForm>
</TabItem>
@if(!BatchEditEnable)
{
<EditorItem @bind-Field="@context.BoolCloseAlarmText" />
<EditorItem @bind-Field="@context.BoolCloseRestrainExpressions" />
<EditorItem @bind-Field="@context.BoolCloseAlarmEnable" Rows="1" />
<EditorItem @bind-Field="@context.BoolOpenAlarmText" />
<EditorItem @bind-Field="@context.BoolOpenRestrainExpressions" />
<EditorItem @bind-Field="@context.BoolOpenAlarmEnable" Rows="1" />
<EditorItem @bind-Field="@context.HHAlarmText" />
<EditorItem @bind-Field="@context.HHAlarmCode" />
<EditorItem @bind-Field="@context.HHRestrainExpressions" />
<EditorItem @bind-Field="@context.HHAlarmEnable" />
<EditorItem @bind-Field="@context.HAlarmText" />
<EditorItem @bind-Field="@context.HAlarmCode" />
<EditorItem @bind-Field="@context.HRestrainExpressions" />
<EditorItem @bind-Field="@context.HAlarmEnable" />
<EditorItem @bind-Field="@context.LAlarmText" />
<EditorItem @bind-Field="@context.LAlarmCode" />
<EditorItem @bind-Field="@context.LRestrainExpressions" />
<EditorItem @bind-Field="@context.LAlarmEnable" />
<EditorItem @bind-Field="@context.LLAlarmText" />
<EditorItem @bind-Field="@context.LLAlarmCode" />
<EditorItem @bind-Field="@context.LLRestrainExpressions" />
<EditorItem @bind-Field="@context.LLAlarmEnable" />
<EditorItem @bind-Field="@context.CustomAlarmText" />
<EditorItem @bind-Field="@context.CustomAlarmCode" />
<EditorItem @bind-Field="@context.CustomRestrainExpressions" />
<EditorItem @bind-Field="@context.CustomAlarmEnable" />
<EditorItem @bind-Field="@context.AlarmDelay" />
</FieldItems>
</EditorForm>
</TabItem>
@if (!BatchEditEnable)
{
<TabItem Text=@GatewayLocalizer["PluginInformation"]>
<div class="min-height-500 px-4">
<div class="row g-2 mx-1 form-inline">
<div class="col-12 col-md-8">
<Select SkipValidate IsVirtualize DefaultVirtualizeItemText=@(GlobalData.ReadOnlyIdDevices.TryGetValue(ChoiceBusinessDeviceId,out var deviceRuntime)?deviceRuntime.Name:string.Empty) @bind-Value="@ChoiceBusinessDeviceId" Items="@BusinessDeviceItems" ShowSearch="true" ShowLabel="true" />
<Select SkipValidate IsVirtualize DefaultVirtualizeItemText=@(GlobalData.ReadOnlyIdDevices.TryGetValue(ChoiceBusinessDeviceId, out var deviceRuntime) ? deviceRuntime.Name : string.Empty) @bind-Value="@ChoiceBusinessDeviceId" Items="@BusinessDeviceItems" ShowSearch="true" ShowLabel="true" />
</div>
<div class="col-12 col-md-4">
<Button OnClick="async() =>{
await RefreshBusinessPropertyClickAsync(ChoiceBusinessDeviceId);
foreach (var item in Model.VariablePropertyModels)
{
if(item.Value!=null)
{
item.Value.ValidateForm=null;
}
}
}">
@GatewayLocalizer["RefreshBusinessProperty"]
</Button>
</div>
await RefreshBusinessPropertyClickAsync(ChoiceBusinessDeviceId);
foreach (var item in Model.VariablePropertyModels)
{
if (item.Value != null)
{
item.Value.ValidateForm = null;
}
}
}">
@GatewayLocalizer["RefreshBusinessProperty"]
</Button>
</div>
@if (Model.VariablePropertyModels != null)
</div>
@if (Model.VariablePropertyModels != null)
{
@foreach (var a in Model.VariablePropertyModels)
{
{
var item = a;
var item = a;
var custom = VariablePropertyRenderFragments.TryGetValue(item.Key, out var renderFragment);
var custom = VariablePropertyRenderFragments.TryGetValue(item.Key, out var renderFragment);
if (!custom)
{
var has = VariablePropertyEditors.TryGetValue(item.Key, out var items);
if (has)
{
if (!custom)
{
var has = VariablePropertyEditors.TryGetValue(item.Key, out var items);
if (has)
{
<Card IsShadow=true class="m-2 flex-fill" Color="Color.Primary">
<HeaderTemplate>
@{
GlobalData.ReadOnlyIdDevices.TryGetValue(item.Key, out var items);
<Card IsShadow=true class="m-2 flex-fill" Color="Color.Primary">
<HeaderTemplate>
@{
GlobalData.ReadOnlyIdDevices.TryGetValue(item.Key, out var items);
}
<div class="flex-fill">
@($"{items.Name} - {PluginServiceUtil.GetFileNameAndTypeName(items?.PluginName).TypeName}")
</div>
<Button OnClick=@((a)=>
{
Model.VariablePropertyModels.TryRemove(item.Key, out _);
}) class="mx-2" Color="Color.None" style="color: var(--bs-card-titlecolor);" Icon=@("fas fa-delete-left") />
</HeaderTemplate>
<BodyTemplate>
<ValidateForm Model="item.Value.Value" @ref=item.Value.ValidateForm
@key=@($"VariableEditValidateForm{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")
Id=@($"VariableEditValidateForm{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")>
<EditorFormObject class="p-2" Items=items AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 ShowLabelTooltip=true LabelWidth=150 Model="item.Value.Value" @key=@($"VariableEditEditorFormObject{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")>
</EditorFormObject>
</ValidateForm>
</BodyTemplate>
</Card>
}
<div class="flex-fill">
@($"{items.Name} - {PluginServiceUtil.GetFileNameAndTypeName(items?.PluginName).TypeName}")
</div>
<Button OnClick=@((a)=>
{
Model.VariablePropertyModels.TryRemove(item.Key,out _);
}) class="mx-2" Color="Color.None" style="color: var(--bs-card-titlecolor);" Icon=@("fas fa-delete-left") />
</HeaderTemplate>
<BodyTemplate>
<ValidateForm Model="item.Value.Value" @ref=item.Value.ValidateForm
@key=@($"VariableEditValidateForm{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")
Id=@($"VariableEditValidateForm{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")>
<EditorFormObject class="p-2" Items=items AutoGenerateAllItem="false" RowType=RowType.Inline ItemsPerRow=2 ShowLabelTooltip=true LabelWidth=150 Model="item.Value.Value" @key=@($"VariableEditEditorFormObject{item.Key}{Model.Id}{item.Value.Value.GetType().TypeHandle.Value}")>
</EditorFormObject>
</ValidateForm>
</BodyTemplate>
</Card>
}
else
{
@renderFragment
}
}
}
}
else
{
@renderFragment
}
}
}
</div>
</div>
</TabItem>
</TabItem>
}
</Tab>;
</Tab>;
}

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