/// <summary> /// 设置命令 /// </summary> /// <param name="address"></param> /// <param name="value"></param> /// <returns></returns> public bool SetBitValue(int address, int value) { //获取设置的命令 var command = PLCCommandFactory.SetBitCommand(address, value != 1); return(WriteDatas(command, 2000)); }
/// <summary> /// 读取数据的长度 /// </summary> /// <param name="address"></param> /// <param name="length"></param> /// <returns></returns> public byte[] ReadDataFromPLC(int address, int length, int timeOut) { if (!Monitor.TryEnter(_flag)) { throw new Exception("串口正在执行命令,请稍后"); } lock (_flag) { _dataRecv = null; if (null != _port && _port.IsOpen) { var command = PLCCommandFactory.GetReadCommand(address, length); _port.Write(command); Console.WriteLine($"向PLC发送数据"); CommandFactory.PrintBytes(command); } else { throw new Exception("请先打开串口"); } var index = 1; while (index < timeOut) { Thread.Sleep(1); index++; if (null != _dataRecv && _dataRecv.Length > 1) { var newBuffer = new byte[_dataRecv.Length]; Array.Copy(_dataRecv, 0, newBuffer, 0, _dataRecv.Length); //接受到应答数据 Console.WriteLine($"接受到PLC应答数据:{GetHexString(newBuffer)}"); if ((length * 2) + 4 != newBuffer.Length) { throw new Exception("接受到PLC应答数据的长度不对"); } //对接受到的数据进行解析 //if (!PLCCommandFactory.ValidateData(newBuffer)) //{ // throw new Exception("接受到的数据校验失败"); //} var datas = new byte[newBuffer.Length - 4]; Array.Copy(newBuffer, 1, datas, 0, datas.Length); return(HexStrToByteArray(Encoding.ASCII.GetString(datas))); } } throw new Exception("执行命令超时"); } }
public bool WriteDatasEx(int address, byte[] bytes, int timeOut) { if (!Monitor.TryEnter(_flag)) { throw new Exception("串口正在执行命令,请稍后"); } lock (_flag) { _dataRecv = null; if (null != _port && _port.IsOpen) { var command = PLCCommandFactory.GetWriteCommand(address, bytes); _port.Write(command); Console.WriteLine($"向PLC发送数据"); CommandFactory.PrintBytes(command); } else { throw new Exception("请先打开串口"); } var index = 1; while (index < timeOut) { Thread.Sleep(1); index++; if (null != _dataRecv && _dataRecv.Length > 0) { var newBuffer = new byte[_dataRecv.Length]; Array.Copy(_dataRecv, 0, newBuffer, 0, _dataRecv.Length); //接受到应答数据 Console.WriteLine($"接受到PLC应答数据 0x06--true 0x15---false :{GetHexString(newBuffer)}"); if (newBuffer[0] == 0x06) { return(true); } return(false); } } throw new Exception("执行命令超时"); } }