Class: NXT::Interface::SerialPort

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

Overview

Implements serial port connectivity to the NXT 2.0 module.

Constant Summary collapse

BAUD_RATE =
57_600
DATA_BITS =
8
STOP_BITS =
1
PARITY =
::SerialPort::NONE
READ_TIMEOUT =
5_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dev) ⇒ SerialPort

Returns a new instance of SerialPort.



19
20
21
22
# File 'lib/nxt/interface/serial_port.rb', line 19

def initialize(dev)
  super()
  self.dev = dev
end

Instance Attribute Details

#devObject

Returns the value of attribute dev.



11
12
13
# File 'lib/nxt/interface/serial_port.rb', line 11

def dev
  @dev
end

Instance Method Details

#connectObject



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/nxt/interface/serial_port.rb', line 30

def connect
  @connection = ::SerialPort.new(@dev, BAUD_RATE, DATA_BITS, STOP_BITS, PARITY)

  raise SerialPortConnectionError, "Could not establish a SerialPort connection to #{dev}" if @connection.nil?

  @connection.flow_control = ::SerialPort::HARD
  @connection.read_timeout = READ_TIMEOUT

  @connection
rescue ArgumentError
  raise SerialPortConnectionError, "The #{dev} device is not a valid SerialPort"
end

#connected?Boolean

Returns:

  • (Boolean)


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

def connected?
  @connection && !@connection.closed?
end

#disconnectObject



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

def disconnect
  @connection.close if connected?
end

#receiveObject



69
70
71
72
73
74
75
76
# File 'lib/nxt/interface/serial_port.rb', line 69

def receive
  # This gets the length of the received data from the header that was sent
  # to us. We unpack it, as it's stored as a 16-bit Little Endian number.
  #
  # Reference: Appendix 1, Page 22
  length = @connection.sysread(2)
  @connection.sysread(length.unpack1('v')).from_hex_str
end

#send(msg) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/nxt/interface/serial_port.rb', line 51

def send(msg)
  # The expected data package structure for NXT Bluetooth communication is:
  #
  #     [Length Byte 1, Length Byte 2, Command Type, Command, ...]
  #
  # So here we calculate the two leading length bytes, and rely on the
  # passed in argument to give us the rest of the message to send.
  #
  # Note that the length is stored in Little Endian ie. LSB -> MSB
  #
  # Reference: Appendix 1, Page 22
  msg = [(msg.length & 255), (msg.length >> 8)] + msg

  msg.each do |b|
    @connection.putc(b)
  end
end