Class: NXT::Interface::SerialPort
- Includes:
- Exceptions
- Defined in:
- lib/nxt/interfaces/serial_port.rb
Constant Summary collapse
- BAUD_RATE =
57600
- DATA_BITS =
8
- STOP_BITS =
1
- PARITY =
::SerialPort::NONE
- READ_TIMEOUT =
5000
Instance Attribute Summary collapse
-
#dev ⇒ Object
Returns the value of attribute dev.
Instance Method Summary collapse
- #connect ⇒ Object
- #connected? ⇒ Boolean
- #disconnect ⇒ Object
-
#initialize(dev) ⇒ SerialPort
constructor
A new instance of SerialPort.
- #receive ⇒ Object
- #send(msg) ⇒ Object
Methods inherited from Base
Constructor Details
#initialize(dev) ⇒ SerialPort
Returns a new instance of SerialPort.
16 17 18 |
# File 'lib/nxt/interfaces/serial_port.rb', line 16 def initialize(dev) self.dev = (dev) end |
Instance Attribute Details
#dev ⇒ Object
Returns the value of attribute dev.
8 9 10 |
# File 'lib/nxt/interfaces/serial_port.rb', line 8 def dev @dev end |
Instance Method Details
#connect ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/nxt/interfaces/serial_port.rb', line 25 def connect @connection = ::SerialPort.new(@dev, BAUD_RATE, DATA_BITS, STOP_BITS, PARITY) if !@connection.nil? @connection.flow_control = ::SerialPort::HARD @connection.read_timeout = READ_TIMEOUT else raise SerialPortConnectionError.new("Could not establish a SerialPort connection to #{dev}") end @connection rescue ArgumentError raise SerialPortConnectionError.new("The #{dev} device is not a valid SerialPort") end |
#connected? ⇒ Boolean
44 45 46 |
# File 'lib/nxt/interfaces/serial_port.rb', line 44 def connected? !@connection.closed? end |
#disconnect ⇒ Object
40 41 42 |
# File 'lib/nxt/interfaces/serial_port.rb', line 40 def disconnect @connection.close if @connection && !@connection.closed? end |
#receive ⇒ Object
66 67 68 69 70 71 72 73 |
# File 'lib/nxt/interfaces/serial_port.rb', line 66 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.unpack('v')[0]) end |
#send(msg) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/nxt/interfaces/serial_port.rb', line 48 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 |