我必须从usb设备TEMPer恢复温度值,然后我在blogpost找到了代码:
import java.io.IOException;
import org.apache.log4j.Logger;
import com.codeminders.hidapi.HIDDevice;
import com.codeminders.hidapi.HIDManager;
public class Foo {
static final int VENDOR_ID = 3141;
static final int PRODUCT_ID = 29697;
static final int BUFSIZE = 2048;
static final long READ_UPDATE_DELAY_MS = 1000;
public static String myTemperature = "0.00";
private static Logger log = Logger.getLogger(Foo.class.getName());
static float raw_to_c(final int rawtemp) {
final float temp_c = rawtemp * (125.f / 32000.f);
return temp_c;
}
static float c_to_u(final float deg_c, final char unit) {
if (unit == 'F') {
return (deg_c * 1.8f) + 32.f;
} else if (unit == 'K') {
return (deg_c + 273.15f);
} else {
return deg_c;
}
}
public static void readDevice(final int vendorId, final int productId) {
System.out.println("In readDevice");
final HIDDevice dev;
try {
final HIDManager hid_mgr = HIDManager.getInstance();
log.debug("vendorId =" +vendorId + " productID =" + productId);
dev = hid_mgr.openById(vendorId, productId, null);
final byte[] temp = new byte[] { (byte) 0x01, (byte) 0x80, (byte) 0x33, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
final int res = dev.write(temp);
try {
final byte[] buf = new byte[BUFSIZE];
final int n = dev.read(buf);
int rawtemp = (buf[3] & (byte) 0xFF) + (buf[2] << 8);
if ((buf[2] & 0x80) != 0) {
/* return the negative of magnitude of the temperature */
rawtemp = -((rawtemp ^ 0xffff) + 1);
}
System.out.println("temp = " + c_to_u(raw_to_c(rawtemp), 'C'));
myTemperature = Float.toString( c_to_u(raw_to_c(rawtemp), 'C'));
try {
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch (final InterruptedException e) {
e.printStackTrace();
}
} finally {
dev.close();
hid_mgr.release();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
我的类返回此错误代码:
com.codeminders.hidapi.HIDDeviceNotFoundException 在com.codeminders.hidapi.HIDManager.openById(HIDManager.java:114) 在Foo.readTemperature(Foo.java:44) 在StartApplication.main(StartApplication.java:96)
我已经验证了我的USB探测器是否是HID设备,是的。
找到解决方案! ==&GT;这是我的Linux,除了经典的存储密钥之外,它没有看到usb设备。所以现在它正在运作!
我现在遇到第二个问题,在这段代码中,我从未在
之后传递 int n = dev.read(buf);
这条线对于取得好成绩至关重要。对于我来说,使用字节操作并不容易......
找到解决方案n°2! ==&GT;我需要的是在写入和读取之前添加以下行:
dev.disableBlocking();
我认为最后一个问题:当我这样做时,我没有读取任何字节:
int n = dev.read(buf);
n始终等于0 ...