class FB::ArduinoEventMachine
Class that is fed into event machine’s event loop to handle incoming serial messages asynchronously via EM.attach(). See: EM.attach
Attributes
arduino[RW]
bot[R]
buffer[R]
q[R]
Public Class Methods
connect(arduino)
click to toggle source
# File lib/arduino/event_machine.rb, line 55 def self.connect(arduino) @arduino = arduino EM.attach arduino.serial_port, self end
new()
click to toggle source
# File lib/arduino/event_machine.rb, line 12 def initialize @bot = self.class.arduino @q, @buffer = @bot.inbound_queue, '' end
Public Instance Methods
add_to_buffer(d)
click to toggle source
# File lib/arduino/event_machine.rb, line 41 def add_to_buffer(d) @buffer += d end
clear_buffer()
click to toggle source
# File lib/arduino/event_machine.rb, line 37 def clear_buffer @buffer = '' end
receive_data(data)
click to toggle source
Gets called when data arrives.
# File lib/arduino/event_machine.rb, line 18 def receive_data(data) split_into_chunks(data).each do |chunk| if chunk.end_with?("\r\n") || chunk.end_with?("R00\n") add_to_buffer(chunk) send_buffer clear_buffer else add_to_buffer(chunk) # Keep RXing the buffer until chunk completes. end end end
send_buffer()
click to toggle source
# File lib/arduino/event_machine.rb, line 45 def send_buffer @q << Gcode.parse_lines(@buffer) end
split_into_chunks(data)
click to toggle source
This is a nasty hack that takes incoming strings from the serial line and splits the data on rn. Unlike Ruby’s split() method, this method will preserve the rn.
# File lib/arduino/event_machine.rb, line 33 def split_into_chunks(data) data.gsub("\r\n", '\b\a').split('\a').map{ |d| d.gsub('\b', "\r\n") } end
unbind()
click to toggle source
Gets called when the connection breaks.
# File lib/arduino/event_machine.rb, line 50 def unbind self.class.arduino.disconnect EM.stop end