lib/arduino_firmata/arduino.rb in arduino_firmata-0.2.6 vs lib/arduino_firmata/arduino.rb in arduino_firmata-0.2.7
- old
+ new
@@ -1,14 +1,17 @@
module ArduinoFirmata
class Arduino
include EventEmitter
- attr_reader :version, :status, :nonblock_io
+ attr_reader :version, :status, :nonblock_io, :eventmachine
def initialize(serial_name, params)
@nonblock_io = !!params[:nonblock_io]
+ @eventmachine = !!params[:eventmachine]
+ @read_byte_size = eventmachine ? 256 : 9600
+ @process_input_interval = eventmachine ? 0.0001 : 0.01
@status = Status::CLOSE
@wait_for_data = 0
@execute_multi_byte_command = 0
@multi_byte_channel = 0
@stored_input_data = []
@@ -42,18 +45,18 @@
close
exit
end
@thread_status = false
- Thread.new{
+ run do
@thread_status = true
while status == Status::OPEN do
process_input
- sleep 0.01
+ sleep @process_input_interval
end
@thread_status = false
- }.run
+ end
(0...6).each do |i|
write(REPORT_ANALOG | i)
write 1
end
@@ -68,10 +71,19 @@
sleep 0.3
end
sleep 0.5
end
+ def run(&block)
+ return unless block_given?
+ if eventmachine
+ EM::defer &block
+ else
+ Thread.new &block
+ end
+ end
+
def close
return if status == Status::CLOSE
@status = Status::CLOSE
@serial.close
loop do
@@ -169,12 +181,12 @@
end
def read
return if status == Status::CLOSE
if nonblock_io
- @serial.read_nonblock 9600 rescue EOFError
+ @serial.read_nonblock @read_byte_size rescue EOFError
else
- @serial.read 9600 rescue EOFError
+ @serial.read @read_byte_size rescue EOFError
end
end
def process_input
StringIO.new(String read).each_byte.each do |input_data|