Method: Modbus::PDU.create

Defined in:
lib/modbus/pdu/pdu.rb

.create(type, func_code, data) ⇒ Modbus::PDU

Factory method for creating PDUs. Decodes a PDU from protocol data and returns a new PDU instance.

Parameters:

  • type (Symbol)

    The type of PDU which should be created. Must be :request or :response.

  • func_code (Integer)

    The modbus function code of the PDU

  • data (Modbus::ProtocolData)

    The protocol data to decode.

Returns:



55
56
57
58
59
60
61
62
63
64
# File 'lib/modbus/pdu/pdu.rb', line 55

def self.create(type, func_code, data)
  map = { :request => REQ_PDU_MAP, :response => RSP_PDU_MAP }[type]
  fail ArgumentError, "Type is expected to be :request or :response, got #{type}" unless map

  # 0x80 is the offset in case of a modbus exception
  klass = func_code > 0x80 ? PDU::Exception : map[func_code]
  fail IllegalFunction, "Unknown function code 0x#{func_code.to_s(16)}" if klass.nil?

  klass.new data, func_code
end