Skip to content

Commit

Permalink
Require matching UID
Browse files Browse the repository at this point in the history
  • Loading branch information
jhart-r7 committed Jul 24, 2015
1 parent eb6c7b9 commit 838c900
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
16 changes: 10 additions & 6 deletions lib/rmodbus/tcp_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,19 @@ def serve(io)
proto_id = header[2,2]
len = header[4,2].unpack('n')[0]
unit_id = header.getbyte(6)
if proto_id == "\x00\x00" or unit_id == @uid
if proto_id == "\x00\x00"
req = io.read(len - 1)
log "Server RX (#{req.size} bytes): #{logging_bytes(req)}"
if unit_id == @uid || unit_id == 0
log "Server RX (#{req.size} bytes): #{logging_bytes(req)}"

pdu = exec_req(req, @coils, @discrete_inputs, @holding_registers, @input_registers)
pdu = exec_req(req, @coils, @discrete_inputs, @holding_registers, @input_registers)

resp = tx_id + "\0\0" + (pdu.size + 1).to_word + @uid.chr + pdu
log "Server TX (#{resp.size} bytes): #{logging_bytes(resp)}"
io.write resp
resp = tx_id + "\0\0" + (pdu.size + 1).to_word + @uid.chr + pdu
log "Server TX (#{resp.size} bytes): #{logging_bytes(resp)}"
io.write resp
else
log "Ignored server RX (invalid unit ID #{unit_id}, #{req.size} bytes): #{logging_bytes(req)}"
end
end
end
end
Expand Down
23 changes: 14 additions & 9 deletions spec/tcp_server_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,28 @@

describe ModBus::TCPServer do
before :all do
@server = ModBus::TCPServer.new(8502,1)
unit_ids = (1..247).to_a.shuffle
valid_unit_id = unit_ids.first
@invalid_unit_id = unit_ids.last
@server = ModBus::TCPServer.new(8502, valid_unit_id)
@server.coils = [1,0,1,1]
@server.discrete_inputs = [1,1,0,0]
@server.holding_registers = [1,2,3,4]
@server.input_registers = [1,2,3,4]
@server.start
@cl = ModBus::TCPClient.new('127.0.0.1', 8502)
@slave = @cl.with_slave(1)
@slave.read_retries = 1
@cl.read_retries = 1
@slave = @cl.with_slave(valid_unit_id)
end

it "should silent if UID has mismatched" do
@cl.with_slave(2).read_coils(1,3)
#lambda { @cl.with_slave(2).read_coils(1,3) }.should raise_exception(
# ModBus::Errors::ModBusException,
# "Server did not respond"
#)
it "should succeed if UID is broadcast" do
@cl.with_slave(0).read_coils(1,3)
end

it "should fail if UID is mismatched" do
lambda { @cl.with_slave(@invalid_unit_id).read_coils(1,3) }.should raise_exception(
ModBus::Errors::ModBusTimeout
)
end

it "should send exception if function not supported" do
Expand Down

0 comments on commit 838c900

Please sign in to comment.