Class: FB::ArduinoEventMachine
- Inherits:
-
EventMachine::Connection
- Object
- EventMachine::Connection
- FB::ArduinoEventMachine
- Defined in:
- lib/arduino/event_machine.rb
Overview
Class that is fed into event machine’s event loop to handle incoming serial messages asynchronously via EM.attach(). See: EM.attach
Class Attribute Summary collapse
-
.arduino ⇒ Object
Returns the value of attribute arduino.
Class Method Summary collapse
Instance Method Summary collapse
- #add_to_buffer(d) ⇒ Object
- #clear_buffer ⇒ Object
-
#initialize ⇒ ArduinoEventMachine
constructor
A new instance of ArduinoEventMachine.
-
#receive_data(data) ⇒ Object
Gets called when data arrives.
- #send_buffer ⇒ Object
-
#split_into_chunks(data) ⇒ Object
This is a nasty hack that takes incoming strings from the serial line and splits the data on rn.
-
#unbind ⇒ Object
Gets called when the connection breaks.
Constructor Details
#initialize ⇒ ArduinoEventMachine
10 11 12 13 |
# File 'lib/arduino/event_machine.rb', line 10 def initialize @bot = self.class.arduino @q, @buffer = @bot.inbound_queue, '' end |
Class Attribute Details
.arduino ⇒ Object
Returns the value of attribute arduino.
7 8 9 |
# File 'lib/arduino/event_machine.rb', line 7 def arduino @arduino end |
Class Method Details
.connect(arduino) ⇒ Object
53 54 55 56 |
# File 'lib/arduino/event_machine.rb', line 53 def self.connect(arduino) @arduino = arduino EM.attach arduino.serial_port, self end |
Instance Method Details
#add_to_buffer(d) ⇒ Object
39 40 41 |
# File 'lib/arduino/event_machine.rb', line 39 def add_to_buffer(d) @buffer += d end |
#clear_buffer ⇒ Object
35 36 37 |
# File 'lib/arduino/event_machine.rb', line 35 def clear_buffer @buffer = '' end |
#receive_data(data) ⇒ Object
Gets called when data arrives.
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/arduino/event_machine.rb', line 16 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 ⇒ Object
43 44 45 |
# File 'lib/arduino/event_machine.rb', line 43 def send_buffer @q << Gcode.parse_lines(@buffer) end |
#split_into_chunks(data) ⇒ Object
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.
31 32 33 |
# File 'lib/arduino/event_machine.rb', line 31 def split_into_chunks(data) data.gsub("\r\n", '\b\a').split('\a').map{ |d| d.gsub('\b', "\r\n") } end |
#unbind ⇒ Object
Gets called when the connection breaks.
48 49 50 51 |
# File 'lib/arduino/event_machine.rb', line 48 def unbind self.class.arduino.disconnect EM.stop end |