using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ModbusTcpMaster;
using HybirdFrameworkDriver.Session;
using HybirdFrameworkServices.Plc;
using Newtonsoft.Json.Linq;
using Service.Execute.Api;
using Service.Init.Entity;
namespace Service
{
[Scope("SingleInstance")]
public class EquipmentInit
{
///
/// 连接所有数据
///
///
public void Connect()
{
ConnectPlc();
}
///
/// 连接PLC
///
///
///
public int ConnectPlc()
{
Thread thread = new Thread(() => ConnectPlcAsync());
thread.Start();
return 0;
}
///
/// 连接PLC
///
private void ConnectPlcAsync()
{
bool connected = false;
ModbusTcpMaster master = null;
//PLC连接
while (!connected)
{
master = new ModbusTcpMaster()
{
Ip = "172.0.20.66",
Port = 502,
};
master.ReadAction = BatchReadPlc; //启动线程一直读
master.Duration = 3000;
connected = master.Connect();
if (connected)
{
PlcApi.master = master;
PlcApi.con = true;
break;
}
Thread.Sleep(5000);
}
}
/**
* 一直读
*/
private static void BatchReadPlc(ModbusTcpMaster master)
{
if (PlcApi.con)
{
var bytes01 = master.BatchReadHolderRegister(1, 115);
if (bytes01 != null)
{
PlcApi.DataValidityTime = DateTime.Now;
ModbusDecoder.Decode(bytes01, PlcApi.hostToPlc);
}
var bytes02 = master.BatchReadHolderRegister(201, 222);
if (bytes02 != null)
{
ModbusDecoder.Decode(bytes02, PlcApi.plcToHost);
}
var bytes03 = master.BatchReadHolderRegister(701, 10);
if (bytes03 != null)
{
PlcApi.DataValidityTime = DateTime.Now;
ModbusDecoder.Decode(bytes03, PlcApi.plcFault);
}
//OperateResult result2 = ModbusTcpNet.Read("x=3;201", 222);
}
}
}
}