Class: RubyBuzz::Device

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_buzz/device.rb

Overview

The main interface for the Buzz controllers. Primarily used to monitor key pushes and trigger events. Keep a single instance of the class:

‘RubyBuzz::Device.new`

The ‘each` method exposes events directly as they come in

‘device.each { |event| puts event }`

The ‘start_watching` method starts a background job which runs the events bound to each button via the RubyBuzz::Button class. You can end this worker with `stop_watching`.

Defined Under Namespace

Classes: Event

Constant Summary collapse

DEFAULT_FILE_NAME =
"/dev/input/by-id/usb-Logitech_Logitech_Buzz_tm__Controller_V1-event-if00"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = nil) ⇒ Device

Initialise device, getting event file from /dev/input/by-id/

You can override this to a different event, but ruby-buzz only supports a single usb controller.



49
50
51
52
53
54
55
# File 'lib/ruby_buzz/device.rb', line 49

def initialize(filename=nil)
  @dev = File.open(filename || DEFAULT_FILE_NAME)
  @block_size = 24
rescue Errno::ENOENT => er
  puts "Could not find device: are your controllers plugged in?"
  raise er
end

Instance Attribute Details

#workerObject

The worker is a thread which is watching the device



22
23
24
# File 'lib/ruby_buzz/device.rb', line 22

def worker
  @worker
end

Instance Method Details

#eachObject

Expose each event to a block of code as it comes in.



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ruby_buzz/device.rb', line 75

def each
  begin
    loop do
      event = read
      next unless event.type == 1
      next unless event.value == 1
      yield event
    end
  rescue Errno::ENODEV
  end
end

#formatObject

The format for each 24 bit data chunk taken from the event stream.



60
61
62
# File 'lib/ruby_buzz/device.rb', line 60

def format
  'qqSSl'
end

#readObject

Read a single 24-bit block.



67
68
69
70
# File 'lib/ruby_buzz/device.rb', line 67

def read
  bin = @dev.read @block_size
  Event.new *bin.unpack(format)
end

#start_watchingObject

Start a background worker which scans input file and triggers any events bound to each one.



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/ruby_buzz/device.rb', line 91

def start_watching
  return if @worker
  @worker = Thread.new do
    loop do
      event = read
      next unless event.type == 1
      next unless event.value == 1
      RubyBuzz::Button.trigger_key(event.code)
    end
  end
end

#stop_watchingObject

Stop the background worker, release it’s resources.



106
107
108
109
# File 'lib/ruby_buzz/device.rb', line 106

def stop_watching
  @worker.kill
  @worker = nil
end