`
songgz
  • 浏览: 39052 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

通过Ruby在Windows中访问USB接口

 
阅读更多
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*")
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics