ModbusServer添加自定义循环间隔,修复中间变量写入

This commit is contained in:
Kimdiego2098
2023-07-20 10:55:17 +08:00
parent b045557ce1
commit 11ba21c9a8
3 changed files with 32 additions and 4 deletions

View File

@@ -59,7 +59,20 @@ public class ModbusServer : UpLoadBase
await _plc.WriteAsync(item.Item1, item.Item2.DataType, item.Item2.Value?.ToString(), cancellationToken);
}
}
await Task.Delay(100, cancellationToken);
if (driverPropertys.CycleInterval > UploadDeviceThread.CycleInterval + 50)
{
try
{
await Task.Delay(driverPropertys.CycleInterval - UploadDeviceThread.CycleInterval, cancellationToken);
}
catch
{
}
}
else
{
}
}
public override OperResult IsConnected()
@@ -160,9 +173,21 @@ public class ModbusServer : UpLoadBase
GetPropertyValue(tag.Value, nameof(variablePropertys.VariableRpcEnable)).ToBoolean()
&& driverPropertys.DeviceRpcEnable;
if (!enable) return new OperResult("不允许写入");
var result = await RpcCore.InvokeDeviceMethodAsync($"{nameof(ModbusServer)}-{CurDevice.Name}-{client.IP + ":" + client.Port}",
new(tag.Value.Name, thingsGatewayBitConverter.GetDynamicDataFormBytes(tag.Value.VariableAddress, tag.Value.DataType, bytes).ToString()), CancellationToken.None);
return result;
var type = GetPropertyValue(tag.Value, nameof(ModbusServerVariableProperty.ModbusType));
if (Enum.TryParse<DataTypeEnum>(type, out DataTypeEnum result))
{
var result1 = await RpcCore.InvokeDeviceMethodAsync($"{nameof(ModbusServer)}-{CurDevice.Name}-{client.IP + ":" + client.Port}",
new(tag.Value.Name, thingsGatewayBitConverter.GetDynamicDataFormBytes(tag.Value.VariableAddress ?? string.Empty, result.GetSystemType(), bytes).ToString()), CancellationToken.None);
return result1;
}
else
{
var result1 = await RpcCore.InvokeDeviceMethodAsync($"{nameof(ModbusServer)}-{CurDevice.Name}-{client.IP + ":" + client.Port}",
new(tag.Value.Name, thingsGatewayBitConverter.GetDynamicDataFormBytes(tag.Value.VariableAddress ?? string.Empty, tag.Value.DataType, bytes).ToString()), CancellationToken.None);
return result1;
}
}
catch (Exception ex)
{

View File

@@ -34,4 +34,5 @@ public class ModbusServerProperty : UpDriverPropertyBase
public DataFormat DataFormat { get; set; }
[DeviceProperty("允许写入", "")]
public bool DeviceRpcEnable { get; set; }
[DeviceProperty("线程循环间隔", "最小10ms")] public int CycleInterval { get; set; } = 100;
}

View File

@@ -344,6 +344,8 @@ public static class ReadWriteDevicesExHelpers
/// </summary>
public static object GetDynamicDataFormBytes(this IThingsGatewayBitConverter thingsGatewayBitConverter, string address, Type type, byte[] bytes, int offset = 0)
{
if (address == null)
address = string.Empty;
if (type == typeof(bool))
return thingsGatewayBitConverter.GetBoolDataFormBytes(address, bytes, offset);
else if (type == typeof(byte))