Class: Lignite::Connection::Bluetooth

Inherits:
Lignite::Connection show all
Defined in:
lib/lignite/connection/bluetooth.rb

Constant Summary collapse

AF_BLUETOOTH =
31
BTPROTO_RFCOMM =
3

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lignite::Connection

create

Constructor Details

#initialize(address = address_from_file) ⇒ Bluetooth

Returns a new instance of Bluetooth.

Parameters:

  • address (String) (defaults to: address_from_file)

    “11:22:33:44:55:66”



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/lignite/connection/bluetooth.rb', line 10

def initialize(address = address_from_file)
  @sock = Socket.new(AF_BLUETOOTH, :STREAM, BTPROTO_RFCOMM)
  addr_b = address.split(/:/).map { |x| x.to_i(16) }
  channel = 1
  sockaddr = [AF_BLUETOOTH, 0, *addr_b.reverse, channel, 0].pack("C*")
  # common exceptions:
  # "Errno::EHOSTUNREACH: No route to host":
  #   - No BT adapter
  #   - BT is disabled; use `hciconfig hci0 up`
  # "Errno::EHOSTDOWN: Host is down":
  #   - Turn the brick on
  #   - enable BT on the brick
  #   - disconnect other programming apps
  @sock.connect(sockaddr)
end

Class Method Details

.config_filenameObject



26
27
28
# File 'lib/lignite/connection/bluetooth.rb', line 26

def self.config_filename
  "#{ENV['HOME']}/.config/lignite-btaddr"
end

.template_config_filenameObject



30
31
32
33
# File 'lib/lignite/connection/bluetooth.rb', line 30

def self.template_config_filename
  # TODO: also find it from a gem
  File.expand_path("../../../../data/lignite-btaddr", __FILE__)
end

Instance Method Details

#address_from_fileObject



35
36
37
38
# File 'lib/lignite/connection/bluetooth.rb', line 35

def address_from_file
  s = File.read(self.class.config_filename)
  s.lines.grep(/^[0-9a-fA-F]/).first.strip
end

#read(n) ⇒ Object



40
41
42
# File 'lib/lignite/connection/bluetooth.rb', line 40

def read(n)
  @sock.recv(n)
end

#write(s) ⇒ Object



44
45
46
# File 'lib/lignite/connection/bluetooth.rb', line 44

def write(s)
  @sock.write(s)
end