module NXT::Protocols::I2C

Communication to the NXT brick for digital sensors is done using the I2C protocol. This module implements communication in that fashion, abstracing the messages we wish to send from the underlying protocol for ease-of-use.

Constants

COMMAND_IDENTIFIER
I2C_COMMANDS

Format is I2C address, followed by the command. If the array is only one member large, then the second byte is instead a value passed at run-time, eg. the length of the interval to run the continuous measuring on the ultrasonic sensor for.

I2C_CONSTANT_OPS

Format is I2C address, followed by the number of bytes expected in the response.

I2C_HEADER
I2C_VARIABLE_OPS

Format is the I2C address (all variable operations expect a 1 byte reponse).

Public Class Methods

method_missing(name, *args) click to toggle source
Calls superclass method
# File lib/nxt/protocols/i2c.rb, line 62
def self.method_missing(name, *args)
  if I2C_CONSTANT_OPS.key?(name)
    run_constant_op(name)
  elsif I2C_VARIABLE_OPS.key?(name)
    run_variable_op(name)
  elsif I2C_COMMANDS.key?(name)
    run_command(name, *args)
  else
    super
  end
end
respond_to_missing?(name, include_private = false) click to toggle source
Calls superclass method
# File lib/nxt/protocols/i2c.rb, line 74
def self.respond_to_missing?(name, include_private = false)
  I2C_CONSTANT_OPS.key?(name) ||
    I2C_VARIABLE_OPS.key?(name) ||
    I2C_COMMANDS.key?(name) ||
    super
end

Private Class Methods

run_command(name, *args) click to toggle source
# File lib/nxt/protocols/i2c.rb, line 100
def run_command(name, *args)
  op = I2C_COMMANDS[name]
  addr = op[0]
  rx_len = 0

  if op[1]
    data = [op[1]]
  elsif args[0]
    data = [args[0]]
  else
    raise "Missing argument for command #{name}"
  end

  [data.size, rx_len, I2C_HEADER, addr] + data
end
run_constant_op(name) click to toggle source
# File lib/nxt/protocols/i2c.rb, line 84
def run_constant_op(name)
  op = I2C_CONSTANT_OPS[name]
  addr = op[0]
  rx_len = op[1]

  [0, rx_len, I2C_HEADER, addr]
end
run_variable_op(name) click to toggle source
# File lib/nxt/protocols/i2c.rb, line 92
def run_variable_op(name)
  op = I2C_VARIABLE_OPS[name]
  addr = op
  rx_len = 1

  [0, rx_len, I2C_HEADER, addr]
end