Created
May 1, 2016 13:58
-
-
Save ryotarai/eb00695655feb3a05839fd83aeb524ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ffi' | |
vendor_id = 3141 | |
product_id = 29697 | |
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 | |
end | |
device = nil | |
10.times do | |
device = HidApi.hid_open(vendor_id, product_id, 0) | |
unless device.address == 0 | |
break | |
end | |
end | |
if device.address == 0 | |
raise 'Failed to get device handler after 10 retries' | |
end | |
res = HidApi.hid_write(device, [0x01, 0x80, 0x33, 0x01, 0x00, 0x00, 0x00, 0x00].pack('C*'), 8) | |
raise "Command write failed" if res <= 0 | |
buffer = FFI::Buffer.new(:char, 4) | |
res = HidApi.hid_read_timeout(device, buffer, 4, 1000) | |
raise "Command read failed" if res <= 0 | |
data = buffer.read_bytes(4).unpack("C*") | |
rawtemp = (data[3] & 0xff) + (data[2] << 8) | |
if (data[2] & 0x80) != 0 | |
rawtemp = -((rawtemp ^ 0xffff) + 1) | |
end | |
temp_c = rawtemp * (125.0 / 32000.0) | |
puts temp_c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment