110,539
社区成员
发帖
与我相关
我的任务
分享
private void frmMain_Load(object sender, EventArgs e)
{
proc();
}
private void proc()
{
timer = new System.Threading.Timer(h =>
{
if (enableComm)
{
foreach (var s in Session.Stations)
{
var station = Session.Stations.Find(p => p.Id == s.Id);
if (station.IsWorking == true)
{
if (!comm.COMMStates.ContainsKey(station.Id))
{
comm.COMMStates[station.Id] = new COMMState()
{
Station = station,
Data = new byte[250],
StationErrNum = 0,
Exception = null,
TcpClient = null
};
}
ThreadPool.QueueUserWorkItem(x => ThreadPollCallback(comm.COMMStates[station.Id]));
}
}
}
},null,0,1000);
}
public void ThreadPollCallback(object state)
{
var cs = state as COMMState;
if (cs == null) return;
var station = cs.Station;
//防止在connect 过程中再次连接,因为下位机只允许3个连接
if (cs.COMMUNICATION_STATE == COMMUNICATIONSTATE.连接&&cs.TriesNum>=3)
{
lock (lockObj)
{
cs.Exception = new Exception("communication timeout");
}
return;
}
cs.Thread = Thread.CurrentThread;
try
{
//连接
if (cs.TcpClient == null || !cs.TcpClient.Connected)
{
lock (lockObj)
{
cs.COMMUNICATION_STATE = COMMUNICATIONSTATE.连接;
cs.TriesNum++;
}
cs.TcpClient = new TcpClient(cs.Station.IP, 502);
}
TcpClient tc = cs.TcpClient;
lock (lockObj)
{
cs.COMMUNICATION_STATE = COMMUNICATIONSTATE.开始;
}
//读数据,实际就是write之后read
ModbusIpMaster master = ModbusIpMaster.CreateIp(tc);
ushort startAddress = 0;
ushort numInputs = 125;
ushort[] res = master.ReadHoldingRegisters(startAddress, numInputs);
lock (lockObj)
{
//处理数据,保存到数据库
cs.COMMUNICATION_STATE = COMMUNICATIONSTATE.完成;
}
}
catch (Exception e)
{
cs.COMMUNICATION_STATE = COMMUNICATIONSTATE.故障;
}
finally
{
}
}