Class: Lignite::Connection::Bluetooth

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

Overview

A Lignite::Connection over Bluetooth

Constant Summary collapse

AF_BLUETOOTH =
31
BTPROTO_RFCOMM =
3

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lignite::Connection

create, #receive, reset, #send

Methods included from Logger

default_logger, #logger

Methods included from Bytes

#bin_to_hex, #f32, #hex_to_bin, #u16, #u32, #u8, #unpack_f32, #unpack_u16, #unpack_u32, #unpack_u8

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”



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

def initialize(address = address_from_file)
  super()
  @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



28
29
30
# File 'lib/lignite/connection/bluetooth.rb', line 28

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

.template_config_filenameObject



32
33
34
35
# File 'lib/lignite/connection/bluetooth.rb', line 32

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



37
38
39
40
# File 'lib/lignite/connection/bluetooth.rb', line 37

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

#closeObject



50
51
52
53
# File 'lib/lignite/connection/bluetooth.rb', line 50

def close
  @sock.shutdown
  super
end

#read(n) ⇒ Object



42
43
44
# File 'lib/lignite/connection/bluetooth.rb', line 42

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

#write(s) ⇒ Object



46
47
48
# File 'lib/lignite/connection/bluetooth.rb', line 46

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