Sha256: 7a425c92b9bb33d7bbb32d8b27fe1e2f0e425ee330a8218798fc1b12935a573d

Contents?: true

Size: 995 Bytes

Versions: 1

Compression:

Stored size: 995 Bytes

Contents

require "socket"

module Lignite
  class Connection
    class Bluetooth < Connection
      AF_BLUETOOTH = 31
      BTPROTO_RFCOMM = 3

      # @param address [String] "11:22:33:44:55:66"
      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": BT is disabled;
        #   use `hciconfig hci0 up`
        # "Errno::EHOSTDOWN: Host is down": Turn the brick on, enable BT
        @sock.connect(sockaddr)
      end

      def address_from_file
        fn = "#{ENV['HOME']}/.config/lignite-btaddr"
        s = File.read(fn)
        s.lines.grep(/^[0-9a-fA-F]/).first.strip
      end

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lignite-0.1.0 lib/lignite/connection/bluetooth.rb