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

Returns a new instance of ArduinoEventMachine.



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

def initialize
  @q, @buffer = self.class.arduino.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



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

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

.poll(interval, &blk) ⇒ Object



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

def self.poll(interval, &blk)
  EventMachine::PeriodicTimer.new(interval.to_f, &blk)
end

Instance Method Details

#add_to_buffer(d) ⇒ Object



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

def add_to_buffer(d)
  @buffer += d
end

#clear_bufferObject



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

def clear_buffer
  @buffer = ''
end

#receive_data(data) ⇒ Object

Gets called when data arrives.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/arduino/event_machine.rb', line 19

def receive_data(data)
  split_into_chunks(data).each do |chunk|
    if chunk.end_with?("\r\n")
      add_to_buffer(chunk)
      send_buffer
      clear_buffer
    else
      add_to_buffer(chunk)
    end
  end
end

#send_bufferObject



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

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.



34
35
36
# File 'lib/arduino/event_machine.rb', line 34

def split_into_chunks(data)
  data.gsub("\r\n", '!@').split('@').map{ |d| d.gsub('!', "\r\n") }
end

#unbindObject

Gets called when the connection breaks.



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

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