Module: Aurora::ModBus::Server

Defined in:
lib/aurora/modbus/server.rb

Instance Method Summary collapse

Instance Method Details

#parse_request(func, req) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/aurora/modbus/server.rb', line 6

def parse_request(func, req)
  case func
  when 65
    # 1 function register, a multiple of two words
    return unless ((req.length - 1) % 4).zero?

    params = []
    req[1..-1].unpack("n*").each_slice(2) do |(addr, quant)|
      params << { addr: addr, quant: quant }
    end
    params
  when 66
    return unless ((req.length - 1) % 2).zero?

    req[1..-1].unpack("n*")
  when 67
    # 1 function register, a multiple of two words
    return unless ((req.length - 1) % 4).zero?

    params = []
    req[1..-1].unpack("n*").each_slice(2) do |(addr, val)|
      params << { addr: addr, val: val }
    end
    params
  when 68
    return unless req.length == 5

    { noidea1: req[1, 2].unpack("n"), noidea2: req[3, 2].unpack("n") }
  else
    super
  end
end

#parse_response(func, res) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/aurora/modbus/server.rb', line 39

def parse_response(func, res)
  return {} if func == 67 && res.length == 1
  return { noidea: res[-1].ord } if func == 68 && res.length == 2

  func = 3 if [65, 66].include?(func)
  super
end

#process_func(func, slave, req, params) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/aurora/modbus/server.rb', line 47

def process_func(func, slave, req, params)
  case func
  when 65
    pdu = ""
    params.each do |param|
      if (err = validate_read_func(param, slave.holding_registers))
        return (func | 0x80).chr + err.chr
      end

      pdu += slave.holding_registers[param[:addr], param[:quant]].pack("n*")
    end
    func.chr + pdu.length.chr + pdu

  when 66
    pdu = params.map { |addr| slave.holding_registers[addr] }.pack("n*")
    func.chr + pdu.length.chr + pdu

  when 67
    slave.holding_registers[param[:addr]] = param[:val]
    pdu = req[0, 2]
  else
    super
  end
end