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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeArduinoEventMachine



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

.arduinoObject

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_bufferObject



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_bufferObject



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

#unbindObject

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