trying out observer and timers

This commit is contained in:
Will Bradley 2019-07-06 20:09:29 -07:00
parent 8a8b57ca0d
commit 2acb7dcd82

View File

@ -1,4 +1,6 @@
require 'rubyserial'
require 'observer'
require 'timers'
#
# User Configs
@ -17,6 +19,7 @@ parity = :none
@serial = Serial.new device, baud, bits, parity
@buffer = Queue.new
@timers = Timers::Group.new
#
# Convenience function
@ -49,7 +52,20 @@ def b_open(num)
serial_writeln("o #{num}")
end
def b_unlock()
# Listen for an unlock event; raise an error if not found
foo = @timers.after(5) {
if @events[:unlocked].changed?
print "foo"
else
print "didn't get an unlock event in time"
end
}
print foo.inspect
SerialListener.new(@events[:unlocked],
Proc.new{ |value| print "got unlock event #{value}" }
)
serial_writeln("u")
@timers.fire
end
def b_lock()
serial_writeln("l")
@ -163,6 +179,7 @@ def parse_in()
case sline
when /(\d*) unlocked$/ # ends line
print ">Door #{$1} unlocked\n"
@events[:unlocked].send($1)
when /All Doors relocked/
print ">All Doors relocked\n"
when /Door (\d*) locked$/ # ends line
@ -282,10 +299,47 @@ def parse_in()
end
end
#
# Classes
#
class SerialEvents
include Observable
@oldvalue = nil
def send(value)
if value != @oldvalue
changed
@oldvalue = value
notify_observers(Time.now, value)
end
end
end
class SerialListener
@callback = nil
def initialize(observable, callback)
@callback = callback
observable.add_observer(self)
end
def update(time, value)
@callback.call(value)
end
end
#
# Runtime
#
@events = {
unlocked: SerialEvents.new,
locked: SerialEvents.new,
}
puts "> Started threads at #{Time.now}"
t1 = Thread.new{console_in()}
t2 = Thread.new{serial_in()}