rickhull/device_input

View on GitHub
bin/evdump

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby

require 'device_input'
require 'slop'

opts = Slop.parse do |o|
  o.banner = "evdump [OPTIONS] [DEVICE]"
  o.string '-p', '--print', 'pretty|raw|hex|off'
  o.int '-d', '--duration', 'number of seconds to read input [inf]'
  o.int '-c', '--count', 'number of events to read [inf]'
  o.on '-h', '--help' do
    puts o
    exit
  end
end

def opts.error(msg = nil)
  puts self
  puts "\nERROR: #{msg}" if msg
  exit 1
end

case opts[:print]
when 'off'
  print_meth = nil
when 'pretty', 'raw', 'hex'
  print_meth = opts[:print]
else
  print_meth = 'to_s'
end

if $stdin.tty?
  device = opts.arguments.shift
  opts.error "Please specify an input device file" unless device
  opts.error "#{device} is not a character device" unless File.chardev? device
  opts.error "#{device} is not readable" unless File.readable? device
  device = File.new(device, 'r')
else
  device = $stdin
end

start = Time.now
duration = opts[:duration]
count = 0
max = opts[:count]

DeviceInput.read_loop(device) { |event|
  puts event.send(print_meth) if print_meth
  if max
    count += 1
    break if count >= max
  end
  break if duration and Time.now - start > duration
}