Class: IRobotCreate::SensorCommand

Inherits:
Command
  • Object
show all
Defined in:
lib/irobotcreate/command/sensor.rb

Constant Summary collapse

@@sensor_commands =
{}

Instance Attribute Summary collapse

Attributes inherited from Command

#argument_options, #code

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sensor_code, response_size, response_type, response_options = nil) ⇒ SensorCommand

Returns a new instance of SensorCommand.



20
21
22
23
24
25
26
# File 'lib/irobotcreate/command/sensor.rb', line 20

def initialize(sensor_code, response_size, response_type, response_options = nil)
  super(142, 1)
  @sensor_code = sensor_code
  @response_size = response_size
  @response_type = response_type
  @response_options = response_options
end

Instance Attribute Details

#response_optionsObject (readonly)

Returns the value of attribute response_options.



4
5
6
# File 'lib/irobotcreate/command/sensor.rb', line 4

def response_options
  @response_options
end

#response_sizeObject (readonly)

Returns the value of attribute response_size.



4
5
6
# File 'lib/irobotcreate/command/sensor.rb', line 4

def response_size
  @response_size
end

#response_typeObject (readonly)

Returns the value of attribute response_type.



4
5
6
# File 'lib/irobotcreate/command/sensor.rb', line 4

def response_type
  @response_type
end

#sensor_codeObject (readonly)

Returns the value of attribute sensor_code.



4
5
6
# File 'lib/irobotcreate/command/sensor.rb', line 4

def sensor_code
  @sensor_code
end

Class Method Details

.[](name) ⇒ Object



14
15
16
# File 'lib/irobotcreate/command/sensor.rb', line 14

def [](name)
  @@sensor_commands[name.to_sym]
end

.register(name, *args) ⇒ Object



10
11
12
# File 'lib/irobotcreate/command/sensor.rb', line 10

def register(name, *args)
  @@sensor_commands[name] = new(*args)
end

Instance Method Details

#run(robot) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/irobotcreate/command/sensor.rb', line 28

def run(robot)
  super(robot, sensor_code)

  response = robot.read_response(response_size)

  case response_type
  when :boolean
    response.first == 1
  when :integer, :signed_integer
    integer = 0
    response_size.times do |i|
      integer += response[i] * (256 ** ((response_size - 1) - i))
    end

    if response_type == :signed_integer
      max = 256 ** response_size
      if integer > max / 2
        integer -= max
      end
    end

    integer
  when :map
    response_options[response.first]
  when :compound
    hash = {}
    options_size = response_options.size
    options_size.times do |i|
      item = response_options[i]
      next unless item
      hash[item] = response.first & 2**((options_size - 1) - i) != 0
    end
    hash
  else
    response
  end
end