Files
2026-05-18 18:54:32 +08:00

62 lines
2.4 KiB
C#
Raw Permalink 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 Task<bool> CheckConnectionAsync() => Task.FromResult(_connected);
public bool IsConnected => _connected;
public Task<float> ReadFloatAsync(ushort startAddress)
{
// 模拟不同地址的数据
float value = startAddress switch
{
100 => 40 + (float)_rand.NextDouble() * 20, // 硬度 40~60N
410 => 4.0f, // 脆碎试验时间(min)
412 => 5.0f + (float)_rand.NextDouble() * 2, // 脆碎度前重
414 => 4.9f + (float)_rand.NextDouble() * 2, // 后重
300 => 37.0f, // 温度
400 => 50 + (float)_rand.NextDouble() * 30, // 转速
402 => 70 + (float)_rand.NextDouble() * 30, // 溶出度%
404 => 70 + (float)_rand.NextDouble() * 30, // 溶出2溶出度%
1430 => 37.0f, // 水浴温度
_ => 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 WriteFloatAsync(ushort startAddress, float 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);
}
}
}