Class: Modbus::Cli::WriteCommand

Inherits:
Clamp::Command
  • Object
show all
Extended by:
CommandsCommon::ClassMethods
Includes:
CommandsCommon
Defined in:
lib/modbus-cli/write_command.rb

Constant Summary

Constants included from CommandsCommon

CommandsCommon::DEFAULT_SLAVE, CommandsCommon::MAX_WRITE_COILS, CommandsCommon::MAX_WRITE_WORDS

Instance Method Summary collapse

Methods included from CommandsCommon::ClassMethods

address_parameter, datatype_options, debug_option, format_options, host_option, host_parameter, output_option, slave_option, timeout_option

Methods included from CommandsCommon

#addr_area, #addr_format, #addr_offset, #addr_type, #data_size, #modicon_match, #schneider_match, #sliced_write_coils, #sliced_write_registers

Instance Method Details

#executeObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/modbus-cli/write_command.rb', line 37

def execute
  ModBus::TCPClient.connect(host, port) do |cl|
    cl.with_slave(slave) do |sl|
      sl.debug = true if debug?
      sl.read_retry_timeout = timeout if timeout

      case addr_type
      when :bit
        write_coils sl
      when :word, :int
        write_words sl
      when :float
        write_floats sl
      when :dword
        write_dwords sl
      end
    end
  end
end

#int_parameter(vv, min, max) ⇒ Object



78
79
80
81
82
# File 'lib/modbus-cli/write_command.rb', line 78

def int_parameter(vv, min, max)
  Integer(vv).tap do |v|
    raise ArgumentError, "Value should be in the range #{min}..#{max}" unless (min..max).member? v
  end
end

#pack_and_write(sl, format) ⇒ Object



73
74
75
76
# File 'lib/modbus-cli/write_command.rb', line 73

def pack_and_write(sl, format)
  # the word ordering is wrong. calling reverse two times effectively swaps every pair
  sliced_write_registers(sl, addr_offset, values_list.reverse.pack("#{format}*").unpack('n*').reverse)
end

#write_coils(sl) ⇒ Object



57
58
59
# File 'lib/modbus-cli/write_command.rb', line 57

def write_coils(sl)
  sliced_write_coils sl, addr_offset, values_list
end

#write_dwords(sl) ⇒ Object



69
70
71
# File 'lib/modbus-cli/write_command.rb', line 69

def write_dwords(sl)
  pack_and_write sl, 'N'
end

#write_floats(sl) ⇒ Object



65
66
67
# File 'lib/modbus-cli/write_command.rb', line 65

def write_floats(sl)
  pack_and_write sl, 'g'
end

#write_words(sl) ⇒ Object



61
62
63
# File 'lib/modbus-cli/write_command.rb', line 61

def write_words(sl)
  sliced_write_registers sl, addr_offset, values_list.pack('S*').unpack('S*')
end