Files
CSI-Z420-Tablet-Multi-Funct…/Services/PlcSimulator.cs
2026-05-15 11:13:06 +08:00

55 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Threading.Tasks;
namespace TabletTester2025.Services
{
public class PlcSimulator : IPlcService
{
private Random _rand = new Random();
private bool _connected = true;
public Task ConnectAsync() => Task.CompletedTask;
public bool IsConnected => _connected;
public Task<float> ReadFloatAsync(ushort startAddress)
{
// 模拟不同地址的数据
float value = startAddress switch
{
100 => 40 + (float)_rand.NextDouble() * 20, // 硬度 40~60N
200 => 5.0f + (float)_rand.NextDouble() * 2, // 脆碎度前重
202 => 4.9f + (float)_rand.NextDouble() * 2, // 后重
300 => 37.0f, // 温度
400 => 50 + (float)_rand.NextDouble() * 30, // 转速
402 => 70 + (float)_rand.NextDouble() * 30, // 溶出度%
_ => 0
};
return Task.FromResult(value);
}
// 👇 新增 ReadIntAsync 的模拟实现
public Task<int> ReadIntAsync(ushort startAddress)
{
// 模拟整数返回比如返回0-1000之间的随机数
return Task.FromResult(_rand.Next(0, 1000));
}
public Task WriteCoilAsync(ushort coilAddress, bool value) => Task.CompletedTask;
public Task<bool> ReadCoilAsync(ushort coilAddress)
{
// 模拟完成信号:随机返回 true/false
return Task.FromResult(_rand.Next(2) == 1);
}
public Task WriteRegisterAsync(ushort registerAddress, ushort value) => Task.CompletedTask;
public Task<ushort[]> ReadHoldingRegistersAsync(ushort startAddress, ushort count)
{
var data = new ushort[count];
for (int i = 0; i < count; i++)
data[i] = (ushort)_rand.Next(0, 65535);
return Task.FromResult(data);
}
}
}