Class: Hacklet::SerialConnection
- Inherits:
-
Object
- Object
- Hacklet::SerialConnection
- Defined in:
- lib/hacklet/serial_connection.rb
Instance Method Summary collapse
-
#close ⇒ Object
Public: Closes the connection.
-
#initialize(logger, port = '/dev/ttyUSB0') ⇒ SerialConnection
constructor
A new instance of SerialConnection.
-
#receive(bytes) ⇒ Object
Public: Waits and receives the specified number of packets from the dongle.
-
#transmit(command) ⇒ Object
Public: Transmits the packet to the dongle.
Constructor Details
#initialize(logger, port = '/dev/ttyUSB0') ⇒ SerialConnection
Returns a new instance of SerialConnection.
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/hacklet/serial_connection.rb', line 5 def initialize(logger, port='/dev/ttyUSB0') @logger = logger @connection = Ftdi::Context.new @connection.usb_open(0x0403, 0x8c81) @connection.set_bitmode(0x00, Ftdi::BitbangMode[:reset]) @connection.baudrate = 115200 @connection.flowctrl = Ftdi::SIO_DISABLE_FLOW_CTRL @connection.dtr = 1 @connection.rts = 1 @receive_buffer = "" end |
Instance Method Details
#close ⇒ Object
Public: Closes the connection
Returns nothing.
20 21 22 |
# File 'lib/hacklet/serial_connection.rb', line 20 def close @connection.usb_close end |
#receive(bytes) ⇒ Object
Public: Waits and receives the specified number of packets from the dongle.
bytes - The number of bytes to read.
Returns a binary string containing the response.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/hacklet/serial_connection.rb', line 40 def receive(bytes) response = "" loop do if bytes <= @receive_buffer.bytesize array = @receive_buffer.bytes.to_a response = array[0..(bytes - 1)].pack('c*') @receive_buffer = array[(bytes)..-1].pack('c*') break end chunk = @connection.read_data if chunk.bytesize > 0 @receive_buffer += chunk else sleep(0.1) end end @logger.debug("RX: #{unpack(response).inspect}") response end |
#transmit(command) ⇒ Object
Public: Transmits the packet to the dongle.
command - The binary string to send.
Returns the number of bytes written.
29 30 31 32 |
# File 'lib/hacklet/serial_connection.rb', line 29 def transmit(command) @logger.debug("TX: #{unpack(command.to_binary_s).inspect}") @connection.write_data(command.to_binary_s) end |