class Modbus::PDU

Base class modelling a Modbus PDU (Protocol Data Unit)

Constants

REQ_PDU_MAP

Maps the Modbus function code to the corresponding class (for request messages)

RSP_PDU_MAP

Maps the Modbus function code to the corresponding class (for response messages)

Attributes

creation_time[R]
func_code[R]

Public Class Methods

create(type, func_code, data) click to toggle source

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

@param type [Symbol] The type of PDU which should be created. Must be :request or :response. @param func_code [Integer] The modbus function code of the PDU @param data [Modbus::ProtocolData] The protocol data to decode. @return [Modbus::PDU] The created PDU instance.

# 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
new(data = nil, func_code = nil) click to toggle source

Initializes a new PDU instance. Decodes from protocol data if given.

@param data [Modbus::ProtocolData] The protocol data to decode. @param func_code [Fixnum] Modbus function code.

# File lib/modbus/pdu/pdu.rb, line 72
def initialize(data = nil, func_code = nil)
  @creation_time = Time.now.utc
  @func_code     = func_code || self.class::FUNC_CODE

  self.decode data if data
end

Public Instance Methods

encode() click to toggle source

Encodes a PDU into protocol data.

@return [Modbus::ProtocolData] The protocol data representation of this object.

# File lib/modbus/pdu/pdu.rb, line 84
def encode
  data = ProtocolData.new
  data.push_byte @func_code
  data
end