2015年11月18日 星期三

[Java]透過Java hidAPI來取得usb裝置資訊

his is JNI wrapper around C/C++ HIDAPI library providing simple java API to work with devices such as USB gamepads, joysticks, keyboards, mice on Mac, Linux and Windows.

它是一個將C/C++ HID API library 透過JNI包裝成JAVA可以使用的API,

並且可以在Mac , Linux以及Windows上運作,可以偵測的裝置例如

遊戲搖桿,鍵盤, 滑鼠等等。


首先下載Java HidAPI

https://code.google.com/p/javahidapi/downloads/list

將jar檔加入專案,撰寫以下程式碼


import com.codeminders.hidapi.HIDDeviceInfo;
import com.codeminders.hidapi.HIDManager;
public class JavaApplication37 {

 
    
    public JavaApplication37()
    {
     
    }
    public static void main(String[] args) {

      try {
            com.codeminders.hidapi.ClassPathLibraryLoader.loadNativeHIDLibrary();
            HIDManager hidManager = HIDManager.getInstance();
            HIDDeviceInfo[] infos = hidManager.listDevices();
            for (HIDDeviceInfo info : infos) {
                System.out.println("info: " + info.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

輸出結果如下

info: HIDDeviceInfo [path=USB_05ac_8242_0x7fab6b40fc50, vendor_id=1452, product_id=33346, serial_number=, release_number=256, manufacturer_string=Apple, Inc., product_string=Apple IR, usage_page=12, usage=1, interface_number=-1]

info: HIDDeviceInfo [path=USB_046d_c52b_0x7fab6b623d40, vendor_id=1133, product_id=50475, serial_number=, release_number=9216, manufacturer_string=Logitech, product_string=USB Receiver, usage_page=1, usage=6, interface_number=-1]

info: HIDDeviceInfo [path=, vendor_id=0, product_id=0, serial_number=, release_number=0, manufacturer_string=, product_string=Apple Mikey HID Driver, usage_page=12, usage=1, interface_number=-1]

info: HIDDeviceInfo [path=USB_046d_c52b_0x7fab6b622cb0, vendor_id=1133, product_id=50475, serial_number=, release_number=9216, manufacturer_string=Logitech, product_string=USB Receiver, usage_page=65280, usage=1, interface_number=-1]

info: HIDDeviceInfo [path=USB_046d_c52b_0x7fab6b623490, vendor_id=1133, product_id=50475, serial_number=, release_number=9216, manufacturer_string=Logitech, product_string=USB Receiver, usage_page=1, usage=2, interface_number=-1]


環境:

OS X 10.10

java version "1.8.0_40-ea"

Netbeans  IDE 8.0.1

沒有留言:

張貼留言