public void ModbusRequestRead(byte slaveAddress, UInt16 regAddress, UInt16 regNumber) { byte[] adu = ModbusADU.CreateRequestADU03(regAddress, regNumber); byte[] requestFrame = ModbusSerialPDU.CreatePDU(slaveAddress, adu); /*if (CommunicationThread!= null) * while (CommunicationThread.IsAlive) ;*/ ModbusParam param = new ModbusParam(regNumber * 2 + 5, requestFrame); Thread CommunicationThread = new Thread(ModbusSendReceive); CommunicationThread.Start(param); }
public void ModbusRequestWrite(byte slaveAddress, UInt16 regAddress, Int16[] values) { ushort[] uValues = new ushort[values.Length]; Buffer.BlockCopy(values, 0, uValues, 0, values.Length * 2); byte[] adu = ModbusADU.CreateRequestADU10(regAddress, uValues); byte[] requestFrame = ModbusSerialPDU.CreatePDU(slaveAddress, adu); /*if (CommunicationThread != null) * while (CommunicationThread.IsAlive) ;*/ Thread CommunicationThread = new Thread(ModbusSendReceive); ModbusParam param = new ModbusParam(8, requestFrame); CommunicationThread.Start(param); }
private void ModbusSendReceive(object param) { lock (this) { try { ModbusParam parameters; if (param is ModbusParam) { parameters = (ModbusParam)param; } else { throw new ModbusPDUException("Wrong parametrization of ModbusSendReceive method."); } byte[] responseFrame = new byte[(int)parameters.ResponseSize]; COMPort.DiscardInBuffer(); COMPort.Write(parameters.RequestADU, 0, parameters.RequestADU.Length); Thread.Sleep(ResponseWaitingDelay); COMPort.Read(responseFrame, 0, (int)parameters.ResponseSize); byte[] adu = ModbusSerialPDU.extractADU(responseFrame); if (responseFrame[1] > (byte)127) { throw new ModbusPDUException(String.Format("Modbus application error : function {0:X}, exception {1:X}", responseFrame[1], responseFrame[2])); } else if (responseFrame[1] == 0x03) { Int16[] values = GetValuesFromResponseADU03(adu); ModbusDataReceived(values); } } catch (Exception ex) { commException = ex; ModbusError(ex); } } }