第一步、modbus管理类开启委托
public class ModbusRtuMgr
{
static ModbusRtuMgr _inst;
ModbusRtuClient _rtuClient;
public bool active;
//开启委托回调
public Action<DataRequestOne> onGetRequestOne;
//单例模式
public static ModbusRtuMgr It
{
get
{
if (_inst == null)
_inst = new ModbusRtuMgr();
return _inst;
}
}
第二步、在readweigh 里定义委托的数据结构
public void ReadWeigh(string address)
{
float weigh = _rtuClient.ReadAddress(address);
//模拟通道称重数据
float[] weighList = _rtuClient.ReadAddresses(address);
for (int i = 0; i < weighList.Length; i++)
{
DataRequestOne one = new DataRequestOne();
one.ttime = 1;
one.pass = i+1;
one.weigh = weighList[i];
one.standWeigh = 90;
one.kickMin = 89;
one.kickMax = 101;
float per = Math.Abs(weigh - one.standWeigh) / one.standWeigh;
one.ngStatus = per < 0.05f ? 0 : 1;
bool kickFlag = (one.kickMin < weigh && weigh < one.kickMax);
one.kickStatus = kickFlag ? 0 : 1;
onGetRequestOne?.Invoke(one);
}
}
main class
第三步 、//开启线程循环读取 weight数组 启动那个方法
Task.Run(() =>
{
int count = 0;
//循环读取, 1秒一次
while (true)
{
ModbusRtuMgr.It.ReadWeigh("0");
Thread.Sleep(1000);
}
})
第四步 、定义数据处理方法 //预设给委托处理方法
private void HandleWeighData(DataRequestOne data)
{
int count = 0;
Console.WriteLine($"重量 {data.weigh}");
}
// 委托回调数据传到给这个方法 用等于号代表这个方法阻塞其他方法调用
ModbusRtuMgr.It.onGetRequestOne = HandleWeighData;