Class: FB::ArduinoEventMachine

Inherits:
EventMachine::Connection
  • Object
show all
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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeArduinoEventMachine

Returns a new instance of ArduinoEventMachine.



12
13
14
15
# File 'lib/arduino/event_machine.rb', line 12

def initialize
  @bot = self.class.arduino
  @q, @buffer = @bot.inbound_queue, ''
end

Class Attribute Details

.arduinoObject

Returns the value of attribute arduino.



7
8
9
# File 'lib/arduino/event_machine.rb', line 7

def arduino
  @arduino
end

Instance Attribute Details

#botObject (readonly)

Returns the value of attribute bot.



10
11
12
# File 'lib/arduino/event_machine.rb', line 10

def bot
  @bot
end

#bufferObject (readonly)

Returns the value of attribute buffer.



10
11
12
# File 'lib/arduino/event_machine.rb', line 10

def buffer
  @buffer
end

#qObject (readonly)

Returns the value of attribute q.



10
11
12
# File 'lib/arduino/event_machine.rb', line 10

def q
  @q
end

Class Method Details

.connect(arduino) ⇒ Object



55
56
57
58
# File 'lib/arduino/event_machine.rb', line 55

def self.connect(arduino)
  @arduino = arduino
  EM.attach arduino.serial_port, self
end

Instance Method Details

#add_to_buffer(d) ⇒ Object



41
42
43
# File 'lib/arduino/event_machine.rb', line 41

def add_to_buffer(d)
  @buffer += d
end

#clear_bufferObject



37
38
39
# File 'lib/arduino/event_machine.rb', line 37

def clear_buffer
  @buffer = ''
end

#receive_data(data) ⇒ Object

Gets called when data arrives.



18
19
20
21
22
23
24
25
26
27
28
# 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_bufferObject



45
46
47
# File 'lib/arduino/event_machine.rb', line 45

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.



33
34
35
# 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

#unbindObject

Gets called when the connection breaks.



50
51
52
53
# File 'lib/arduino/event_machine.rb', line 50

def unbind
  self.class.arduino.disconnect
  EM.stop
end