Class: IRobotCreate::Robot

Inherits:
Object
  • Object
show all
Defined in:
lib/irobotcreate/robot.rb

Constant Summary collapse

DEFAULT_PORT =
'/dev/tty.ElementSerial-ElementSe'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port = DEFAULT_PORT, args = {}) ⇒ Robot

Returns a new instance of Robot.



11
12
13
14
# File 'lib/irobotcreate/robot.rb', line 11

def initialize(port = DEFAULT_PORT, args = {})
  args = { :baudrate => 57600, :databits => 8, :stopbits => 1 }.merge(args)
  @serial = SerialPort.new(port, args)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/irobotcreate/robot.rb', line 45

def method_missing(sym, *args, &block)
  if sym.to_s =~ /^sensor_(.*)$/ && SensorCommand[$1]
    check_sensor($1)
  elsif Command[sym]
    run_command(sym, *args, &block)
  else
    super
  end
end

Instance Attribute Details

#serialObject (readonly)

Returns the value of attribute serial.



9
10
11
# File 'lib/irobotcreate/robot.rb', line 9

def serial
  @serial
end

Instance Method Details

#check_sensor(name) ⇒ Object



41
42
43
# File 'lib/irobotcreate/robot.rb', line 41

def check_sensor(name)
  SensorCommand[name].run(self)
end

#format_bytes(arg) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/irobotcreate/robot.rb', line 16

def format_bytes(arg)
  array = case arg
    when String
      arg.split(/\s+/).map(&:to_i)
    when Array
      arg
    else
      [arg]
  end

  array.pack('C*')
end

#read_response(size = 1) ⇒ Object



33
34
35
# File 'lib/irobotcreate/robot.rb', line 33

def read_response(size=1)
  (0...size).map{|_| serial.getc }.join.unpack('C*')
end

#run_command(name, *args) ⇒ Object



37
38
39
# File 'lib/irobotcreate/robot.rb', line 37

def run_command(name, *args)
  Command[name].run(self, *args)
end

#send(cmd) ⇒ Object



29
30
31
# File 'lib/irobotcreate/robot.rb', line 29

def send(cmd)
  serial.write format_bytes(cmd)
end