Skip to content

Instantly share code, notes, and snippets.

@cho45
Created October 6, 2019 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cho45/69cb0f6a65334df98a933a7a8e96ffc4 to your computer and use it in GitHub Desktop.
Save cho45/69cb0f6a65334df98a933a7a8e96ffc4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "hid_api" # gem install hid_api
require "pp"
COMMAND_READ_ALL = 0xf2
COMMAND_VERSION = 0xf9
COMMAND_READ_COUNTER = 0xe3
COMMAND_INITIAL_CALIB = 0xdb
COMMAND_PRESS_CALIB = 0xdd
#COMMAND_WRITE_ALL = 0x00
device = HidApi.open(0x0483, 0x512A)
def device.writex(command)
report_id = 0x00
buf = [0] * 64
buf[1] = command
self.write([report_id] + buf)
end
# monkey patch for hid_api. hid_api ignores timeout error
def device.read_timeout(length, timeout)
buffer = clear_buffer length
with_hid_error_handling do
ret = HidApi.hid_read_timeout self, buffer, buffer.length, timeout
if ret.zero?
raise HidApi::HidError, "timeout"
end
# -1 is treated by hid_api
ret
end
buffer
end
# get version
device.writex(COMMAND_VERSION)
bytes = device.read_timeout(64, 100).get_bytes(0, 64)
p bytes.unpack("cCA*")
device.writex(COMMAND_READ_ALL)
keymap = {}
loop do # expect 66 * 3 (layers) = 198 count
bytes = device.read_timeout(64, 100).get_bytes(0, 64)
break if bytes[0] != "\x00"
# report_id 0xf0 level key_id
# puts bytes.unpack("cCC*").map {|i| "%02x" % i }.join(" ")
report_id, command, level, key_id, _unknown, hwcode, *rest = *bytes.unpack("cCCCa2CC*")
(keymap[level-1] ||= {})[key_id] = hwcode
puts "l=%d, key=% 3d hwcode=% 4d %p %s " % [level-1, key_id, hwcode, _unknown, rest.map {|i| "%02x" % i }.join(" ")]
end
pp keymap
device.writex(COMMAND_READ_COUNTER)
all_counts = []
loop do
bytes = device.read_timeout(64, 100).get_bytes(0, 64)
break if bytes[0] != "\x00"
report_id, command, _unknown, *counts = *bytes.unpack("cCCV*")
all_counts.concat(counts)
end
all_counts.each_with_index do |count, i|
chr = keymap[0][i] || 0
puts "key=% 3d hwcode=% 4d % 5s: %d" % [i, chr, chr ? chr.chr.dump : "", count]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment