Send data in hex using the parameter dataOut
larskanis opened this issue · 3 comments
Asked by Simone per Email:
I'm trying to use the 'libusb' gem in Ruby under Windows 7. I can connect to the device but when I try to send the command to the device I get the following error:
C:\>ruby rubyusb2.rb
C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/libusb-0.6.2-x86-mingw32/li
b/libusb/transfer.rb:76:in `buffer=': undefined method `bytesize' for 131072:Fix
num (NoMethodError)
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/libusb-0.6.2-x
86-mingw32/lib/libusb/dev_handle.rb:460:in `interrupt_transfer'
from rubyusb2.rb:18:in `<main>'
This is my code:
require "libusb"
usb = LIBUSB::Context.new
device = usb.devices(idVendor: 0x0452, idProduct: 0xFFFF).first
handle = device.open
begin
handle.claim_interface(0)
rescue LIBUSB::ERROR_BUSY
handle.detach_kernel_driver(0)
handle.claim_interface(0)
end
handle.interrupt_transfer(endpoint: 0x02, dataOut: 0x020000)
handle.close
If I enter a string (es. "02") instead of a hexadecimal parameter in the :dataOut parameter, there are no problems. There is a way to send directly data in hex using the parameter: dataOut?
There is a way to send directly data in hex using the parameter: dataOut?
Not directly. However this is what Array#pack is made for. Use it to build binary data strings from Integer or from Hex strings like so:
[0x42, 0x456547, "abcd"].pack("CNH*")
=> "B\x00EeG\xAB\xCD"
For the opposite direction (reception of data) it's best to use String.unpack, which has the exact opposite semantics:
"B\x00EeG\xAB\xCD".unpack("CNH*")
=> [66, 4547911, "abcd"]
So your code could look like this (for little endian byte order):
handle.interrupt_transfer(endpoint: 0x02, dataOut: [0x020000].pack("V"))
This is the solution I was looking for. Thank you so much.
OK, thanks for responding!