Class: NXT::Interface::Usb

Inherits:
Base
  • Object
show all
Includes:
Exceptions
Defined in:
lib/nxt/interface/usb.rb

Overview

Implements USB connectivity to the NXT 2.0 module.

Constant Summary collapse

ID_VENDOR_LEGO =
0x0694
ID_PRODUCT_NXT =
0x0002
OUT_ENDPOINT =
0x01
IN_ENDPOINT =
0x82
TIMEOUT =
10_000
READSIZE =
64
INTERFACE =
0

Instance Method Summary collapse

Instance Method Details

#connectObject

Raises:



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

def connect
  @usb_context = LIBUSB::Context.new
  @dev = @usb_context.devices(idVendor: ID_VENDOR_LEGO, idProduct: ID_PRODUCT_NXT).first

  raise UsbConnectionError, 'Could not find NXT attached as USB device' if @dev.nil?

  @connection = @dev.open
  @connection.claim_interface(INTERFACE)

  @connection
end

#connected?Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/nxt/interface/usb.rb', line 38

def connected?
  # FIXME: How do we check if the device is connected?
  @connection
end

#disconnectObject



31
32
33
34
35
36
# File 'lib/nxt/interface/usb.rb', line 31

def disconnect
  return unless connected?

  @connection.release_interface(INTERFACE)
  @connection.close
end

#receiveObject



47
48
49
# File 'lib/nxt/interface/usb.rb', line 47

def receive
  @connection.bulk_transfer(endpoint: IN_ENDPOINT, dataIn: READSIZE, timeout: TIMEOUT).from_hex_str
end

#send(msg) ⇒ Object



43
44
45
# File 'lib/nxt/interface/usb.rb', line 43

def send(msg)
  @connection.bulk_transfer(endpoint: OUT_ENDPOINT, dataOut: msg.pack('C*'), timeout: TIMEOUT)
end