require 'ffi'
module HidApi
extend FFI::Library
ffi_lib 'hidapi'
attach_function :hid_open, [:int, :int, :int], :pointer
attach_function :hid_write, [:pointer, :pointer, :int], :int
attach_function :hid_read_timeout, [:pointer, :pointer, :int, :int], :int
attach_function :hid_close, [:pointer], :void
REPORT_SIZE = 65 # 64 bytes + 1 byte for report type
def self.pad_to_report_size(bytes)
(bytes+[0]*(REPORT_SIZE-bytes.size)).pack("C*")
end
end
# USAGE
# CONNECT
vendor_id = 1234
product_id = 65432
serial_number = 0
device = HidApi.hid_open(vendor_id, product_id, serial_number)
# SEND
command_to_send = HidApi.pad_to_report_size([0]+ARGV.map(&:hex)).pack("C*")
res = HidApi.hid_write dev, command_to_send, HidApi::REPORT_SIZE
raise "command write failed" if res <= 0
# READ
buffer = FFI::Buffer.new(:char, HidApi::REPORT_SIZE)
res = HidApi.hid_read_timeout device, buffer, HidApi::REPORT_SIZE, 1000
raise "command read failed" if res <= 0
p buffer.read_bytes(HidApi::REPORT_SIZE).unpack("C*")
通过Ruby在Windows中访问USB接口
最新推荐文章于 2024-09-23 17:45:48 发布