Compare commits

...

10 Commits

Author SHA1 Message Date
Diego
b40ca920d3 fix: 变量自动刷新运行态 2025-06-20 16:58:45 +08:00
Diego
5a4b0a0e93 修改插件过期提示 2025-06-20 14:43:13 +08:00
Diego
a879edd68b 10.8.12 2025-06-20 13:52:42 +08:00
Diego
62e0a6ee9d gitee登录按钮隐藏 2025-06-19 17:04:22 +08:00
Diego
765e5564d4 10.8.10 2025-06-19 16:56:04 +08:00
Diego
10eecac19b feat: 优化设备状态逻辑 2025-06-19 11:41:43 +08:00
Diego
59241b8faa fix: opcua插件订阅检查失效 2025-06-19 10:42:54 +08:00
Diego
52b3097f04 10.8.7 2025-06-18 22:04:48 +08:00
Diego
d922296b70 feat: 重构插件任务 2025-06-18 17:11:57 +08:00
Diego
aec91da28b 10.8.2
feat: 优化闭包导致的状态机内存占用,高并发时内存显著下降
fix(sqldb): 定时上传模式时,实时表时效
fix(taos): 初始化失败
2025-06-17 17:09:05 +08:00
114 changed files with 1738 additions and 1417 deletions

View File

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

View File

@@ -81,7 +81,7 @@ public class HardwareJob : IJob, IHardwareJob
{
if (HardwareInfo.MachineInfo == null)
{
await MachineInfo.RegisterAsync().ConfigureAwait(false);
MachineInfo.Register();
HardwareInfo.MachineInfo = MachineInfo.Current;
string currentPath = Directory.GetCurrentDirectory();

View File

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

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

View File

@@ -33,6 +33,12 @@
<None Remove="$(SolutionDir)..\README.md" Pack="false" PackagePath="\" />
<None Remove="$(SolutionDir)..\README.zh-CN.md" Pack="false" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,14 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Import Project="$(SolutionDir)Version.props" />
<Import Project="$(SolutionDir)PackNuget.props" />
<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<Version>$(SourceGeneratorVersion)</Version>
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BootstrapBlazor.FontAwesome" Version="9.0.2" />
<PackageReference Include="BootstrapBlazor" Version="9.7.3" />
<PackageReference Include="BootstrapBlazor" Version="9.7.4-beta09" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
</ItemGroup>
@@ -31,10 +29,10 @@
</ItemGroup>
<ItemGroup Condition="'$(Configuration)' != 'Debug' ">
<!--<ItemGroup Condition="'$(Configuration)' != 'Debug' ">
<None Include="..\BlazorSetParametersAsyncGenerator\tools\*.ps1" PackagePath="tools" Pack="true" Visible="false" />
<None Include="..\BlazorSetParametersAsyncGenerator\bin\$(Configuration)\netstandard2.0\BlazorSetParametersAsyncGenerator.dll" PackagePath="analyzers\dotnet\cs" Pack="true" Visible="false" />
</ItemGroup>
</ItemGroup>-->
<ItemGroup>
<ProjectReference Include="..\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />

View File

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

View File

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

View File

@@ -1,10 +1,10 @@
<Project>
<PropertyGroup>
<PluginVersion>10.8.1</PluginVersion>
<ProPluginVersion>10.8.1</ProPluginVersion>
<PluginVersion>10.8.14</PluginVersion>
<ProPluginVersion>10.8.14</ProPluginVersion>
<AuthenticationVersion>2.8.0</AuthenticationVersion>
<SourceGeneratorVersion>10.8.0</SourceGeneratorVersion>
<SourceGeneratorVersion>10.8.2</SourceGeneratorVersion>
<NET8Version>8.0.17</NET8Version>
<NET9Version>9.0.6</NET9Version>
</PropertyGroup>

View File

@@ -7,8 +7,8 @@
<!--<UseRazorSourceGenerator>false</UseRazorSourceGenerator>-->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />
<!--<ProjectReference Include="..\..\Admin\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />-->
<!--<PackageReference Include="ThingsGateway.Razor" Version="$(SourceGeneratorVersion)" />-->
<ProjectReference Include="..\..\Admin\ThingsGateway.Razor\ThingsGateway.Razor.csproj" />
<ProjectReference Include="..\ThingsGateway.Foundation\ThingsGateway.Foundation.csproj" />
</ItemGroup>
@@ -22,8 +22,10 @@
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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;
}
@@ -141,11 +137,9 @@ public abstract class CollectFoundationBase : CollectBase
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)
@@ -216,12 +210,4 @@ public abstract class CollectFoundationBase : CollectBase
}
}
private sealed class ReadResultCount
{
public int deviceMethodsVariableFailedNum = 0;
public int deviceMethodsVariableSuccessNum = 0;
public int deviceSourceVariableFailedNum = 0;
public int deviceSourceVariableSuccessNum = 0;
}
}

View File

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

View File

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

View File

