You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.7 KiB
99 lines
2.7 KiB
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;
|
|
using Service.Plc;
|
|
|
|
namespace Service
|
|
{
|
|
[Scope("SingleInstance")]
|
|
public class EquipmentInit
|
|
{
|
|
/// <summary>
|
|
/// 连接所有数据
|
|
/// </summary>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
public void Connect()
|
|
{
|
|
ConnectPlc();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 连接PLC
|
|
/// </summary>
|
|
/// <param name="param"></param>
|
|
/// <returns></returns>
|
|
public int ConnectPlc()
|
|
{
|
|
Thread thread = new Thread(() => ConnectPlcAsync());
|
|
thread.Start();
|
|
|
|
return 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 连接PLC
|
|
/// </summary>
|
|
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)
|
|
{
|
|
PlcMgr.ModbusTcpMaster = master;
|
|
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<HostToPlc>(bytes01, PlcMgr.HostToPlcData);
|
|
}
|
|
|
|
var bytes02 = master.BatchReadHolderRegister(201, 222);
|
|
if (bytes02 != null)
|
|
{
|
|
ModbusDecoder.Decode<PlcToHost>(bytes02, PlcMgr.PlcToHostData);
|
|
}
|
|
|
|
var bytes03 = master.BatchReadHolderRegister(701, 10);
|
|
if (bytes03 != null)
|
|
{
|
|
PlcApi.DataValidityTime = DateTime.Now;
|
|
ModbusDecoder.Decode<PlcFault>(bytes03, PlcMgr.PlcFaultData);
|
|
}
|
|
//OperateResult<byte[]> result2 = ModbusTcpNet.Read("x=3;201", 222);
|
|
}
|
|
}
|
|
}
|
|
} |