Model Bus通信在工业上比较常用,最近需要开发与西门子PLC的model bus通信,需要读写连续地址,逻辑看起来没有问题,代码调试还没有做
private short[] ReadModelBus(ushort[] channel, int[] IO, out string msg) //可以写入多个IO或WORD
{
msg = "";
if (channel == null)
{
msg = "channel不能为空!";
return null;
}
if (IO != null)
{
if (channel.Length != IO.Length)
{
msg = "channel和IO值不一致!";
return null;
}
}
ushort maxValue = channel.Max();
ushort minValue = channel.Min();
short[] datas = new short[maxValue - minValue];
int result = -1;
bool bResult = tcpip.ReadMultiWordData(minValue, (ushort)(maxValue - minValue), datas, out result); //读出从最小到最大channel的所有的数据
if (!bResult)
{
if (result == -1)
{
msg = "不能连接PLC!";
return null;
}
else if (result != 0)
{
msg = string.Format("Modbus TCP异常码={0:d02}", result);
return null;
}
}
if (IO == null)
{
short[] RET_VALUE = new short[channel.Length];
for (int i = 0; i < channel.Length; i++)
{
RET_VALUE[i] = (short)datas[channel[i] - minValue];
}
return RET_VALUE;
}
else
{
short[] RET_VALUE = new short[channel.Length];
for (int i = 0; i < channel.Length; i++)
{
RET_VALUE[i] = (short)((datas[channel[i] - minValue] >> IO[i]) & 0x0001);
}
return RET_VALUE;
}
}