class Modbus::TCPADU

ADU (Application Data Unit) for transport over TCP

Attributes

pdu[RW]
protocol_ident[RW]
transaction_ident[RW]
unit_ident[RW]

Public Class Methods

new(pdu = nil, transaction_ident = 0) click to toggle source

Initializes a new TCPADU instance.

@param pdu [Modbus::PDU] A PDU to preset in the ADU.

# File lib/modbus/adu/tcp_adu.rb, line 17
def initialize(pdu = nil, transaction_ident = 0)
  @transaction_ident = transaction_ident
  @protocol_ident    = 0
  @unit_ident        = 0xFF # TODO configurable?
  @pdu               = pdu
end

Public Instance Methods

decode(type, buffer, conn) click to toggle source

Decodes an ADU from wire format and sets the attributes of this object.

@param type [Symbol] The type of PDU which should be created. @param buffer [String] The bytes to decode. @param conn [Modbus::Connection::Base] An EM connection object to work on. @return [true, false] True, if there where enough bytes in the buffer and decoding was successful.

# File lib/modbus/adu/tcp_adu.rb, line 47
def decode(type, buffer, conn)
  data = ProtocolData.new buffer

  # not enough data in buffer to know the length
  return false if data.size < 6

  @transaction_ident = data.shift_word
  @protocol_ident    = data.shift_word
  length             = data.shift_word

  # not enough data in buffer according to length
  return false if data.size < length

  # Strip the consumed bytes off the buffer, thus NOT consumed bytes remain in the buffer!
  buffer.slice!(0..length + 5)

  @unit_ident = data.shift_byte
  func_code   = data.shift_byte
  @pdu        = PDU.create type, func_code, data

  return true

rescue ModbusError => error
  pdu = PDU::Exception.create func_code, error
  adu = TCPADU.new pdu, @transaction_ident
  conn.send_data adu.encode

  return false
end
encode() click to toggle source

Encodes the ADU into the wire format.

@return [String] The encoded ADU.

# File lib/modbus/adu/tcp_adu.rb, line 29
def encode
  data = ProtocolData.new
  data.push_word @transaction_ident
  data.push_word @protocol_ident
  data.push_word @pdu.length + 1
  data.push_byte @unit_ident
  data.concat @pdu.encode
  data.to_buffer
end