设备线程内使用ManualResetEvent

This commit is contained in:
iioter 2023-10-21 22:14:18 +08:00
parent 4152b8c598
commit 64e950c52b

View File

@ -23,7 +23,7 @@ namespace Plugin
private Task? _task;
private readonly DateTime _tsStartDt = new(1970, 1, 1);
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private readonly object _lock = new();
private ManualResetEvent resetEvent = new(true);
public DeviceThread(Device device, IDriver driver, string projectId, MyMqttClient myMqttClient,
MqttServer mqttServer, ILogger logger)
@ -68,13 +68,12 @@ namespace Plugin
return;
}
lock (_lock)
{
resetEvent.WaitOne();
try
{
if (driver.IsConnected)
{
foreach (var deviceVariables in Device.DeviceVariables.Where(x=>x.ProtectType!= ProtectTypeEnum.WriteOnly).GroupBy(x => x.Alias))
foreach (var deviceVariables in Device.DeviceVariables.Where(x => x.ProtectType != ProtectTypeEnum.WriteOnly).GroupBy(x => x.Alias))
{
string deviceName = string.IsNullOrWhiteSpace(deviceVariables.Key)
? Device.DeviceName
@ -140,7 +139,7 @@ namespace Plugin
ret.CookedValue = ret.Value;
if(item.IsUpload)
if (item.IsUpload)
payLoad.Values[item.Name] = ret.CookedValue;
ret.VarId = item.ID;
@ -175,7 +174,7 @@ namespace Plugin
payLoad.TS = (long)(DateTime.UtcNow - _tsStartDt).TotalMilliseconds;
if (deviceVariables.Where(x=>x.IsUpload&&x.ProtectType!=ProtectTypeEnum.WriteOnly).All(x => x.StatusType == VaribaleStatusTypeEnum.Good))
if (deviceVariables.Where(x => x.IsUpload && x.ProtectType != ProtectTypeEnum.WriteOnly).All(x => x.StatusType == VaribaleStatusTypeEnum.Good))
{
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
sendModel[deviceName] = new List<PayLoad> { payLoad };
@ -224,7 +223,6 @@ namespace Plugin
{
_logger.LogError(ex, $"线程循环异常,{Device.DeviceName}");
}
}
Thread.Sleep(Device.DeviceVariables!.Any() ? (int)Driver.MinPeriod : 10000);
@ -255,8 +253,8 @@ namespace Plugin
//执行写入变量RPC
if (e.Method.ToLower() == "write")
{
lock (_lock)
{
resetEvent.Reset();
bool rpcConnected = false;
//没连接就连接
if (!Driver.IsConnected)
@ -278,7 +276,7 @@ namespace Plugin
deviceVariable = Device.DeviceVariables.FirstOrDefault(x =>
x.Name == para.Key && x.Alias == e.DeviceName);
if (deviceVariable != null&& deviceVariable.ProtectType!= ProtectTypeEnum.ReadOnly)
if (deviceVariable != null && deviceVariable.ProtectType != ProtectTypeEnum.ReadOnly)
{
DriverAddressIoArgModel ioArgModel = new()
{
@ -309,7 +307,7 @@ namespace Plugin
rpcResponse.IsSuccess = false;
rpcResponse.Description = $"{e.DeviceName} 连接失败";
}
}
resetEvent.Set();
}
//其他RPC TODO
else