Class: Modbus::ProtocolData

Inherits:
Array
  • Object
show all
Defined in:
lib/modbus/connection/protocol_data.rb

Overview

Helper class for dealing with the modbus wire format.

Instance Method Summary collapse

Constructor Details

#initialize(buffer = nil) ⇒ ProtocolData

Initializes a new ProtocolData instance. Unpacks a buffer string if given.

Parameters:

  • buffer (String, Array) (defaults to: nil)

    The buffer data. If it’s a String, it’s automatically unpacked.



17
18
19
20
21
22
23
24
# File 'lib/modbus/connection/protocol_data.rb', line 17

def initialize(buffer = nil)
  case buffer
  when String
    super buffer.unpack('C*')
  when Array
    super buffer
  end
end

Instance Method Details

#push_byte(byte) ⇒ Object

Interprets a value as a byte (network byte order) and pushes the byte to the end of the array.

Parameters:

  • byte (Integer)

    The value to push.



61
62
63
# File 'lib/modbus/connection/protocol_data.rb', line 61

def push_byte(byte)
  self.concat [byte].pack('C').unpack('C')
end

#push_word(word) ⇒ Object

Interprets a value as a word (network byte order) and pushes two bytes to the end of the array.

Parameters:

  • word (Integer)

    The value to push.



42
43
44
# File 'lib/modbus/connection/protocol_data.rb', line 42

def push_word(word)
  self.concat [word].pack('n').unpack('C2')
end

#shift_byteInteger

Shifts one bytes off the from front of the array.

Returns:

  • (Integer)

    The shifted byte.



51
52
53
54
# File 'lib/modbus/connection/protocol_data.rb', line 51

def shift_byte
  # self.shift
  self.slice!(0,1).first
end

#shift_wordInteger, NilClass

Shifts two bytes off the from front of the array and interprets them as a word (network byte order).

Returns:

  • (Integer, NilClass)

    The shifted word or nil if there are not enough bytes.



31
32
33
34
35
# File 'lib/modbus/connection/protocol_data.rb', line 31

def shift_word
  return nil if size < 2
  # self.shift(2).pack('C2').unpack('n').first
  self.slice!(0,2).pack('C2').unpack('n').first
end

#to_bufferString

Converts the array data into a string.

Returns:

  • (String)

    The data string (frozen).



70
71
72
# File 'lib/modbus/connection/protocol_data.rb', line 70

def to_buffer
  self.pack('C*').freeze
end