Can I stop Linux from listening to a USB input device as a keyboard, but still capture events with a program?

I have a USB barcode scanner at /dev/input/event0 (/dev/input/by-id/usb-Metrologic_Metrologic_Scanner-event-kbd), and scanning a barcode causes it to send keypress events. I’m capturing these keypresses using the libdevinput Ruby library, which works great. The issue is that each barcode is also entered as a username, and subsequently a password on the Raspberry Pi, causing lots of failed login attempts. (The Raspberry Pi will be headless, and inside a microwave.)

How can I stop Linux from seeing the barcode scanner as an input device, and have my program be the sole event consumer? Or is there a different, better solution?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I found out that I need to send an EVIOCGRAB ioctl to the device, which grabs it for exclusive use.

Here’s how to do it in Ruby:

#!/usr/bin/env ruby
BARCODE_SCANNER = "/dev/input/by-id/usb-Metrologic_Metrologic_Scanner-event-kbd"

require 'rubygems'
require 'libdevinput'
require 'ffi'
require 'ffi/tools/const_generator'

# We need access to the file
DevInput.class_eval { attr_reader :dev }

# Look up value of EVIOCGRAB constant
cg = FFI::ConstGenerator.new('input') do |gen|
  gen.include('linux/input.h')
  gen.const(:EVIOCGRAB, '%u', '(unsigned)')
end
EVIOCGRAB = cg['EVIOCGRAB'].to_i

scanner = DevInput.new(BARCODE_SCANNER)
# Send EVIOCGRAB to scanner, which grabs it for exclusive use by our process
scanner.dev.ioctl(EVIOCGRAB, 1)


puts "Waiting for events..."
scanner.each do |event|
  # Ignore everything except key press events
  next unless event.type == 1 && event.value == 1
  puts "Key: #{event.code_str}"
end

Note: You’ll need to install the libdevinput gem, ffi, and Linux headers. If you are using a Linux version between 3.2.0 and 3.6.11, you can replace the FFI::ConstGenerator part with EVIOCGRAB = 1074021776, and then you don’t need ffi or Linux headers.

Method 2

Sounds somehow similar to this issue, so I’d try this solution : if I understand correctly your problem, the barcode scanner should appear as a slave pointer of “Virtual core keyboard” when you do

xinput --list

Then maybe getting its ID and forcing it to float could help :
xinput float <id>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments