using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.ModbusTcpMaster;
using HybirdFrameworkDriver.Session;
using HybirdFrameworkServices.Plc;
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)
{
break;
}
Thread.Sleep(5000);
}
ModbusSession modbusSession = new ModbusSession(master);
master.connectId = master.Ip + master.Port;
SessionMgr.RegisterModbusSession(master.connectId, modbusSession);
SessionMgr.SetAttrModbus(modbusSession, "eqm_sn", 1);
PlcInfo waterColdInfo = new PlcInfo(master.connectId, 1);
ChargerStaticInfo.PlcInfos.TryAdd(1, waterColdInfo);
}
/**
* 一直读
*/
private static void BatchReadPlc(ModbusTcpMaster master)
{
while (true)
{
int sn = 3; //(int)SessionMgr.GetAttrModbus(master.connectId, "eqm_sn");
ChargerStaticInfo.PlcInfos.TryGetValue(sn, out PlcInfo plcInfo);
if (plcInfo != null)
{
var bytes01 = master.BatchRead(1, 115);
if (bytes01 != null)
{
ModbusDecoder.Decode(bytes01, plcInfo.hostToPlc);
}
var bytes02 = master.BatchRead(201, 222);
if (bytes02 != null)
{
ModbusDecoder.Decode(bytes02, plcInfo.plcToHost);
}
var bytes03 = master.BatchRead(701, 10);
if (bytes03 != null)
{
ModbusDecoder.Decode(bytes03, plcInfo.plcFault);
}
//OperateResult result2 = ModbusTcpNet.Read("x=3;201", 222);
}
/*
if (plcInfo != null)
{
byte[]? bytes01 = master.BatchRead(0, 22);
if (bytes01 != null)
{
ModbusDecoder.DecodeByT(bytes01, plcInfo.PlcReadAndWritten2);
}
byte[]? bytes02 = master.BatchRead(256, 170);
if (bytes02 != null)
{
ModbusDecoder.DecodeByT(bytes02, plcInfo.PlcReadonly);
}
byte[]? bytes03 = master.BatchRead(39424, 108);
if (bytes03 != null)
{
ModbusDecoder.DecodeByT(bytes03, plcInfo.PlcTurnsRatio);
}
byte[]? bytes04 = master.BatchRead(40960, 3);//写编程使能。本机modbus地址。波特率
byte[]? bytes05 = master.BatchRead(2566, 1);//校验位
byte[]? bytes06 = master.BatchRead(42, 1);//秒脉冲/无功电能选择
byte[]? bytes07 = master.BatchRead(48, 1);//电流接线反向
byte[]? bytes08 = master.BatchRead(4576, 1);//电表清零
if (bytes04 != null)
{
ModbusDecoder.DecodeByT(bytes04, plcInfo.PlcReadAndWritten1);
}
plcInfo.PlcReadAndWritten1.CheckBit = master.ModbusTcpNet.ByteTransform.TransUInt16(bytes05, 0);
plcInfo.PlcReadAndWritten1.PulsePerSecond = master.ModbusTcpNet.ByteTransform.TransUInt16(bytes06, 0);
plcInfo.PlcReadAndWritten1.CurrentReversal = master.ModbusTcpNet.ByteTransform.TransUInt16(bytes07, 0);
plcInfo.PlcReadAndWritten1.MeterReset = master.ModbusTcpNet.ByteTransform.TransUInt16(bytes08, 0);
}
*/
}
}
}
}