Class: Modbus::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/modbus/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, handler) ⇒ Server

Returns a new instance of Server.



12
13
14
15
16
# File 'lib/modbus/server.rb', line 12

def initialize(uri, handler)
  @uri       = URI uri
  @handler   = handler
  @registers = {}
end

Instance Attribute Details

#registersObject (readonly)

Returns the value of attribute registers.



9
10
11
# File 'lib/modbus/server.rb', line 9

def registers
  @registers
end

Instance Method Details

#add_register(addr, handler = nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/modbus/server.rb', line 19

def add_register(addr, handler = nil)
  log.info "Adding register @ #{addr}"

  reg_addr, bit = addr.split('.')
  reg_addr = reg_addr.to_i

  register_class = bit ? BitRegister : WordRegister
  reg = get_register reg_addr, register_class
  reg.handler = handler

  value = bit ? false : 0
  update_register addr, value

  reg
end

#client_connected(signature) ⇒ Object



54
55
56
# File 'lib/modbus/server.rb', line 54

def client_connected(signature)
  log.info "client connected (signature #{signature})"
end

#client_disconnected(signature) ⇒ Object



59
60
61
# File 'lib/modbus/server.rb', line 59

def client_disconnected(signature)
  log.info "client disconnected (signature #{signature})"
end

#read_registers(start_addr, reg_count) ⇒ Object



64
65
66
67
68
69
# File 'lib/modbus/server.rb', line 64

def read_registers(start_addr, reg_count)
  (0..reg_count-1).map do |idx|
    addr = start_addr + idx
    read_register addr
  end
end

#startObject



49
50
51
# File 'lib/modbus/server.rb', line 49

def start
  EM.start_server @uri.host, @uri.port, Modbus::Connection::TCPServer, self
end

#update_register(addr, value) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/modbus/server.rb', line 36

def update_register(addr, value)
  reg_addr, bit = addr.split('.')
  reg = @registers.fetch reg_addr.to_i

  case reg
  when WordRegister
    reg.update value
  when BitRegister
    reg.update bit.to_i, value
  end
end

#write_registers(start_addr, reg_values) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/modbus/server.rb', line 72

def write_registers(start_addr, reg_values)
  reg_values.each_with_index do |value, idx|
    addr = start_addr + idx
    write_register addr, value
  end

  reg_values.size
end