Class: Modbus::BitRegister

Inherits:
Register show all
Defined in:
lib/modbus/register/bit_register.rb

Instance Attribute Summary

Attributes inherited from Register

#addr, #handler

Instance Method Summary collapse

Constructor Details

#initialize(addr) ⇒ BitRegister

Returns a new instance of BitRegister.



10
11
12
13
# File 'lib/modbus/register/bit_register.rb', line 10

def initialize(addr)
  super
  @bits = {}
end

Instance Method Details

#update(bit, value) ⇒ Object



16
17
18
19
20
# File 'lib/modbus/register/bit_register.rb', line 16

def update(bit, value)
  fail ArgumentError unless (0..15).include? bit
  fail ArgumentError unless [true, false].include? value
  @bits[bit] = value
end

#valueObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/modbus/register/bit_register.rb', line 23

def value
  result = 0

  @bits.each do |bit, bit_value|
    value = bit_value ? 1 : 0
    result |= (value << bit)
  end

  result
end

#write(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/modbus/register/bit_register.rb', line 35

def write(value)
  return unless @handler

  values = @bits.keys.map do |bit|
    bit_value = value[bit] == 1
    {:addr => [@addr, bit].join('.'), :value => bit_value}
  end

  @handler.write_values values
end