Class: LegoEv3::Brick

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

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ Brick

Returns a new instance of Brick.



3
4
5
6
7
8
9
10
11
12
# File 'lib/brick.rb', line 3

def initialize(connection)
  @connection = connection
  @ports = []
  @devices = []
  @motors = []
  @sensors = []

  refresh!
  motors.each{ |m| m.reset }
end

Instance Method Details

#infoObject



88
89
90
91
92
93
94
# File 'lib/brick.rb', line 88

def info
  {
    ports: @ports,
    motors: @motors.map(&:info),
    sensors: @sensors.map(&:info)
  }
end

#motorsObject



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

def motors
  @motors
end

#refresh!Object



22
23
24
25
26
27
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/brick.rb', line 22

def refresh!
  @ports = LegoEv3::Commands::LegoPort.list!(@connection).map do |port|
    { id: port }
  end

  # Retrieve name and status in batch.
  @ports.each do |port|
    LegoEv3::Commands::LegoPort.get_port_name(@connection, port[:id]) do |name|
      port[:name] = name
    end

    LegoEv3::Commands::LegoPort.get_status(@connection, port[:id]) do |status|
      port[:status] = status
    end
  end

  # Retrieve Port name -> Tacho motor in batch.
  tacho_motors = {}
  LegoEv3::Commands::TachoMotor.list!(@connection).each do |motor|
    LegoEv3::Commands::TachoMotor.get_port_name(@connection, motor) do |port_name|
      tacho_motors[port_name] = motor
    end
  end

  # Retrieve Port name -> Lego sensor in batch.
  lego_sensors = {}
  LegoEv3::Commands::LegoSensor.list!(@connection).each do |sensor|
    LegoEv3::Commands::LegoSensor.get_port_name(@connection, sensor) do |port_name|
      lego_sensors[port_name] = sensor
    end
  end

  @connection.flush

  # Assemble port info.
  @ports.each do |port|
    status = port.delete(:status)
    connected =
      status != 'no-sensor' &&
      status != 'no-motor' &&
      status != 'error'

    port[:type] = port[:name].start_with?('in') ? :sensor : :motor
    port[:connected] = connected
    port[:error] = status == 'error'
    port[:driver] = connected ? status : nil
  end

  @motors = @ports
    .select{ |p| p[:type] == :motor && p[:connected] }
    .map{ |p| LegoEv3::TachoMotor.new(@connection, tacho_motors[p[:name]], p) }

  @sensors = @ports
    .select{ |p| p[:type] == :sensor && p[:connected] }
    .map do |p|
      id = lego_sensors[p[:name]]
      driver_name = LegoEv3::Commands::LegoSensor.get_driver_name!(@connection, id)

      if driver_name == 'lego-ev3-touch'
        LegoEv3::TouchSensor.new(@connection, id, p)
      else
        nil
      end
    end.compact
end

#sensorsObject



18
19
20
# File 'lib/brick.rb', line 18

def sensors
  @sensors
end