class Wifly::Connection

Attributes

address[RW]
port[RW]

Public Class Methods

new(address, port) click to toggle source

address => the hostname or IP address of the wifly device port => the port for communicating with the wifly

# File lib/wifly/connection.rb, line 8
def initialize(address, port)
  self.address = address
  self.port    = port
end

Public Instance Methods

close() click to toggle source
# File lib/wifly/connection.rb, line 29
def close
  socket.close
end
send_command(str) click to toggle source

str => the command to send to the wifly, without any carriage return

return_len

> the expected length of the return string; defaults to 0

The wifly will echo back the command (with carriage return) along with another CRLF and the command prompt string. Something like “litesrrn<2.32> ”

# File lib/wifly/connection.rb, line 21
def send_command(str)
  str += "\r"
  write(socket, str) # the write is blocking
  sleep(0.2)
  read(socket).gsub(prompt,'')
end
socket() click to toggle source
# File lib/wifly/connection.rb, line 33
def socket
  @socket ||= initialize_socket
end

Private Instance Methods

initialize_socket() click to toggle source
# File lib/wifly/connection.rb, line 71
def initialize_socket
  sock = Socket.tcp(address, port)
  write(sock, COMMAND_MODE) # enter command mode
  read(sock) # read off the response
  sock
end
prompt() click to toggle source
# File lib/wifly/connection.rb, line 65
def prompt
  # 2.32
  # 3.2.23
  /<[0-9]{1,}\.[0-9]{1,}(\.[0-9]{1,})?>/
end
read(sock) click to toggle source
# File lib/wifly/connection.rb, line 39
def read(sock)
  result = ''
  begin
    result = sock.read_nonblock(1024)
  # connection lost somehow
  rescue Errno::ECONNRESET, Errno::EPIPE, IOError
    initialize_socket
    read(socket)
  # No more data on socket
  rescue Errno::EAGAIN
    retry
  rescue EOFError => e
    # ain't nothin left on socket.
  end
  result.strip
end
write(sock, str) click to toggle source
# File lib/wifly/connection.rb, line 56
def write(sock, str)
  begin
    sock.write(str)
  rescue Errno::EPIPE, IOError
    initialize_socket
    write(socket, str)
  end
end