[TestMethod] // Handling Request on Server public void WriteMultipleRegistersPDU_LifeCycle() { var RandomGen = new Random(); int Address = RandomGen.Next(MinAddress, MaxAddress); int Quantity = RandomGen.Next(MinQuantity, MaxQuantity); #region Build Server and Values var Server = new BaseModbusServer(); var Value = new int[Quantity]; for (int i = 0; i < Quantity; i++) { Value[i] = RandomGen.Next(0xFFFF); Server.AddHoldingRegister(Address + i); } #endregion var ClientPDU = new WriteMultipleRegistersPDU(Address, Value); var Request = ClientPDU.BuildRequest(); var ServerPDU = new WriteMultipleRegistersPDU(); var ReqStatus = ServerPDU.CheckRequest(Request); Assert.AreEqual(Status.OK, ReqStatus, "Recognition Error"); Assert.AreEqual(Address, ServerPDU.StartingAddress, "Whong Address recognition in CheckRequest"); ServerPDU.Handle(Server); CollectionAssert.AreEqual(Value, ServerPDU.Value, "Whong Address recognition in CheckRequest"); ClientPDU.CheckResponse(ServerPDU.BuildResponse()); CollectionAssert.AreEqual(Value, ClientPDU.Value, "Whong Address recognition in CheckRequest"); }
public Status CheckRequest(byte[] Request) { if (Request.Length < 13) return Status.Error; Header = new MBAP(Request); if (Header.ProtocolID != 0) return Status.Error; switch (Request[1]) { case 0x01: PDU = new ReadCoilsPDU(); break; case 0x02: PDU = new ReadDiscreteInputsPDU(); break; case 0x03: PDU = new ReadHoldingRegistersPDU(); break; case 0x04: PDU = new ReadInputRegistersPDU(); break; case 0x05: PDU = new WriteSingleCoilPDU(); break; case 0x06: PDU = new WriteSingleRegisterPDU(); break; case 0x0F: PDU = new WriteMultipleCoilsPDU(); break; case 0x10: PDU = new WriteMultipleRegistersPDU(); break; default: return Status.Error; } var PDURequest = new byte[Request.Length - 3]; for (int i=0; i<PDURequest.Length; i++) PDURequest[i] = Request[i + 1]; return PDU.CheckRequest(PDURequest); }
public Status CheckRequest(byte[] Request) { if ( (Request.Length < 4) || (Request[0] != Device.Address) ) // 3 = Address + FuncCode + CRC_Lo + CRC_Hi return Status.Error; if (CRC.Get(Request) != 0) return Status.Error; switch (Request[1]) { case 0x01: PDU = new ReadCoilsPDU(); break; case 0x02: PDU = new ReadDiscreteInputsPDU(); break; case 0x03: PDU = new ReadHoldingRegistersPDU(); break; case 0x04: PDU = new ReadInputRegistersPDU(); break; case 0x05: PDU = new WriteSingleCoilPDU(); break; case 0x06: PDU = new WriteSingleRegisterPDU(); break; case 0x0F: PDU = new WriteMultipleCoilsPDU(); break; case 0x10: PDU = new WriteMultipleRegistersPDU(); break; default: return Status.Error; } var PDURequest = new byte[Request.Length - 3]; for (int i=0; i<PDURequest.Length; i++) PDURequest[i] = Request[i + 1]; return PDU.CheckRequest(PDURequest); }