/
base.rb
63 lines (56 loc) · 1.2 KB
/
base.rb
1
2
3
4
5
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'observer'
require 'timeout'
module Dino
module TxRx
class Base
include Observable
def read
@thread ||= Thread.new do
loop do
line = gets
if line
pin, message = line.chop.split(/:/)
pin && message && changed && notify_observers(pin, message)
end
end
end
end
def close_read
return nil if @thread.nil?
Thread.kill(@thread)
@thread = nil
end
def write(message)
loop do
if IO.select(nil, [io], nil)
io.puts(message)
break
end
end
end
def handshake
100.times do
begin
write("!9000000.")
Timeout::timeout(0.1) do
line = gets.to_s.chop
if line.match /ACK/
flush_read
return line.split(/:/)[1].to_i
end
end
rescue
nil
end
end
raise BoardNotFound
end
def flush_read
gets until gets == nil
end
def gets
IO.select([io], nil, nil, 0.005) && io.gets
end
end
end
end