class Lignite::Connection

The communication channel to the robot. The callers use {#send} and {#receive}. Subclasses implement {#read}, {#write} and {#close}.

Public Class Methods

create() click to toggle source

@return [Connection] Try a {Usb} connection first, then a {Bluetooth} one.

# File lib/lignite/connection.rb, line 11
def self.create
  @c ||= Replay.new(ENV["LIGNITE_REPLAY"]) if ENV["LIGNITE_REPLAY"]

  @c ||= begin
           logger.debug "Connection: trying USB"
           Usb.new
         rescue NoUsbDevice
           logger.debug "Connection: trying BT"
           Bluetooth.new
         end

  @c = Tap.new(@c, ENV["LIGNITE_TAP"]) if ENV["LIGNITE_TAP"]
  logger.debug "Connection: #{@c.inspect}"
  @c
end
new() click to toggle source
# File lib/lignite/connection.rb, line 31
def initialize
  @buf = ""
end
reset() click to toggle source
# File lib/lignite/connection.rb, line 27
def self.reset
  @c = nil
end

Public Instance Methods

close() click to toggle source

@!endgroup

# File lib/lignite/connection.rb, line 45
def close
  Connection.reset
end
receive() click to toggle source

@return [ByteString] a complete message

# File lib/lignite/connection.rb, line 58
def receive
  size = nil
  loop do
    lenbuf = bufread(2)
    size = unpack_u16(lenbuf)
    break unless size.zero?
    # leftover data?
    @buf = ""
  end

  res = bufread(size)
  res
end
send(payload) click to toggle source

@param payload [ByteString]

# File lib/lignite/connection.rb, line 50
def send(payload)
  packet = u16(payload.bytesize) + payload
  logger.debug "-> #{packet.inspect}"

  write(packet)
end

Private Instance Methods

bufread(n) click to toggle source

read must not be called with a too low value :-/

# File lib/lignite/connection.rb, line 75
def bufread(n)
  @buf += read(10000) while @buf.bytesize < n
  ret = @buf[0, n]
  @buf = @buf[n..-1]
  logger.debug "R<-(#{ret.bytesize})#{ret.inspect}"
  ret
end