@@ -55,7 +55,7 @@
"ThingsGateway.Management.Authentication": {
"AuthName": "AuthName",
"Authorized": "Authorized",
"ExpireTime": "ExpireTime",
"ExpireTime": "ExpireTime {0}",
"Password": "Password",
"Register": "Register",
"RegisterStatus": "RegisterStatus",
@@ -298,11 +298,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 +373,7 @@
"ThingsGateway.Gateway.Application.DriverBase": {
"Authorized": "Authorized",
"ExpireTime": "ExpireTime",
"ExpireTime": "ExpireTime {0}",
"Unauthorized": "Unauthorized"
},
"ThingsGateway.Gateway.Application.ExportString": {

View File

@@ -53,7 +53,7 @@
"ThingsGateway.Management.Authentication": {
"AuthName": "公司名称",
"Authorized": "已授权",
"ExpireTime": "过期时间",
"ExpireTime": "过期时间 {0}",
"Password": "注册码",
"Register": "注册",
"RegisterStatus": "注册状态",
@@ -297,11 +297,9 @@
},
"ThingsGateway.Gateway.Application.CollectPropertyBase": {
"ConcurrentCount": "最大并发数量",
"ReIntervalTime": "离线恢复时间",
"RetryCount": "失败重试次数"
},
"ThingsGateway.Gateway.Application.CollectPropertyRetryBase": {
"ReIntervalTime": "离线恢复时间",
"RetryCount": "失败重试次数"
},
"ThingsGateway.Gateway.Application.ControlController": {
@@ -376,7 +374,7 @@
"ThingsGateway.Gateway.Application.DriverBase": {
"Authorized": "已授权",
"ExpireTime": "过期时间",
"ExpireTime": "过期时间 {0}",
"Unauthorized": "未授权"
},
"ThingsGateway.Gateway.Application.ExportString": {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ public interface IActuatorNode : INode
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

@@ -168,14 +168,14 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
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);
}
@@ -205,11 +205,15 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
dispatchService.Dispatch(null);
_ = Task.Factory.StartNew(async () =>
_ = Task.Factory.StartNew(async (state) =>
{
if (state is not Dictionary<RulesLog, Diagram> diagrams)
{
return;
}
while (!cancellationToken.IsCancellationRequested)
{
foreach (var item in Diagrams?.Values?.SelectMany(a => a.Nodes) ?? new List<NodeModel>())
foreach (var item in diagrams?.Values?.SelectMany(a => a.Nodes) ?? new List<NodeModel>())
{
if (item is IExexcuteExpressionsBase)
{
@@ -218,7 +222,7 @@ internal sealed class RulesEngineHostedService : BackgroundService, IRulesEngine
}
await Task.Delay(60000, cancellationToken).ConfigureAwait(false);
}
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
}, Diagrams, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
}

View File

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

@@ -27,7 +27,9 @@
<PropertyGroup>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>
</Project>

View File

@@ -6,10 +6,6 @@
"Url": "/",
"Text": "首页"
},
{
"Url": "/des",
"Text": "DES"
},
{
"Text": "Modbus",
"Items": [

View File

@@ -45,6 +45,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Admin\BlazorSetParametersAsyncGenerator\BlazorSetParametersAsyncGenerator.csproj" PrivateAssets="all" OutputItemType="Analyzer" />
</ItemGroup>

View File

@@ -44,7 +44,7 @@ public class Dlt645_2007Master : DtuServiceDeviceBase
/// <param name="dateTime">时间</param>
/// <param name="cancellationToken">取消令箭</param>
/// <returns></returns>
public async ValueTask<OperResult> BroadcastTimeAsync(DateTime dateTime, CancellationToken cancellationToken = default)
public ValueTask<OperResult> BroadcastTimeAsync(DateTime dateTime, CancellationToken cancellationToken = default)
{
try
{
@@ -53,40 +53,30 @@ public class Dlt645_2007Master : DtuServiceDeviceBase
dAddress.Station = str.HexStringToBytes();
dAddress.DataId = "999999999999".HexStringToBytes();
return await Dlt645SendAsync(dAddress, ControlCode.BroadcastTime, FEHead, cancellationToken: cancellationToken).ConfigureAwait(false);
return Dlt645SendAsync(dAddress, ControlCode.BroadcastTime, FEHead, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
return new OperResult(ex);
return EasyValueTask.FromResult(new OperResult(ex));
}
}
/// <inheritdoc/>
public async ValueTask<OperResult<byte[]>> Dlt645RequestAsync(Dlt645_2007Address dAddress, ControlCode controlCode, string feHead, byte[] codes = default, string[] datas = default, CancellationToken cancellationToken = default)
public ValueTask<OperResult<byte[]>> Dlt645RequestAsync(Dlt645_2007Address dAddress, ControlCode controlCode, string feHead, byte[] codes = default, string[] datas = default, CancellationToken cancellationToken = default)
{
try
{
return await SendThenReturnAsync(GetSendMessage(dAddress, controlCode, feHead, codes, datas), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
return new OperResult<byte[]>(ex);
}
return SendThenReturnAsync(GetSendMessage(dAddress, controlCode, feHead, codes, datas), cancellationToken);
}
/// <inheritdoc/>
public async ValueTask<OperResult> Dlt645SendAsync(Dlt645_2007Address dAddress, ControlCode controlCode, string feHead, byte[] codes = default, string[] datas = default, CancellationToken cancellationToken = default)
public ValueTask<OperResult> Dlt645SendAsync(Dlt645_2007Address dAddress, ControlCode controlCode, string feHead, byte[] codes = default, string[] datas = default, CancellationToken cancellationToken = default)
{
try
{
return await SendAsync(GetSendMessage(dAddress, controlCode, feHead, codes, datas), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
return new OperResult<byte[]>(ex);
}
return SendAsync(GetSendMessage(dAddress, controlCode, feHead, codes, datas), cancellationToken);
}
/// <summary>
@@ -147,7 +137,7 @@ public class Dlt645_2007Master : DtuServiceDeviceBase
/// <inheritdoc/>
public override List<T> LoadSourceRead<T>(IEnumerable<IVariable> deviceVariables, int maxPack, string defaultIntervalTime)
{
return PackHelper.LoadSourceRead<T>(this, deviceVariables, maxPack, defaultIntervalTime);
return PackHelper.LoadSourceRead<T>(this, deviceVariables, maxPack, Station, defaultIntervalTime);
}
/// <inheritdoc/>
@@ -163,7 +153,19 @@ public class Dlt645_2007Master : DtuServiceDeviceBase
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
public override ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default)
{
if (state is Dlt645_2007Address dlt645_2007Address)
{
return Dlt645RequestAsync(dlt645_2007Address, ControlCode.Read, FEHead, cancellationToken: cancellationToken);
}
else
{
return EasyValueTask.FromResult(new OperResult<byte[]>(new ArgumentException("State must be of type Dlt645_2007Address", nameof(state))));
}
}
/// <summary>
/// 读取通信地址
/// </summary>
@@ -231,16 +233,16 @@ public class Dlt645_2007Master : DtuServiceDeviceBase
}
/// <inheritdoc/>
public override async ValueTask<OperResult> WriteAsync(string address, string value, IThingsGatewayBitConverter bitConverter = null, CancellationToken cancellationToken = default)
public override ValueTask<OperResult> WriteAsync(string address, string value, IThingsGatewayBitConverter bitConverter = null, CancellationToken cancellationToken = default)
{
try
{
string[] strArray = value.SplitStringBySemicolon();
return await WriteAsync(address, value, bitConverter, cancellationToken).ConfigureAwait(false);
return WriteAsync(address, value, bitConverter, cancellationToken);
}
catch (Exception ex)
{
return new OperResult<byte[]>(ex);
return EasyValueTask.FromResult(new OperResult(ex));
}
}

View File

@@ -11,7 +11,6 @@
using System.Text;
using ThingsGateway.Foundation.Extension.String;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Extension;
namespace ThingsGateway.Foundation.Dlt645;
@@ -40,10 +39,10 @@ public class Dlt645_2007Address : Dlt645_2007Request
/// </summary>
public static Dlt645_2007Address ParseFrom(string address, string defaultStation = null, bool isCache = true)
{
var cacheKey = $"{nameof(ParseFrom)}_{typeof(Dlt645_2007Address).FullName}_{typeof(Dlt645_2007Address).TypeHandle.Value}_{address}_{defaultStation}";
if (isCache)
if (MemoryCache.Instance.TryGetValue(cacheKey, out Dlt645_2007Address dAddress))
return new(dAddress);
//var cacheKey = $"{nameof(ParseFrom)}_{typeof(Dlt645_2007Address).FullName}_{typeof(Dlt645_2007Address).TypeHandle.Value}_{address}_{defaultStation}";
//if (isCache)
// if (MemoryCache.Instance.TryGetValue(cacheKey, out Dlt645_2007Address dAddress))
// return new(dAddress);
Dlt645_2007Address dlt645_2007Address = new();
if (!string.IsNullOrEmpty(defaultStation))
@@ -78,10 +77,11 @@ public class Dlt645_2007Address : Dlt645_2007Request
}
}
if (isCache)
MemoryCache.Instance.Set(cacheKey, dlt645_2007Address, 3600);
//if (isCache)
// MemoryCache.Instance.Set(cacheKey, dlt645_2007Address, 3600);
return new(dlt645_2007Address);
return dlt645_2007Address;
//return new(dlt645_2007Address);
}
public void SetDataId(string dataId)

View File

@@ -18,9 +18,10 @@ internal static class PackHelper
/// <param name="device"></param>
/// <param name="deviceVariables"></param>
/// <param name="maxPack">最大打包长度</param>
/// <param name="station">station</param>
/// <param name="defaultIntervalTime">默认间隔时间</param>
/// <returns></returns>
public static List<T> LoadSourceRead<T>(IDevice device, IEnumerable<IVariable> deviceVariables, int maxPack, string defaultIntervalTime) where T : IVariableSource, new()
public static List<T> LoadSourceRead<T>(IDevice device, IEnumerable<IVariable> deviceVariables, int maxPack, string station, string defaultIntervalTime) where T : IVariableSource, new()
{
var byteConverter = device.ThingsGatewayBitConverter;
var result = new List<T>();
@@ -42,8 +43,9 @@ internal static class PackHelper
var r = new T()
{
RegisterAddress = item.Key!,
AddressObject = Dlt645_2007Address.ParseFrom(item.Key, station),
Length = 1,
TimeTick = new(string.IsNullOrWhiteSpace(item.FirstOrDefault().IntervalTime) ? defaultIntervalTime : item.FirstOrDefault().IntervalTime),
IntervalTime = string.IsNullOrWhiteSpace(item.FirstOrDefault().IntervalTime) ? defaultIntervalTime : item.FirstOrDefault().IntervalTime,
};
r.AddVariableRange(item);
result.Add(r);

View File

@@ -11,7 +11,6 @@
using System.Text;
using ThingsGateway.Foundation.Extension.String;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Extension;
namespace ThingsGateway.Foundation.Modbus;
@@ -68,10 +67,10 @@ public class ModbusAddress : ModbusRequest
public static ModbusAddress? ParseFrom(string address, byte? station = null, bool isCache = true)
{
if (string.IsNullOrWhiteSpace(address)) { return null; }
var cacheKey = $"{nameof(ParseFrom)}_{typeof(ModbusAddress).FullName}_{typeof(ModbusAddress).TypeHandle.Value}_{station}_{address}";
if (isCache)
if (MemoryCache.Instance.TryGetValue(cacheKey, out ModbusAddress mAddress))
return new(mAddress);
//var cacheKey = $"{nameof(ParseFrom)}_{typeof(ModbusAddress).FullName}_{typeof(ModbusAddress).TypeHandle.Value}_{station}_{address}";
//if (isCache)
// if (MemoryCache.Instance.TryGetValue(cacheKey, out ModbusAddress mAddress))
// return new(mAddress);
var modbusAddress = new ModbusAddress();
if (station != null)
@@ -103,10 +102,11 @@ public class ModbusAddress : ModbusRequest
}
}
if (isCache)
MemoryCache.Instance.Set(cacheKey, modbusAddress, 3600);
//if (isCache)
// MemoryCache.Instance.Set(cacheKey, modbusAddress, 3600);
return new(modbusAddress);
//return new(modbusAddress);
return modbusAddress;
void Address(string address)
{

View File

@@ -8,7 +8,6 @@
// QQ群605534569
//------------------------------------------------------------------------------
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension;
namespace ThingsGateway.Foundation.Modbus;
@@ -165,9 +164,10 @@ public static class PackHelper
// 创建一个新的变量源读取对象
T sourceRead = new()
{
TimeTick = new TimeTick(intervalTime),
IntervalTime = intervalTime,
// 将当前组打包地址中的起始地址作为实际打包报文中的起始地址
RegisterAddress = startAddress.ToString(),
AddressObject = new ModbusAddress(startAddress) { Length = (ushort)sourceLen },
Length = sourceLen.ToInt()
};

View File

@@ -98,31 +98,64 @@ public partial class ModbusMaster : DtuServiceDeviceBase, IModbusAddress
return PackHelper.LoadSourceRead<T>(this, deviceVariables, maxPack, defaultIntervalTime, Station);
}
public async ValueTask<OperResult<byte[]>> ModbusRequestAsync(ModbusAddress mAddress, bool read, CancellationToken cancellationToken = default)
public override ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default)
{
try
{
return await SendThenReturnAsync(GetSendMessage(mAddress, read),
cancellationToken).ConfigureAwait(false);
if (state is ModbusAddress mAddress)
{
return ModbusReadAsync(mAddress, cancellationToken);
}
else
{
return EasyValueTask.FromResult(new OperResult<byte[]>(new ArgumentException("State must be of type ModbusAddress", nameof(state))));
}
}
catch (Exception ex)
{
return new OperResult<byte[]>(ex);
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
public ValueTask<OperResult<byte[]>> ModbusReadAsync(ModbusAddress mAddress, CancellationToken cancellationToken = default)
{
try
{
return SendThenReturnAsync(GetSendMessage(mAddress, true),
cancellationToken);
}
catch (Exception ex)
{
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
public ValueTask<OperResult<byte[]>> ModbusRequestAsync(ModbusAddress mAddress, bool read, CancellationToken cancellationToken = default)
{
try
{
return SendThenReturnAsync(GetSendMessage(mAddress, read),
cancellationToken);
}
catch (Exception ex)
{
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
/// <inheritdoc/>
public override async ValueTask<OperResult<byte[]>> ReadAsync(string address, int length, CancellationToken cancellationToken = default)
public override ValueTask<OperResult<byte[]>> ReadAsync(string address, int length, CancellationToken cancellationToken = default)
{
try
{
var mAddress = GetModbusAddress(address, Station);
mAddress.Length = (ushort)length;
return await ModbusRequestAsync(mAddress, true, cancellationToken).ConfigureAwait(false);
return ModbusRequestAsync(mAddress, true, cancellationToken);
}
catch (Exception ex)
{
return new OperResult<byte[]>(ex);
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}

View File

@@ -310,6 +310,34 @@ public class ModbusSlave : DeviceBase, IModbusAddress
return EasyValueTask.FromResult(new OperResult<byte[]>(result));
}
}
public override ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default)
{
try
{
if (state is ModbusAddress mAddress)
{
var result = ModbusRequest(mAddress, true, cancellationToken);
if (result.IsSuccess)
{
return EasyValueTask.FromResult(new OperResult<byte[]>() { Content = result.Content.ToArray() });
}
else
{
return EasyValueTask.FromResult(new OperResult<byte[]>(result));
}
}
else
{
return EasyValueTask.FromResult(new OperResult<byte[]>(new ArgumentException("State must be of type ModbusAddress", nameof(state))));
}
}
catch (Exception ex)
{
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
public virtual ModbusAddress GetModbusAddress(string address, byte? station, bool isCache = true)
{
var mAddress = ModbusAddress.ParseFrom(address, station, isCache);

View File

@@ -12,7 +12,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes" Version="1.5.376.213" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes" Version="1.5.376.232" />
</ItemGroup>
<ItemGroup>

View File

@@ -11,7 +11,6 @@
using System.Text;
using ThingsGateway.Foundation.Extension.String;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Collections;
using ThingsGateway.NewLife.Extension;
@@ -144,10 +143,10 @@ public class SiemensS7Address : S7Request
public static SiemensS7Address ParseFrom(string address, bool isCache = true)
{
if (string.IsNullOrWhiteSpace(address)) { return null; }
var cacheKey = $"{nameof(ParseFrom)}_{typeof(SiemensS7Address).FullName}_{typeof(SiemensS7Address).TypeHandle.Value}_{address}";
if (isCache)
if (MemoryCache.Instance.TryGetValue(cacheKey, out SiemensS7Address sAddress))
return new(sAddress);
//var cacheKey = $"{nameof(ParseFrom)}_{typeof(SiemensS7Address).FullName}_{typeof(SiemensS7Address).TypeHandle.Value}_{address}";
//if (isCache)
// if (MemoryCache.Instance.TryGetValue(cacheKey, out SiemensS7Address sAddress))
// return new(sAddress);
SiemensS7Address s7AddressData = new();
address = address.ToUpper();
@@ -276,8 +275,8 @@ public class SiemensS7Address : S7Request
}
}
if (isCache)
MemoryCache.Instance.Set(cacheKey, new SiemensS7Address(s7AddressData), 3600);
//if (isCache)
// MemoryCache.Instance.Set(cacheKey, new SiemensS7Address(s7AddressData), 3600);
return s7AddressData;
}

View File

@@ -228,8 +228,9 @@ internal static class PackHelper
T sourceRead = new() // 创建一个新的源读取对象
{
TimeTick = new(intervalTime), // 设置时间戳
IntervalTime = intervalTime, // 设置时间戳
RegisterAddress = tempAddresses.OrderBy(it => it.AddressStart).First().ToString(), // 获取地址并按地址排序
AddressObject = new SiemensS7Address(tempAddresses.OrderBy(it => it.AddressStart).First()) { Length = sourceLen },
Length = sourceLen // 设置源长度
};

View File

@@ -298,6 +298,26 @@ public partial class SiemensS7Master : DeviceBase
}
}
public override ValueTask<OperResult<byte[]>> ReadAsync(object state, CancellationToken cancellationToken = default)
{
try
{
if (state is SiemensS7Address sAddress)
{
return S7ReadAsync([sAddress], cancellationToken);
}
else
{
return EasyValueTask.FromResult(new OperResult<byte[]>(new ArgumentException("State must be of type SiemensS7Address", nameof(state))));
}
}
catch (Exception ex)
{
return EasyValueTask.FromResult(new OperResult<byte[]>(ex));
}
}
/// <inheritdoc/>
public override async ValueTask<OperResult> WriteAsync(string address, byte[] value, DataTypeEnum dataType, CancellationToken cancellationToken = default)
{

View File

@@ -25,7 +25,7 @@ namespace ThingsGateway.Plugin.QuestDB;
/// <summary>
/// QuestDBProducer
/// </summary>
public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableModel<QuestDBHistoryValue>, IDBHistoryValueService
public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>, IDBHistoryValueService
{
internal readonly RealDBProducerProperty _driverPropertys = new();
private readonly QuestDBProducerVariableProperty _variablePropertys = new();
@@ -180,7 +180,8 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override async Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await UpdateVarModelMemory(cancellationToken).ConfigureAwait(false);
await UpdateVarModelsMemory(cancellationToken).ConfigureAwait(false);

View File

@@ -23,11 +23,11 @@ namespace ThingsGateway.Plugin.QuestDB;
/// <summary>
/// RabbitMQProducer
/// </summary>
public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableModel<QuestDBHistoryValue>
public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>
{
private TypeAdapterConfig _config;
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<QuestDBHistoryValue>> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<VariableBasicData>> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item.Select(a => a.Value).OrderBy(a => a.Id), cancellationToken);
}
@@ -41,7 +41,7 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
UpdateVariable(variableRuntime, variable);
base.VariableChange(variableRuntime, variable);
}
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<QuestDBHistoryValue> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item, cancellationToken);
}
@@ -56,18 +56,18 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
foreach (var group in varGroup)
{
AddQueueVarModel(new CacheDBItem<List<QuestDBHistoryValue>>(group.Adapt<List<QuestDBHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(group.ToList()));
}
foreach (var variable in varList)
{
AddQueueVarModel(new CacheDBItem<QuestDBHistoryValue>(variable.Adapt<QuestDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
else
{
foreach (var variable in variables)
{
AddQueueVarModel(new CacheDBItem<QuestDBHistoryValue>(variable.Adapt<QuestDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
}
@@ -78,15 +78,15 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
if (_driverPropertys.GroupUpdate && !variable.BusinessGroup.IsNullOrEmpty() && VariableRuntimeGroups.TryGetValue(variable.BusinessGroup, out var variableRuntimeGroup))
{
AddQueueVarModel(new CacheDBItem<List<QuestDBHistoryValue>>(variableRuntimeGroup.Adapt<List<QuestDBHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(variableRuntimeGroup.Adapt<List<VariableBasicData>>(_config)));
}
else
{
AddQueueVarModel(new CacheDBItem<QuestDBHistoryValue>(variableRuntime.Adapt<QuestDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<QuestDBHistoryValue> item, CancellationToken cancellationToken)
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
var result = await InserableAsync(item.WhereIf(_driverPropertys.OnlineFilter, a => a.IsOnline == true).ToList(), cancellationToken).ConfigureAwait(false);
if (success != result.IsSuccess)
@@ -101,7 +101,7 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
#region
private async ValueTask<OperResult> InserableAsync(List<QuestDBHistoryValue> dbInserts, CancellationToken cancellationToken)
private async ValueTask<OperResult> InserableAsync(List<VariableBasicData> dbInserts, CancellationToken cancellationToken)
{
try
{
@@ -118,8 +118,8 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
{
Stopwatch stopwatch = new();
stopwatch.Start();
var result = await _db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表
var data = dbInserts.Adapt<List<QuestDBHistoryValue>>();
var result = await _db.Insertable(data).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表
stopwatch.Stop();
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);

View File

@@ -25,7 +25,7 @@ namespace ThingsGateway.Plugin.SqlDB;
/// <summary>
/// SqlDBProducer
/// </summary>
public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<SQLHistoryValue>, IDBHistoryValueService
public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>, IDBHistoryValueService
{
internal readonly SqlDBProducerProperty _driverPropertys = new();
private readonly SqlDBProducerVariableProperty _variablePropertys = new();
@@ -172,8 +172,15 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
.Map(dest => dest.Value, src => src.Value == null ? string.Empty : src.Value.ToString() ?? string.Empty)
.Map(dest => dest.CreateTime, (src) => DateTime.Now);
if (_businessPropertyWithCacheInterval.BusinessUpdateEnum == BusinessUpdateEnum.Interval && _driverPropertys.IsReadDB)
{
GlobalData.VariableValueChangeEvent += VariableValueChange;
}
await base.InitChannelAsync(channel, cancellationToken).ConfigureAwait(false);
}
public override Task AfterVariablesChangedAsync(CancellationToken cancellationToken)
{
@@ -220,7 +227,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override async Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
if (_driverPropertys.IsReadDB)
{
@@ -229,7 +236,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
var varList = RealTimeVariables.ToListWithDequeue();
if (varList.Count > 0)
{
var result = await UpdateAsync(varList.Adapt<List<SQLRealValue>>(), cancellationToken).ConfigureAwait(false);
var result = await UpdateAsync(varList, cancellationToken).ConfigureAwait(false);
if (success != result.IsSuccess)
{
if (!result.IsSuccess)

View File

@@ -24,13 +24,13 @@ namespace ThingsGateway.Plugin.SqlDB;
/// <summary>
/// SqlDBProducer
/// </summary>
public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<SQLHistoryValue>
public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>
{
private TypeAdapterConfig _config;
private volatile bool _initRealData;
private ConcurrentDictionary<long, VariableBasicData> RealTimeVariables { get; } = new ConcurrentDictionary<long, VariableBasicData>();
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<SQLHistoryValue>> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<VariableBasicData>> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item.Select(a => a.Value).OrderBy(a => a.Id), cancellationToken);
}
@@ -48,7 +48,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
UpdateVariable(variableRuntime, variable);
base.VariableChange(variableRuntime, variable);
}
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<SQLHistoryValue> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item, cancellationToken);
}
@@ -62,18 +62,18 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
foreach (var group in varGroup)
{
AddQueueVarModel(new CacheDBItem<List<SQLHistoryValue>>(group.Adapt<List<SQLHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(group.ToList()));
}
foreach (var variable in varList)
{
AddQueueVarModel(new CacheDBItem<SQLHistoryValue>(variable.Adapt<SQLHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
else
{
foreach (var variable in variables)
{
AddQueueVarModel(new CacheDBItem<SQLHistoryValue>(variable.Adapt<SQLHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
}
@@ -85,12 +85,12 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
if (_driverPropertys.GroupUpdate && !variable.BusinessGroup.IsNullOrEmpty() && VariableRuntimeGroups.TryGetValue(variable.BusinessGroup, out var variableRuntimeGroup))
{
AddQueueVarModel(new CacheDBItem<List<SQLHistoryValue>>(variableRuntimeGroup.Adapt<List<SQLHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(variableRuntimeGroup.Adapt<List<VariableBasicData>>(_config)));
}
else
{
AddQueueVarModel(new CacheDBItem<SQLHistoryValue>(variableRuntime.Adapt<SQLHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
@@ -101,7 +101,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
}
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<SQLHistoryValue> item, CancellationToken cancellationToken)
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
var result = await InserableAsync(item.WhereIf(_driverPropertys.OnlineFilter, a => a.IsOnline == true).ToList(), cancellationToken).ConfigureAwait(false);
if (success != result.IsSuccess)
@@ -116,7 +116,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
#region
private async ValueTask<OperResult> InserableAsync(List<SQLHistoryValue> dbInserts, CancellationToken cancellationToken)
private async ValueTask<OperResult> InserableAsync(List<VariableBasicData> dbInserts, CancellationToken cancellationToken)
{
try
{
@@ -134,8 +134,8 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
{
Stopwatch stopwatch = new();
stopwatch.Start();
var result = await _db.Fastest<SQLHistoryValue>().PageSize(50000).SplitTable().BulkCopyAsync(dbInserts).ConfigureAwait(false);
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
var data = dbInserts.Adapt<List<SQLHistoryValue>>(_config);
var result = await _db.Fastest<SQLHistoryValue>().PageSize(50000).SplitTable().BulkCopyAsync(data).ConfigureAwait(false);
stopwatch.Stop();
if (result > 0)
{
@@ -152,7 +152,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
}
}
private async ValueTask<OperResult> UpdateAsync(List<SQLRealValue> datas, CancellationToken cancellationToken)
private async ValueTask<OperResult> UpdateAsync(List<VariableBasicData> datas, CancellationToken cancellationToken)
{
try
{
@@ -190,7 +190,8 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
Stopwatch stopwatch = new();
stopwatch.Start();
var result = await _db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkUpdateAsync(datas).ConfigureAwait(false);
var data = datas.Adapt<List<SQLRealValue>>(_config);
var result = await _db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkUpdateAsync(data).ConfigureAwait(false);
stopwatch.Stop();
if (result > 0)

View File

@@ -43,7 +43,7 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
_db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
_db = BusinessDatabaseUtil.GetDb((DbType)_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
_config.ForType<AlarmVariable, HistoryAlarm>().Map(dest => dest.Id, (src) => CommonUtils.GetSingleId());
GlobalData.AlarmChangedEvent -= AlarmWorker_OnAlarmChanged;
@@ -91,9 +91,9 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
return base.ProtectedStartAsync(cancellationToken);
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await Update(cancellationToken).ConfigureAwait(false);
return Update(cancellationToken);
}
#region
@@ -112,7 +112,7 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
internal ISugarQueryable<HistoryAlarm> Query(DBHistoryAlarmPageInput input)
{
using var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
using var db = BusinessDatabaseUtil.GetDb((DbType)_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
var query = db.Queryable<HistoryAlarm>().AS(_driverPropertys.TableName)
.WhereIF(input.StartTime != null, a => a.EventTime >= input.StartTime)
.WhereIF(input.EndTime != null, a => a.EventTime <= input.EndTime)
@@ -132,7 +132,7 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
internal async Task<QueryData<HistoryAlarm>> QueryData(QueryPageOptions option)
{
using var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
using var db = BusinessDatabaseUtil.GetDb((DbType)_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
var ret = new QueryData<HistoryAlarm>()
{
IsSorted = option.SortOrder != SortOrder.Unset,

View File

@@ -13,7 +13,7 @@ using Mapster;
using System.Diagnostics;
using ThingsGateway.Foundation;
using ThingsGateway.NewLife.Threading;
using ThingsGateway.Plugin.DB;
using TouchSocket.Core;
@@ -56,38 +56,6 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
}
}
private async ValueTask<OperResult> InserableAsync(List<HistoryAlarm> dbInserts, CancellationToken cancellationToken)
{
try
{
int result = 0;
//.SplitTable()
Stopwatch stopwatch = new();
stopwatch.Start();
if (_db.CurrentConnectionConfig.DbType == SqlSugar.DbType.QuestDB)
result = await _db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表
else
result = await _db.Fastest<HistoryAlarm>().AS(_driverPropertys.TableName).PageSize(50000).BulkCopyAsync(dbInserts).ConfigureAwait(false);
stopwatch.Stop();
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
if (result > 0)
{
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
LogMessage?.Trace($"Count{dbInserts.Count}watchTime: {stopwatch.ElapsedMilliseconds} ms");
}
return OperResult.Success;
}
catch (Exception ex)
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
return new OperResult(ex);
}
}
private async ValueTask<OperResult> UpdateT(IEnumerable<HistoryAlarm> item, CancellationToken cancellationToken)
{
var result = await InserableAsync(item.ToList(), cancellationToken).ConfigureAwait(false);
@@ -100,4 +68,51 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
return result;
}
private async ValueTask<OperResult> InserableAsync(List<HistoryAlarm> dbInserts, CancellationToken cancellationToken)
{
try
{
_db.Ado.CancellationToken = cancellationToken;
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
{
var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
getDeviceModel.Logger = LogMessage;
await getDeviceModel.DBInsertable(_db, dbInserts, cancellationToken).ConfigureAwait(false);
}
else
{
int result = 0;
//.SplitTable()
Stopwatch stopwatch = new();
stopwatch.Start();
if (_db.CurrentConnectionConfig.DbType == SqlSugar.DbType.QuestDB)
result = await _db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);
else
result = await _db.Fastest<HistoryAlarm>().AS(_driverPropertys.TableName).PageSize(50000).BulkCopyAsync(dbInserts).ConfigureAwait(false);
stopwatch.Stop();
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
if (result > 0)
{
LogMessage?.Trace($"Count{dbInserts.Count}watchTime: {stopwatch.ElapsedMilliseconds} ms");
}
return OperResult.Success;
}
return OperResult.Success;
}
catch (Exception ex)
{
return new OperResult(ex);
}
}
}

View File

@@ -12,7 +12,8 @@ using BootstrapBlazor.Components;
using System.ComponentModel.DataAnnotations;
using ThingsGateway.SqlSugar;
using ThingsGateway.Plugin.SqlDB;
namespace ThingsGateway.Plugin.SqlHistoryAlarm;
@@ -23,15 +24,21 @@ public class SqlHistoryAlarmProperty : BusinessPropertyWithCache
{
[DynamicProperty]
public DbType DbType { get; set; } = DbType.SqlServer;
[DynamicProperty]
[Required]
public string TableName { get; set; } = "historyAlarm";
[DynamicProperty]
[Required]
[AutoGenerateColumn(ComponentType = typeof(Textarea), Rows = 1)]
public string BigTextConnectStr { get; set; } = "server=.;uid=sa;pwd=111111;database=test;";
/// <summary>
/// 历史表脚本
/// </summary>
[DynamicProperty]
[Required]
public string TableName { get; set; } = "historyAlarm";
[AutoGenerateColumn(Visible = true, IsVisibleWhenEdit = false, IsVisibleWhenAdd = false)]
public string? BigTextScriptHistoryTable { get; set; }
public override bool OnlineFilter { get; set; } = false;
}

View File

@@ -29,7 +29,7 @@ namespace ThingsGateway.Plugin.TDengineDB;
/// <summary>
/// TDengineDBProducer
/// </summary>
public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableModel<TDengineDBHistoryValue>, IDBHistoryValueService
public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>, IDBHistoryValueService
{
internal readonly RealDBProducerProperty _driverPropertys = new()
{
@@ -199,7 +199,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override async Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await UpdateVarModelMemory(cancellationToken).ConfigureAwait(false);
await UpdateVarModelsMemory(cancellationToken).ConfigureAwait(false);

View File

@@ -26,11 +26,11 @@ namespace ThingsGateway.Plugin.TDengineDB;
/// <summary>
/// RabbitMQProducer
/// </summary>
public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableModel<TDengineDBHistoryValue>
public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableModel<VariableBasicData>
{
private TypeAdapterConfig _config;
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<TDengineDBHistoryValue>> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModel(IEnumerable<CacheDBItem<VariableBasicData>> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item.Select(a => a.Value).OrderBy(a => a.Id), cancellationToken);
}
@@ -46,7 +46,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
UpdateVariable(variableRuntime, variable);
base.VariableChange(variableRuntime, variable);
}
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<TDengineDBHistoryValue> item, CancellationToken cancellationToken)
protected override ValueTask<OperResult> UpdateVarModels(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
return UpdateVarModel(item, cancellationToken);
}
@@ -59,18 +59,18 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
foreach (var group in varGroup)
{
AddQueueVarModel(new CacheDBItem<List<TDengineDBHistoryValue>>(group.Adapt<List<TDengineDBHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(group.ToList()));
}
foreach (var variable in varList)
{
AddQueueVarModel(new CacheDBItem<TDengineDBHistoryValue>(variable.Adapt<TDengineDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
else
{
foreach (var variable in variables)
{
AddQueueVarModel(new CacheDBItem<TDengineDBHistoryValue>(variable.Adapt<TDengineDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
}
@@ -80,15 +80,15 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
if (_driverPropertys.GroupUpdate && !variable.BusinessGroup.IsNullOrEmpty() && VariableRuntimeGroups.TryGetValue(variable.BusinessGroup, out var variableRuntimeGroup))
{
AddQueueVarModel(new CacheDBItem<List<TDengineDBHistoryValue>>(variableRuntimeGroup.Adapt<List<TDengineDBHistoryValue>>(_config)));
AddQueueVarModel(new CacheDBItem<List<VariableBasicData>>(variableRuntimeGroup.Adapt<List<VariableBasicData>>(_config)));
}
else
{
AddQueueVarModel(new CacheDBItem<TDengineDBHistoryValue>(variableRuntime.Adapt<TDengineDBHistoryValue>(_config)));
AddQueueVarModel(new CacheDBItem<VariableBasicData>(variable));
}
}
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<TDengineDBHistoryValue> item, CancellationToken cancellationToken)
private async ValueTask<OperResult> UpdateVarModel(IEnumerable<VariableBasicData> item, CancellationToken cancellationToken)
{
var result = await InserableAsync(item.WhereIf(_driverPropertys.OnlineFilter, a => a.IsOnline == true).ToList(), cancellationToken).ConfigureAwait(false);
if (success != result.IsSuccess)
@@ -103,7 +103,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
#region
private async ValueTask<OperResult> InserableAsync(List<TDengineDBHistoryValue> dbInserts, CancellationToken cancellationToken)
private async ValueTask<OperResult> InserableAsync(List<VariableBasicData> dbInserts, CancellationToken cancellationToken)
{
try
{

View File

@@ -63,9 +63,8 @@ public class Dlt645_2007Master : CollectFoundationBase
}
/// <inheritdoc/>
protected override async Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
protected override Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
{
await Task.CompletedTask.ConfigureAwait(false);
return _plc.LoadSourceRead<VariableSourceRead>(deviceVariables, 0, CurrentDevice.IntervalTime);
return Task.FromResult(_plc.LoadSourceRead<VariableSourceRead>(deviceVariables, 0, CurrentDevice.IntervalTime));
}
}

View File

@@ -23,9 +23,9 @@ public partial class Webhook : BusinessBaseWithCacheIntervalScript<VariableBasic
/// <inheritdoc/>
public override bool IsConnected() => success;
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await Update(cancellationToken).ConfigureAwait(false);
return Update(cancellationToken);
}

View File

@@ -87,9 +87,9 @@ public partial class KafkaProducer : BusinessBaseWithCacheIntervalScript<Variabl
base.Dispose(disposing);
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await Update(cancellationToken).ConfigureAwait(false);
return Update(cancellationToken);
}
}

View File

@@ -77,14 +77,13 @@ public class ModbusMaster : CollectFoundationBase
}
/// <inheritdoc/>
protected override async Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
protected override Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
{
await Task.CompletedTask.ConfigureAwait(false);
List<VariableSourceRead> variableSourceReads = new();
foreach (var deviceVariable in deviceVariables.GroupBy(a => a.CollectGroup))
{
variableSourceReads.AddRange(_plc.LoadSourceRead<VariableSourceRead>(deviceVariable, _driverPropertys.MaxPack, CurrentDevice.IntervalTime));
}
return variableSourceReads;
return Task.FromResult(variableSourceReads);
}
}

View File

@@ -19,7 +19,6 @@ using ThingsGateway.Gateway.Application;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension;
using ThingsGateway.NewLife.Json.Extension;
using ThingsGateway.NewLife.Threading;
using ThingsGateway.SqlSugar;
using TouchSocket.Core;
@@ -150,17 +149,11 @@ public class ModbusSlave : BusinessBase
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override async Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
//获取设备连接状态
if (IsConnected())
if (!IsConnected())
{
//更新设备活动时间
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
try
{
if (cancellationToken.IsCancellationRequested)
@@ -233,7 +226,7 @@ public class ModbusSlave : BusinessBase
}
else
{
var data = thingsGatewayBitConverter.GetDataFormBytes(_plc, addressStr, writeData, 0, dType, item.Value.ArrayLength ?? 1);
_ = thingsGatewayBitConverter.GetChangedDataFormBytes(_plc, addressStr, writeData, 0, dType, item.Value.ArrayLength ?? 1, null, out var data);
var result = await item.Value.RpcAsync(data.ToSystemTextJsonString(), $"{nameof(ModbusSlave)}-{CurrentDevice.Name}-{$"{channel}"}").ConfigureAwait(false);

View File

@@ -176,7 +176,7 @@ public partial class MqttClient : BusinessBaseWithCacheIntervalScript<VariableBa
}
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override async Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
var clientResult = await TryMqttClientAsync(cancellationToken).ConfigureAwait(false);
if (!clientResult.IsSuccess)

View File

@@ -16,7 +16,6 @@ using MQTTnet.Client;
#endif
using ThingsGateway.Foundation;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
@@ -98,9 +97,8 @@ public partial class MqttCollect : CollectBase
}
}
protected override async Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
protected override Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
{
await Task.CompletedTask.ConfigureAwait(false);
TopicItemDict.Clear();
if (deviceVariables.Count > 0)
{
@@ -128,7 +126,7 @@ public partial class MqttCollect : CollectBase
TopicItemDict[group.Key] = new();
var sourVars = new VariableSourceRead()
{
TimeTick = new("1000"),
IntervalTime = "1000",
RegisterAddress = group.Key,
};
foreach (var item in group)
@@ -170,11 +168,11 @@ public partial class MqttCollect : CollectBase
_mqttSubscribeOptions = mqttClientSubscribeOptions;
}
return dataResult;
return Task.FromResult(dataResult);
}
else
{
return new();
return Task.FromResult(new List<VariableSourceRead>());
}
}
@@ -230,11 +228,12 @@ public partial class MqttCollect : CollectBase
{
try
{
var now = DateTime.Now;
foreach (var item in IdVariableRuntimes)
{
if (DateTime.Now - item.Value.CollectTime > ETime)
if (now - item.Value.CollectTime > ETime)
{
item.Value.SetValue(null, DateTime.Now, false);
item.Value.SetValue(null, now, false);
}
}
}
@@ -260,7 +259,18 @@ public partial class MqttCollect : CollectBase
private volatile bool success;
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override bool VariableSourceReadsEnable => false;
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
var list = base.ProtectedGetTasks(cancellationToken);
var check = ScheduledTaskHelper.GetTask("3000", CheckAsync, null, LogMessage, cancellationToken);
list.Add(check);
return list;
}
private async Task CheckAsync(object? state, CancellationToken cancellationToken)
{
var clientResult = await TryMqttClientAsync(cancellationToken).ConfigureAwait(false);
if (!clientResult.IsSuccess)
@@ -276,18 +286,6 @@ public partial class MqttCollect : CollectBase
await Task.Delay(10000, cancellationToken).ConfigureAwait(false);
//return;
}
//获取设备连接状态
if (IsConnected())
{
//更新设备活动时间
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
ScriptVariableRun(cancellationToken);
}

View File

@@ -102,9 +102,9 @@ public partial class MqttServer : BusinessBaseWithCacheIntervalScript<VariableBa
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
protected override Task ProtectedExecuteAsync(object? state, CancellationToken cancellationToken)
{
await Update(cancellationToken).ConfigureAwait(false);
return Update(cancellationToken);
}
}

View File

@@ -14,7 +14,6 @@ using ThingsGateway.Foundation.OpcDa;
using ThingsGateway.Foundation.OpcDa.Da;
using ThingsGateway.Gateway.Application;
using ThingsGateway.NewLife.Json.Extension;
using ThingsGateway.NewLife.Threading;
using TouchSocket.Core;
@@ -90,34 +89,11 @@ public class OpcDaMaster : CollectBase
}
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
{
if (_driverProperties.ActiveSubscribe)
{
//获取设备连接状态
if (IsConnected())
{
//更新设备活动时间
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
}
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
ScriptVariableRun(cancellationToken);
}
else
{
await base.ProtectedExecuteAsync(cancellationToken).ConfigureAwait(false);
}
}
protected override bool VariableSourceReadsEnable => !_driverProperties.ActiveSubscribe;
/// <inheritdoc/>
protected override async Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
protected override Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
{
await Task.CompletedTask.ConfigureAwait(false);
try
{
if (deviceVariables.Count > 0)
@@ -132,7 +108,7 @@ public class OpcDaMaster : CollectBase
{
var read = new VariableSourceRead()
{
TimeTick = new(_driverProperties.UpdateRate.ToString()),
IntervalTime = _driverProperties.UpdateRate.ToString(),
RegisterAddress = it.Key,
};
HashSet<string> ids = new(it.Value.Select(b => b.ItemID));
@@ -146,11 +122,11 @@ public class OpcDaMaster : CollectBase
}).ToList();
variableSourceReads.AddRange(sourVars);
}
return variableSourceReads;
return Task.FromResult(variableSourceReads);
}
else
{
return new();
return Task.FromResult(new List<VariableSourceRead>());
}
}
finally

View File

@@ -16,7 +16,6 @@ using Opc.Ua.Client;
using ThingsGateway.Foundation.Extension.Generic;
using ThingsGateway.Foundation.OpcUa;
using ThingsGateway.Gateway.Application;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Json.Extension;
using ThingsGateway.NewLife.Threading;
@@ -102,15 +101,30 @@ public class OpcUaMaster : CollectBase
{
return _plc?.GetAddressDescription();
}
protected override bool VariableSourceReadsEnable => !_driverProperties.ActiveSubscribe;
protected override List<IScheduledTask> ProtectedGetTasks(CancellationToken cancellationToken)
{
var list = base.ProtectedGetTasks(cancellationToken);
private TimeTick checkTimeTick = new("60000");
protected override async ValueTask ProtectedExecuteAsync(CancellationToken cancellationToken)
var check = ScheduledTaskHelper.GetTask("3000", CheckAsync, null, LogMessage, cancellationToken);
list.Add(check);
var checkConnec = ScheduledTaskHelper.GetTask("10000", CheckConnectAsync, null, LogMessage, cancellationToken);
list.Add(checkConnec);
return list;
}
protected override async Task ProtectedStartAsync(CancellationToken cancellationToken)
{
await CheckConnectAsync(null, cancellationToken).ConfigureAwait(false);
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);
}
private async Task CheckConnectAsync(object? state, CancellationToken cancellationToken)
{
if (_plc.Session == null)
{
try
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
if (_plc.Session == null)
await _plc.ConnectAsync(cancellationToken).ConfigureAwait(false);
}
@@ -120,69 +134,61 @@ public class OpcUaMaster : CollectBase
LogMessage?.LogWarning(ex, "Connect Fail");
connectFirstFailLoged = true;
CurrentDevice.SetDeviceStatus(TimerX.Now, true, ex.Message);
await Task.Delay(10000, cancellationToken).ConfigureAwait(false);
CurrentDevice.SetDeviceStatus(TimerX.Now, null, ex.Message);
}
}
if (_driverProperties.ActiveSubscribe)
}
private async Task CheckAsync(object? state, CancellationToken cancellationToken)
{
if (_plc.Session != null)
{
//获取设备连接状态
if (IsConnected())
if (_driverProperties.ActiveSubscribe)
{
//更新设备活动时间
CurrentDevice.SetDeviceStatus(TimerX.Now, false);
if (checkTimeTick.IsTickHappen())
//获取设备连接状态
if (IsConnected())
{
//如果是订阅模式,连接时添加订阅组
if (_plc.OpcUaProperty?.ActiveSubscribe == true && CurrentDevice.VariableSourceReads.Count > 0 && _plc.Session.SubscriptionCount < CurrentDevice.VariableSourceReads.Count)
//更新设备活动时间
{
try
{
foreach (var variableSourceRead in CurrentDevice.VariableSourceReads)
//如果是订阅模式,连接时添加订阅组
if (_plc.OpcUaProperty?.ActiveSubscribe == true && CurrentDevice.VariableSourceReads.Count > 0 && _plc.Session.SubscriptionCount < CurrentDevice.VariableSourceReads.Count)
{
try
{
if (_plc.Session.Subscriptions.FirstOrDefault(a => a.DisplayName == variableSourceRead.RegisterAddress) == null)
foreach (var variableSourceRead in CurrentDevice.VariableSourceReads)
{
await _plc.AddSubscriptionAsync(variableSourceRead.RegisterAddress, variableSourceRead.VariableRuntimes.Where(a => !a.RegisterAddress.IsNullOrEmpty()).Select(a => a.RegisterAddress!).ToHashSet().ToArray(), _plc.OpcUaProperty.LoadType, cancellationToken).ConfigureAwait(false);
if (_plc.Session.Subscriptions.FirstOrDefault(a => a.DisplayName == variableSourceRead.RegisterAddress) == null)
{
await _plc.AddSubscriptionAsync(variableSourceRead.RegisterAddress, variableSourceRead.VariableRuntimes.Where(a => !a.RegisterAddress.IsNullOrEmpty()).Select(a => a.RegisterAddress!).ToHashSet().ToArray(), _plc.OpcUaProperty.LoadType, cancellationToken).ConfigureAwait(false);
LogMessage?.LogInformation($"AddSubscription index {CurrentDevice.VariableSourceReads.IndexOf(variableSourceRead)} done");
LogMessage?.LogInformation($"AddSubscription index {CurrentDevice.VariableSourceReads.IndexOf(variableSourceRead)} done");
}
}
LogMessage?.LogInformation("AddSubscriptions done");
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, "AddSubscriptions");
}
finally
{
}
LogMessage?.LogInformation("AddSubscriptions done");
}
catch (Exception ex)
{
LogMessage?.LogWarning(ex, "AddSubscriptions");
}
finally
{
}
}
}
}
else
{
CurrentDevice.SetDeviceStatus(TimerX.Now, true);
}
ScriptVariableRun(cancellationToken);
}
else
{
await base.ProtectedExecuteAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc/>
protected override async Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
protected override Task<List<VariableSourceRead>> ProtectedLoadSourceReadAsync(List<VariableRuntime> deviceVariables)
{
await Task.CompletedTask.ConfigureAwait(false);
if (deviceVariables.Count > 0)
{
List<VariableSourceRead> variableSourceReads = new List<VariableSourceRead>();
@@ -194,7 +200,7 @@ public class OpcUaMaster : CollectBase
{
var sourVars = new VariableSourceRead()
{
TimeTick = new(_driverProperties.UpdateRate.ToString()),
IntervalTime = _driverProperties.UpdateRate.ToString(),
RegisterAddress = Guid.NewGuid().ToString(),
};
foreach (var item in variable)
@@ -205,11 +211,11 @@ public class OpcUaMaster : CollectBase
}
}
return variableSourceReads;
return Task.FromResult(variableSourceReads);
}
else
{
return new();
return Task.FromResult(new List<VariableSourceRead>());
}
}

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